Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add wall unread indicators

Anand Baburajanead92790f99f
diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rs
index ae9c9c2c41..c2f7b0d1a3 100644
--- a/rust/wall/src/client.rs
+++ b/rust/wall/src/client.rs
@@ -17,13 +17,14 @@ use crate::transport::{
CreatePostRequest, CreatePostResponse, CreateWallRequest, EntityKeyPayload, EntityKeyResponse,
FriendRelationshipResponse, FriendShareResponse, FriendStatusResponse, FriendTargetPayload,
LikeMessageRequest, LikeMessageResponse, LikePostRequest, LikePostResponse,
- ListPostLikersResponse, MessageConversationPage, MessagePage, MessageResponse,
- PostObjectPayload, PostPage, PostResponse, PresignUploadRequest, PresignUploadResponse,
- ProfileAvatarPayload, RefreshFriendSharesRequest, RotateWallKeyRequest, ShareUpdatePayload,
- UpdatePostCaptionRequest, UpdateWallProfileRequest, UpdateWallProfileResponse,
- UpdateWallSlugRequest, WallActorResponse, WallFriendResponse, WallKeyResponse,
- WallKeyVersionResponse, WallLinkCreateRequest, WallLinkLoginRequest, WallLinkLoginResponse,
- WallLinkStatusResponse, WallLookupResponse, WallProfileResponse,
+ ListPostLikersResponse, MarkFeedReadRequest, MarkNotificationsReadRequest,
+ MessageConversationPage, MessagePage, MessageResponse, PostObjectPayload, PostPage,
+ PostResponse, PresignUploadRequest, PresignUploadResponse, ProfileAvatarPayload,
+ RefreshFriendSharesRequest, RotateWallKeyRequest, ShareUpdatePayload, UpdatePostCaptionRequest,
+ UpdateWallProfileRequest, UpdateWallProfileResponse, UpdateWallSlugRequest, WallActorResponse,
+ WallFriendResponse, WallKeyResponse, WallKeyVersionResponse, WallLinkCreateRequest,
+ WallLinkLoginRequest, WallLinkLoginResponse, WallLinkStatusResponse, WallLookupResponse,
+ WallProfileResponse, WallUnreadStatusResponse,
};
use ente_core::crypto::{sealed, secretbox};
use ente_core::http::{Error as HttpError, HttpClient, HttpConfig};
@@ -624,6 +625,40 @@ impl AccountWallCtx {
.map_err(Into::into)
}
+ pub async fn unread_status(&self) -> Result<WallUnreadStatusResponse> {
+ self.client
+ .get_json("/wall/unread", &[])
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn mark_feed_read(&self, post_id: i64) -> Result<WallUnreadStatusResponse> {
+ if post_id <= 0 {
+ return Err(WallError::InvalidInput("post id is required".into()));
+ }
+ self.client
+ .post_json("/wall/feed/read", &MarkFeedReadRequest { post_id })
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn mark_notifications_read(
+ &self,
+ friend_wall_id: impl Into<String>,
+ ) -> Result<WallUnreadStatusResponse> {
+ let friend_wall_id = friend_wall_id.into();
+ if friend_wall_id.trim().is_empty() {
+ return Err(WallError::InvalidInput("friend wall id is required".into()));
+ }
+ self.client
+ .post_json(
+ "/wall/messages/read",
+ &MarkNotificationsReadRequest { friend_wall_id },
+ )
+ .await
+ .map_err(Into::into)
+ }
+
pub async fn get_post(&self, post_id: i64) -> Result<PostResponse> {
let path = format!("/wall/posts/{post_id}");
self.client.get_json(&path, &[]).await.map_err(Into::into)
@@ -1192,6 +1227,7 @@ fn post_response_from_feed_item(item: &FeedItem) -> PostResponse {
created_at: item.created_at.clone(),
likes: item.likes,
viewer_liked: item.viewer_liked,
+ viewer_unread: item.viewer_unread,
}
}
@@ -1838,6 +1874,7 @@ mod tests {
created_at: "2026-04-16T00:00:00Z".to_owned(),
likes: 0,
viewer_liked: false,
+ viewer_unread: false,
};
let decrypted = ctx
@@ -2422,6 +2459,55 @@ mod tests {
like.assert_async().await;
}
+ #[tokio::test]
+ async fn unread_methods_use_read_marker_endpoints() {
+ let mut server = Server::new_async().await;
+ let ctx = test_account_ctx(&server.url());
+ let status = server
+ .mock("GET", "/wall/unread")
+ .match_header("x-auth-token", "token")
+ .with_status(200)
+ .with_body(json!({"feedUnread": true, "notificationsUnread": false}).to_string())
+ .create_async()
+ .await;
+ let feed_read = server
+ .mock("POST", "/wall/feed/read")
+ .match_header("x-auth-token", "token")
+ .match_body(Matcher::JsonString(json!({"postId": 42}).to_string()))
+ .with_status(200)
+ .with_body(json!({"feedUnread": false, "notificationsUnread": false}).to_string())
+ .create_async()
+ .await;
+ let notifications_read = server
+ .mock("POST", "/wall/messages/read")
+ .match_header("x-auth-token", "token")
+ .match_body(Matcher::JsonString(
+ json!({"friendWallId": "wall_friend"}).to_string(),
+ ))
+ .with_status(200)
+ .with_body(json!({"feedUnread": false, "notificationsUnread": false}).to_string())
+ .create_async()
+ .await;
+
+ let unread = ctx
+ .unread_status()
+ .await
+ .expect("unread status should load");
+ assert!(unread.feed_unread);
+ assert!(!unread.notifications_unread);
+ assert!(!ctx.mark_feed_read(42).await.expect("feed read").feed_unread);
+ assert!(
+ !ctx.mark_notifications_read("wall_friend")
+ .await
+ .expect("notifications read")
+ .notifications_unread
+ );
+
+ status.assert_async().await;
+ feed_read.assert_async().await;
+ notifications_read.assert_async().await;
+ }
+
#[tokio::test]
async fn message_actions_use_message_endpoints() {
let mut server = Server::new_async().await;
diff --git a/rust/wall/src/lib.rs b/rust/wall/src/lib.rs
index 4b3cafcbb0..f401aaa99f 100644
--- a/rust/wall/src/lib.rs
+++ b/rust/wall/src/lib.rs
@@ -18,5 +18,5 @@ pub use transport::{
MessageResponse, PostLikerResponse, PostObjectPayload, PostPage, PostResponse,
PresignUploadResponse, ProfileAvatarPayload, ProfileAvatarResponse, WallActorResponse,
WallFriendResponse, WallKeyResponse, WallKeyVersionResponse, WallLinkLoginResponse,
- WallLinkStatusResponse, WallLookupResponse, WallProfileResponse,
+ WallLinkStatusResponse, WallLookupResponse, WallProfileResponse, WallUnreadStatusResponse,
};
diff --git a/rust/wall/src/models.rs b/rust/wall/src/models.rs
index f701202322..bef8c086e1 100644
--- a/rust/wall/src/models.rs
+++ b/rust/wall/src/models.rs
@@ -139,6 +139,8 @@ pub struct FeedItem {
pub created_at: String,
pub likes: i64,
pub viewer_liked: bool,
+ #[serde(default)]
+ pub viewer_unread: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
diff --git a/rust/wall/src/transport.rs b/rust/wall/src/transport.rs
index 7d2a7549dd..7396a3dcbc 100644
--- a/rust/wall/src/transport.rs
+++ b/rust/wall/src/transport.rs
@@ -128,6 +128,25 @@ pub struct LikePostResponse {
pub liked: bool,
}
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MarkFeedReadRequest {
+ pub post_id: i64,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MarkNotificationsReadRequest {
+ pub friend_wall_id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WallUnreadStatusResponse {
+ pub feed_unread: bool,
+ pub notifications_unread: bool,
+}
+
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LikeMessageRequest {
@@ -189,6 +208,8 @@ pub struct MessagePage {
pub struct MessageConversationResponse {
pub friend: WallActorResponse,
pub latest_activity: MessageConversationActivity,
+ #[serde(default)]
+ pub unread: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -249,6 +270,8 @@ pub struct PostResponse {
pub created_at: String,
pub likes: i64,
pub viewer_liked: bool,
+ #[serde(default)]
+ pub viewer_unread: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/server/migrations/121_wall.down.sql b/server/migrations/121_wall.down.sql
index d97f9cb195..7228f7217c 100644
--- a/server/migrations/121_wall.down.sql
+++ b/server/migrations/121_wall.down.sql
@@ -24,5 +24,11 @@ DROP TABLE IF EXISTS wall_posts;
DROP TABLE IF EXISTS wall_key_versions;
+DROP TRIGGER IF EXISTS update_wall_notification_read_markers_updated_at ON wall_notification_read_markers;
+DROP TABLE IF EXISTS wall_notification_read_markers;
+
+DROP TRIGGER IF EXISTS update_wall_read_markers_updated_at ON wall_read_markers;
+DROP TABLE IF EXISTS wall_read_markers;
+
DROP TRIGGER IF EXISTS update_walls_updated_at ON walls;
DROP TABLE IF EXISTS walls;
diff --git a/server/migrations/121_wall.up.sql b/server/migrations/121_wall.up.sql
index 858f868769..dea1ec288b 100644
--- a/server/migrations/121_wall.up.sql
+++ b/server/migrations/121_wall.up.sql
@@ -22,6 +22,36 @@ CREATE TRIGGER update_walls_updated_at
FOR EACH ROW
EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
+CREATE TABLE IF NOT EXISTS wall_read_markers (
+ user_id BIGINT PRIMARY KEY REFERENCES users (user_id) ON DELETE CASCADE,
+ feed_read_created_at BIGINT NOT NULL DEFAULT 0,
+ feed_read_post_id BIGINT NOT NULL DEFAULT 0,
+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds()
+);
+
+CREATE TRIGGER update_wall_read_markers_updated_at
+ BEFORE UPDATE ON wall_read_markers
+ FOR EACH ROW
+EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
+
+CREATE TABLE IF NOT EXISTS wall_notification_read_markers (
+ user_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,
+ friend_wall_id TEXT NOT NULL REFERENCES walls (wall_id) ON DELETE CASCADE,
+ read_at BIGINT NOT NULL DEFAULT 0,
+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ PRIMARY KEY (user_id, friend_wall_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_wall_notification_read_markers_user
+ ON wall_notification_read_markers (user_id, read_at DESC);
+
+CREATE TRIGGER update_wall_notification_read_markers_updated_at
+ BEFORE UPDATE ON wall_notification_read_markers
+ FOR EACH ROW
+EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
+
CREATE TABLE IF NOT EXISTS wall_key_versions (
wall_id TEXT NOT NULL REFERENCES walls (wall_id) ON DELETE CASCADE,
version INTEGER NOT NULL,
diff --git a/server/wall/api/read_markers.go b/server/wall/api/read_markers.go
new file mode 100644
index 0000000000..7a6b2693e2
--- /dev/null
+++ b/server/wall/api/read_markers.go
@@ -0,0 +1,32 @@
+package api
+
+import (
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/wall/models"
+ "github.com/gin-gonic/gin"
+)
+
+func (h *Handlers) GetUnreadStatus(c *gin.Context) {
+ resp, err := h.Module.Read.GetUnreadStatus(c)
+ respondJSON(c, resp, err)
+}
+
+func (h *Handlers) MarkFeedRead(c *gin.Context) {
+ var req models.MarkFeedReadRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ respondJSON(c, nil, ente.ErrBadRequest)
+ return
+ }
+ resp, err := h.Module.Read.MarkFeedRead(c, req)
+ respondJSON(c, resp, err)
+}
+
+func (h *Handlers) MarkNotificationsRead(c *gin.Context) {
+ var req models.MarkNotificationsReadRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ respondJSON(c, nil, ente.ErrBadRequest)
+ return
+ }
+ resp, err := h.Module.Read.MarkNotificationsRead(c, req)
+ respondJSON(c, resp, err)
+}
diff --git a/server/wall/api/register.go b/server/wall/api/register.go
index 94dc166f34..e75ec0b1e6 100644
--- a/server/wall/api/register.go
+++ b/server/wall/api/register.go
@@ -9,6 +9,8 @@ func Register(privateAPI, publicAPI gin.IRoutes, handlers *Handlers) {
privateAPI.PUT("/wall/:wallID/slug", handlers.UpdateWallSlug)
privateAPI.PATCH("/wall/:wallID/slug", handlers.UpdateWallSlug)
privateAPI.POST("/wall/uploads/presign", handlers.PresignUpload)
+ privateAPI.GET("/wall/unread", handlers.GetUnreadStatus)
+ privateAPI.POST("/wall/feed/read", handlers.MarkFeedRead)
privateAPI.POST("/wall/posts", handlers.CreatePost)
privateAPI.GET("/wall/feed", handlers.ListFeed)
privateAPI.POST("/wall/posts/:postID/caption", handlers.UpdatePostCaption)
@@ -17,6 +19,7 @@ func Register(privateAPI, publicAPI gin.IRoutes, handlers *Handlers) {
privateAPI.POST("/wall/posts/:postID/reply", handlers.ReplyToPost)
privateAPI.DELETE("/wall/posts/:postID", handlers.DeletePost)
privateAPI.GET("/wall/messages", handlers.ListMessages)
+ privateAPI.POST("/wall/messages/read", handlers.MarkNotificationsRead)
privateAPI.GET("/wall/messages/:wallID", handlers.ListMessageThread)
privateAPI.POST("/wall/messages/:wallID", handlers.CreateMessage)
privateAPI.POST("/wall/message/:messageID/like", handlers.ToggleMessageLike)
diff --git a/server/wall/controller/helpers.go b/server/wall/controller/helpers.go
index 4de5fbadf5..b4c18f1911 100644
--- a/server/wall/controller/helpers.go
+++ b/server/wall/controller/helpers.go
@@ -148,6 +148,7 @@ func toPostResponse(post *wallrepo.WallPostRecord, assets []wallrepo.WallPostAss
CreatedAt: formatMicros(post.CreatedAt),
Likes: post.Likes,
ViewerLiked: post.ViewerLiked,
+ ViewerUnread: post.ViewerUnread,
}
if len(assets) > 0 {
resp.Objects = make([]models.PostObjectPayload, 0, len(assets))
diff --git a/server/wall/controller/messages.go b/server/wall/controller/messages.go
index 7da39e9047..834b392f90 100644
--- a/server/wall/controller/messages.go
+++ b/server/wall/controller/messages.go
@@ -19,11 +19,12 @@ const (
)
type MessagesController struct {
- MessagesRepo *repo.MessagesRepository
- PostsRepo *repo.PostsRepository
- WallsRepo *repo.WallsRepository
- FriendsRepo *repo.FriendsRepository
- auth authDeps
+ MessagesRepo *repo.MessagesRepository
+ PostsRepo *repo.PostsRepository
+ WallsRepo *repo.WallsRepository
+ FriendsRepo *repo.FriendsRepository
+ ReadMarkersRepo *repo.ReadMarkersRepository
+ auth authDeps
}
func (c *MessagesController) Create(ctx *gin.Context, targetWallID string, req models.CreateMessageRequest) (*models.MessageResponse, error) {
@@ -125,6 +126,7 @@ func (c *MessagesController) List(ctx *gin.Context, req models.ListMessagesReque
items = append(items, models.MessageConversationResponse{
Friend: toActorResponse(conversation.Friend, true),
LatestActivity: toMessageConversationActivityResponse(conversation.LatestActivity),
+ Unread: conversation.Unread,
})
}
return &models.MessageConversationPage{Items: items, NextCursor: nextCursor}, nil
diff --git a/server/wall/controller/module.go b/server/wall/controller/module.go
index 7a654863c9..fdc931b652 100644
--- a/server/wall/controller/module.go
+++ b/server/wall/controller/module.go
@@ -12,6 +12,7 @@ type Module struct {
Messages *MessagesController
Links *LinksController
Assets *AssetsController
+ Read *ReadMarkersController
Cleanup *CleanupController
UserAuth *baserepo.UserAuthRepository
}
@@ -25,11 +26,12 @@ func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository) *M
}
return &Module{
Walls: &WallsController{WallsRepo: repos.Walls, AssetsRepo: repos.Assets, auth: authDeps},
- Posts: &PostsController{PostsRepo: repos.Posts, WallsRepo: repos.Walls, AssetsRepo: repos.Assets, auth: authDeps},
+ Posts: &PostsController{PostsRepo: repos.Posts, WallsRepo: repos.Walls, AssetsRepo: repos.Assets, ReadMarkersRepo: repos.Read, auth: authDeps},
Friends: &FriendsController{FriendsRepo: repos.Friends, WallsRepo: repos.Walls, auth: authDeps},
- Messages: &MessagesController{MessagesRepo: repos.Messages, PostsRepo: repos.Posts, WallsRepo: repos.Walls, FriendsRepo: repos.Friends, auth: authDeps},
+ Messages: &MessagesController{MessagesRepo: repos.Messages, PostsRepo: repos.Posts, WallsRepo: repos.Walls, FriendsRepo: repos.Friends, ReadMarkersRepo: repos.Read, auth: authDeps},
Links: &LinksController{LinksRepo: repos.Links, WallsRepo: repos.Walls, auth: authDeps},
Assets: &AssetsController{AssetsRepo: repos.Assets, WallsRepo: repos.Walls, LinksRepo: repos.Links, auth: authDeps},
+ Read: &ReadMarkersController{ReadMarkersRepo: repos.Read, PostsRepo: repos.Posts, MessagesRepo: repos.Messages, auth: authDeps},
Cleanup: &CleanupController{AssetsRepo: repos.Assets},
UserAuth: userAuthRepo,
}
diff --git a/server/wall/controller/posts.go b/server/wall/controller/posts.go
index 83f8365a64..45fd05b1cd 100644
--- a/server/wall/controller/posts.go
+++ b/server/wall/controller/posts.go
@@ -14,10 +14,11 @@ import (
)
type PostsController struct {
- PostsRepo *repo.PostsRepository
- WallsRepo *repo.WallsRepository
- AssetsRepo *repo.AssetsRepository
- auth authDeps
+ PostsRepo *repo.PostsRepository
+ WallsRepo *repo.WallsRepository
+ AssetsRepo *repo.AssetsRepository
+ ReadMarkersRepo *repo.ReadMarkersRepository
+ auth authDeps
}
func (c *PostsController) Create(ctx *gin.Context, req models.CreatePostRequest) (*models.CreatePostResponse, error) {
@@ -109,7 +110,11 @@ func (c *PostsController) ListFeed(ctx *gin.Context, req models.ListFeedRequest)
if err != nil {
return nil, err
}
- posts, nextCursor, err := c.PostsRepo.ListFeed(ctx.Request.Context(), userID, req.Cursor, req.Limit)
+ marker, err := c.ReadMarkersRepo.Get(ctx.Request.Context(), userID)
+ if err != nil {
+ return nil, err
+ }
+ posts, nextCursor, err := c.PostsRepo.ListFeed(ctx.Request.Context(), userID, req.Cursor, req.Limit, marker.FeedReadCreatedAt, marker.FeedReadPostID)
if err != nil {
return nil, err
}
diff --git a/server/wall/controller/read_markers.go b/server/wall/controller/read_markers.go
new file mode 100644
index 0000000000..a5a47a092e
--- /dev/null
+++ b/server/wall/controller/read_markers.go
@@ -0,0 +1,85 @@
+package controller
+
+import (
+ "database/sql"
+ "errors"
+ "strings"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/wall/models"
+ "github.com/ente-io/museum/wall/repo"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+type ReadMarkersController struct {
+ ReadMarkersRepo *repo.ReadMarkersRepository
+ PostsRepo *repo.PostsRepository
+ MessagesRepo *repo.MessagesRepository
+ auth authDeps
+}
+
+func (c *ReadMarkersController) GetUnreadStatus(ctx *gin.Context) (*models.WallUnreadStatusResponse, error) {
+ userID, err := c.auth.requireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ marker, err := c.ReadMarkersRepo.Get(ctx.Request.Context(), userID)
+ if err != nil {
+ return nil, err
+ }
+ feedUnread, err := c.PostsRepo.HasUnreadFeed(ctx.Request.Context(), userID, marker.FeedReadCreatedAt, marker.FeedReadPostID)
+ if err != nil {
+ return nil, err
+ }
+ notificationsUnread, err := c.MessagesRepo.HasUnreadNotifications(ctx.Request.Context(), userID)
+ if err != nil {
+ return nil, err
+ }
+ return &models.WallUnreadStatusResponse{
+ FeedUnread: feedUnread,
+ NotificationsUnread: notificationsUnread,
+ }, nil
+}
+
+func (c *ReadMarkersController) MarkFeedRead(ctx *gin.Context, req models.MarkFeedReadRequest) (*models.WallUnreadStatusResponse, error) {
+ userID, err := c.auth.requireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if req.PostID <= 0 {
+ return nil, ente.NewBadRequestWithMessage("postId is required")
+ }
+ createdAt, postID, err := c.PostsRepo.GetFeedPostMarker(ctx.Request.Context(), userID, req.PostID)
+ if err != nil {
+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {
+ return nil, ente.ErrPermissionDenied
+ }
+ return nil, err
+ }
+ if err := c.ReadMarkersRepo.UpsertFeedReadMarker(ctx.Request.Context(), userID, createdAt, postID); err != nil {
+ return nil, err
+ }
+ return c.GetUnreadStatus(ctx)
+}
+
+func (c *ReadMarkersController) MarkNotificationsRead(ctx *gin.Context, req models.MarkNotificationsReadRequest) (*models.WallUnreadStatusResponse, error) {
+ userID, err := c.auth.requireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if strings.TrimSpace(req.FriendWallID) == "" {
+ return nil, ente.NewBadRequestWithMessage("friendWallId is required")
+ }
+ readAt, err := c.MessagesRepo.GetLatestConversationActivityAt(ctx.Request.Context(), userID, req.FriendWallID)
+ if err != nil {
+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {
+ return nil, ente.ErrPermissionDenied
+ }
+ return nil, err
+ }
+ if err := c.ReadMarkersRepo.UpsertNotificationReadMarker(ctx.Request.Context(), userID, req.FriendWallID, readAt); err != nil {
+ return nil, err
+ }
+ return c.GetUnreadStatus(ctx)
+}
diff --git a/server/wall/models/models.go b/server/wall/models/models.go
index 51bfd8dcc5..f7eba99bfe 100644
--- a/server/wall/models/models.go
+++ b/server/wall/models/models.go
@@ -303,6 +303,7 @@ type MessagePage struct {
type MessageConversationResponse struct {
Friend WallActorResponse `json:"friend"`
LatestActivity MessageConversationActivityResponse `json:"latestActivity"`
+ Unread bool `json:"unread"`
}
type MessageConversationActivityResponse struct {
@@ -350,6 +351,20 @@ type PostResponse struct {
CreatedAt string `json:"createdAt"`
Likes int64 `json:"likes"`
ViewerLiked bool `json:"viewerLiked"`
+ ViewerUnread bool `json:"viewerUnread"`
+}
+
+type WallUnreadStatusResponse struct {
+ FeedUnread bool `json:"feedUnread"`
+ NotificationsUnread bool `json:"notificationsUnread"`
+}
+
+type MarkFeedReadRequest struct {
+ PostID int64 `json:"postId"`
+}
+
+type MarkNotificationsReadRequest struct {
+ FriendWallID string `json:"friendWallId"`
}
type PostPage struct {
diff --git a/server/wall/repo/messages.go b/server/wall/repo/messages.go
index 31e52ba0cb..87c510bc49 100644
--- a/server/wall/repo/messages.go
+++ b/server/wall/repo/messages.go
@@ -205,7 +205,8 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
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_id
+ NULL::bigint AS post_id,
+ CASE WHEN m.recipient_id = $1 THEN m.created_at ELSE NULL::bigint END AS unread_created_at
FROM wall_messages m
WHERE (m.sender_id = $1 OR m.recipient_id = $1)
AND m.is_deleted = FALSE
@@ -219,7 +220,8 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
ml.created_at AS activity_created_at,
liker_wall.wall_id AS friend_wall_id,
m.message_id,
- NULL::bigint AS post_id
+ NULL::bigint AS post_id,
+ ml.created_at AS unread_created_at
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
@@ -269,7 +271,8 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
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
+ COALESCE(l.post_id, r.post_id) AS post_id,
+ GREATEST(COALESCE(l.liked_at, 0), COALESCE(r.replied_at, 0)) AS unread_created_at
FROM post_like_events l
FULL OUTER JOIN post_reply_events r
ON r.friend_wall_id = l.friend_wall_id
@@ -285,7 +288,8 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
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
+ NULL::bigint AS post_id,
+ fe.created_at AS unread_created_at
FROM wall_friend_events fe
WHERE fe.target_id = $1
AND fe.actor_id <> $1
@@ -307,9 +311,10 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
FROM candidates c
)
SELECT
- c.activity_type,
- c.activity_id,
- c.activity_created_at,
+ c.activity_type,
+ c.activity_id,
+ c.activity_created_at,
+ (c.unread_created_at IS NOT NULL AND c.unread_created_at > COALESCE(nrm.read_at, 0)) AS unread,
friend_wall.owner_id,
friend_wall.wall_id,
friend_wall.wall_slug,
@@ -374,8 +379,11 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
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
+ FROM ranked c
+ LEFT JOIN wall_notification_read_markers nrm
+ ON nrm.user_id = $1
+ AND nrm.friend_wall_id = c.friend_wall_id
+ 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
@@ -391,11 +399,11 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
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 DESC
- LIMIT $4
- `, viewerID, cursorCreatedAt, cursorID, limit+1)
+ 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 DESC
+ LIMIT $4
+ `, viewerID, cursorCreatedAt, cursorID, limit+1)
if err != nil {
return nil, "", stacktrace.Propagate(err, "")
}
@@ -419,6 +427,195 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
return out, nextCursor, nil
}
+func (r *MessagesRepository) GetLatestConversationActivityAt(ctx context.Context, viewerID int64, friendWallID string) (int64, error) {
+ var activityCreatedAt int64
+ if err := r.DB.QueryRowContext(ctx, `
+ WITH candidates AS (
+ SELECT
+ m.created_at AS activity_created_at,
+ 'message:' || m.message_id AS activity_id,
+ CASE WHEN m.sender_id = $1 THEN m.recipient_wall_id ELSE m.sender_wall_id END AS friend_wall_id
+ FROM wall_messages m
+ WHERE (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
+ ml.created_at AS activity_created_at,
+ 'message_like:' || ml.message_id || ':' || ml.user_id::text AS activity_id,
+ liker_wall.wall_id AS friend_wall_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
+
+ UNION ALL
+
+ SELECT
+ pl.created_at AS activity_created_at,
+ 'post_like:' || pl.post_id::text || ':' || pl.user_id::text AS activity_id,
+ actor_wall.wall_id AS friend_wall_id
+ 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
+
+ UNION ALL
+
+ SELECT
+ m.created_at AS activity_created_at,
+ 'post_reply:' || m.message_id AS activity_id,
+ m.sender_wall_id AS friend_wall_id
+ 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
+
+ UNION ALL
+
+ SELECT
+ fe.created_at AS activity_created_at,
+ 'friend_event:' || fe.event_id::text AS activity_id,
+ fe.actor_wall_id AS friend_wall_id
+ FROM wall_friend_events fe
+ WHERE fe.target_id = $1
+ AND fe.actor_id <> $1
+ )
+ SELECT c.activity_created_at
+ FROM candidates c
+ WHERE c.friend_wall_id = $2
+ ORDER BY c.activity_created_at DESC, c.activity_id DESC
+ LIMIT 1
+ `, viewerID, strings.TrimSpace(friendWallID)).Scan(&activityCreatedAt); err != nil {
+ return 0, stacktrace.Propagate(err, "")
+ }
+ return activityCreatedAt, nil
+}
+
+func (r *MessagesRepository) HasUnreadNotifications(ctx context.Context, viewerID int64) (bool, error) {
+ var exists bool
+ if err := r.DB.QueryRowContext(ctx, `
+ WITH message_candidates AS (
+ SELECT
+ m.created_at AS activity_created_at,
+ 'message:' || m.message_id AS activity_id,
+ CASE WHEN m.sender_id = $1 THEN m.recipient_wall_id ELSE m.sender_wall_id END AS friend_wall_id,
+ CASE WHEN m.recipient_id = $1 THEN m.created_at ELSE NULL::bigint END AS unread_created_at
+ FROM wall_messages m
+ WHERE (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
+ ml.created_at AS activity_created_at,
+ 'message_like:' || ml.message_id || ':' || ml.user_id::text AS activity_id,
+ liker_wall.wall_id AS friend_wall_id,
+ ml.created_at AS unread_created_at
+ 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.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
+ GREATEST(COALESCE(l.liked_at, 0), COALESCE(r.replied_at, 0)) AS activity_created_at,
+ 'post_activity:' || COALESCE(l.post_id, r.post_id)::text || ':' || COALESCE(l.friend_wall_id, r.friend_wall_id) AS activity_id,
+ COALESCE(l.friend_wall_id, r.friend_wall_id) AS friend_wall_id,
+ GREATEST(COALESCE(l.liked_at, 0), COALESCE(r.replied_at, 0)) AS unread_created_at
+ 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
+ fe.created_at AS activity_created_at,
+ 'friend_event:' || fe.event_id::text AS activity_id,
+ fe.actor_wall_id AS friend_wall_id,
+ fe.created_at AS unread_created_at
+ 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 EXISTS (
+ SELECT 1
+ FROM ranked c
+ LEFT JOIN wall_notification_read_markers nrm
+ ON nrm.user_id = $1
+ AND nrm.friend_wall_id = c.friend_wall_id
+ WHERE c.rn = 1
+ AND c.unread_created_at IS NOT NULL
+ AND c.unread_created_at > COALESCE(nrm.read_at, 0)
+ LIMIT 1
+ )
+ `, viewerID).Scan(&exists); err != nil {
+ return false, stacktrace.Propagate(err, "")
+ }
+ return exists, nil
+}
+
func sprintfWallMessageColumns(viewerPlaceholder string) string {
return strings.TrimSpace(strings.ReplaceAll(wallMessageSelectColumns, "%s", viewerPlaceholder))
}
@@ -459,6 +656,7 @@ func scanMessageConversationRecord(scanner interface{ Scan(dest ...any) error })
&rec.LatestActivity.Type,
&rec.LatestActivity.ID,
&rec.LatestActivity.CreatedAt,
+ &rec.Unread,
}
dest = append(dest, wallActorScanDest(&rec.Friend)...)
dest = append(dest,
diff --git a/server/wall/repo/module.go b/server/wall/repo/module.go
index 451d35e848..24ab2bd670 100644
--- a/server/wall/repo/module.go
+++ b/server/wall/repo/module.go
@@ -13,6 +13,7 @@ type Module struct {
Messages *MessagesRepository
Links *LinksRepository
Assets *AssetsRepository
+ Read *ReadMarkersRepository
}
type WallsRepository struct {
@@ -40,6 +41,10 @@ type AssetsRepository struct {
S3Config *s3config.S3Config
}
+type ReadMarkersRepository struct {
+ DB *sql.DB
+}
+
type WallRecord struct {
WallID string
OwnerID int64
@@ -75,6 +80,7 @@ type WallPostRecord struct {
CreatedAt int64
Likes int64
ViewerLiked bool
+ ViewerUnread bool
}
type WallPostAssetRecord struct {
@@ -131,6 +137,7 @@ type WallMessageRecord struct {
type WallMessageConversationRecord struct {
Friend WallActorRecord
LatestActivity WallMessageConversationActivityRecord
+ Unread bool
}
type WallMessageConversationActivityRecord struct {
@@ -232,6 +239,14 @@ type WallLinkSessionRecord struct {
EncryptedWallKey string
}
+type WallReadMarkerRecord struct {
+ UserID int64
+ FeedReadCreatedAt int64
+ FeedReadPostID int64
+ CreatedAt int64
+ UpdatedAt int64
+}
+
func NewModule(db *sql.DB, s3Config *s3config.S3Config) *Module {
return &Module{
Walls: &WallsRepository{DB: db},
@@ -240,5 +255,6 @@ func NewModule(db *sql.DB, s3Config *s3config.S3Config) *Module {
Messages: &MessagesRepository{DB: db},
Links: &LinksRepository{DB: db},
Assets: &AssetsRepository{DB: db, S3Config: s3Config},
+ Read: &ReadMarkersRepository{DB: db},
}
}
diff --git a/server/wall/repo/module_test.go b/server/wall/repo/module_test.go
index ca90910fd1..5ee7a877ad 100644
--- a/server/wall/repo/module_test.go
+++ b/server/wall/repo/module_test.go
@@ -1022,25 +1022,250 @@ func TestListFeedCursorUsesCreatedAtSortOrder(t *testing.T) {
setPostCreatedAt(t, module, 2000, second)
setPostCreatedAt(t, module, 1000, third)
- page, nextCursor, err := module.Posts.ListFeed(ctx, aliceID, "", 1)
+ page, nextCursor, err := module.Posts.ListFeed(ctx, aliceID, "", 1, 0, 0)
require.NoError(t, err)
require.Len(t, page, 1)
require.Equal(t, first, page[0].PostID)
require.Equal(t, "3000:"+strconv.FormatInt(first, 10), nextCursor)
- page, nextCursor, err = module.Posts.ListFeed(ctx, aliceID, nextCursor, 1)
+ page, nextCursor, err = module.Posts.ListFeed(ctx, aliceID, nextCursor, 1, 0, 0)
require.NoError(t, err)
require.Len(t, page, 1)
require.Equal(t, second, page[0].PostID)
require.Equal(t, "2000:"+strconv.FormatInt(second, 10), nextCursor)
- page, nextCursor, err = module.Posts.ListFeed(ctx, aliceID, nextCursor, 1)
+ page, nextCursor, err = module.Posts.ListFeed(ctx, aliceID, nextCursor, 1, 0, 0)
require.NoError(t, err)
require.Len(t, page, 1)
require.Equal(t, third, page[0].PostID)
require.Empty(t, nextCursor)
}
+func TestWallReadMarkersDriveUnreadState(t *testing.T) {
+ ctx := context.Background()
+ module := newWallTestModule(t)
+
+ aliceID := insertWallUser(t, module, "[email protected]", "alice-unread-public")
+ bobID := insertWallUser(t, module, "[email protected]", "bob-unread-public")
+ aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice-unread", "alice-wall-key", "alice-profile")
+ require.NoError(t, err)
+ bobWall, err := module.Walls.CreateWall(ctx, bobID, "bob-unread", "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, 500, "friend_add", bobID, aliceID)
+
+ postID, err := module.Posts.CreatePost(ctx, bobID, bobWall.WallID, "post-key", nil, bobWall.CurrentVersion, nil)
+ require.NoError(t, err)
+ setPostCreatedAt(t, module, 1000, postID)
+ feed, _, err := module.Posts.ListFeed(ctx, aliceID, "", 10, 0, 0)
+ require.NoError(t, err)
+ require.Len(t, feed, 1)
+ require.True(t, feed[0].ViewerUnread)
+ feedUnread, err := module.Posts.HasUnreadFeed(ctx, aliceID, 0, 0)
+ require.NoError(t, err)
+ require.True(t, feedUnread)
+
+ createdAt, markerPostID, err := module.Posts.GetFeedPostMarker(ctx, aliceID, postID)
+ require.NoError(t, err)
+ require.NoError(t, module.Read.UpsertFeedReadMarker(ctx, aliceID, createdAt, markerPostID))
+ marker, err := module.Read.Get(ctx, aliceID)
+ require.NoError(t, err)
+ feed, _, err = module.Posts.ListFeed(ctx, aliceID, "", 10, marker.FeedReadCreatedAt, marker.FeedReadPostID)
+ require.NoError(t, err)
+ require.False(t, feed[0].ViewerUnread)
+ feedUnread, err = module.Posts.HasUnreadFeed(ctx, aliceID, marker.FeedReadCreatedAt, marker.FeedReadPostID)
+ require.NoError(t, err)
+ require.False(t, feedUnread)
+
+ incoming, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{
+ Kind: "regular",
+ SenderID: bobID,
+ SenderWallID: bobWall.WallID,
+ RecipientID: aliceID,
+ RecipientWallID: aliceWall.WallID,
+ MessageCipher: "incoming-cipher",
+ SenderEncryptedMessageKey: "incoming-sender-key",
+ RecipientEncryptedMessageKey: "incoming-recipient-key",
+ })
+ require.NoError(t, err)
+ setMessageCreatedAt(t, module, 2000, incoming.MessageID)
+ conversations, _, err := module.Messages.ListConversations(ctx, aliceID, "", 10)
+ require.NoError(t, err)
+ require.Len(t, conversations, 1)
+ require.True(t, conversations[0].Unread)
+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID)
+ require.NoError(t, err)
+ require.True(t, notificationsUnread)
+
+ require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, bobWall.WallID, 2000))
+ conversations, _, err = module.Messages.ListConversations(ctx, aliceID, "", 10)
+ require.NoError(t, err)
+ require.False(t, conversations[0].Unread)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID)
+ require.NoError(t, err)
+ require.False(t, notificationsUnread)
+
+ outgoing, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{
+ Kind: "regular",
+ SenderID: aliceID,
+ SenderWallID: aliceWall.WallID,
+ RecipientID: bobID,
+ RecipientWallID: bobWall.WallID,
+ MessageCipher: "outgoing-cipher",
+ SenderEncryptedMessageKey: "outgoing-sender-key",
+ RecipientEncryptedMessageKey: "outgoing-recipient-key",
+ })
+ require.NoError(t, err)
+ setMessageCreatedAt(t, module, 3000, outgoing.MessageID)
+ conversations, _, err = module.Messages.ListConversations(ctx, aliceID, "", 10)
+ require.NoError(t, err)
+ require.Equal(t, outgoing.MessageID, conversations[0].LatestActivity.Message.MessageID)
+ require.False(t, conversations[0].Unread)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID)
+ require.NoError(t, err)
+ require.False(t, notificationsUnread)
+}
+
+func TestWallNotificationReadMarkersArePerFriend(t *testing.T) {
+ ctx := context.Background()
+ module := newWallTestModule(t)
+
+ aliceID := insertWallUser(t, module, "[email protected]", "alice-per-friend-public")
+ bobID := insertWallUser(t, module, "[email protected]", "bob-per-friend-public")
+ charlieID := insertWallUser(t, module, "[email protected]", "charlie-per-friend-public")
+ aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice-per-friend-unread", "alice-wall-key", "alice-profile")
+ require.NoError(t, err)
+ bobWall, err := module.Walls.CreateWall(ctx, bobID, "bob-per-friend-unread", "bob-wall-key", "bob-profile")
+ require.NoError(t, err)
+ charlieWall, err := module.Walls.CreateWall(ctx, charlieID, "charlie-per-friend-unread", "charlie-wall-key", "charlie-profile")
+ require.NoError(t, err)
+ require.NoError(t, module.Friends.AddFriend(ctx, bobID, bobWall.WallID, aliceWall.WallID, "alice-bob-share-key", aliceWall.CurrentVersion, "bob-share-key", bobWall.CurrentVersion))
+ require.NoError(t, module.Friends.AddFriend(ctx, charlieID, charlieWall.WallID, aliceWall.WallID, "alice-charlie-share-key", aliceWall.CurrentVersion, "charlie-share-key", charlieWall.CurrentVersion))
+ setFriendEventCreatedAt(t, module, 100, "friend_add", bobID, aliceID)
+ setFriendEventCreatedAt(t, module, 200, "friend_add", charlieID, aliceID)
+
+ bobMessage, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{
+ Kind: "regular",
+ SenderID: bobID,
+ SenderWallID: bobWall.WallID,
+ RecipientID: aliceID,
+ RecipientWallID: aliceWall.WallID,
+ MessageCipher: "bob-cipher",
+ SenderEncryptedMessageKey: "bob-sender-key",
+ RecipientEncryptedMessageKey: "bob-recipient-key",
+ })
+ require.NoError(t, err)
+ setMessageCreatedAt(t, module, 1000, bobMessage.MessageID)
+ aliceMessageToBob, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{
+ Kind: "regular",
+ SenderID: aliceID,
+ SenderWallID: aliceWall.WallID,
+ RecipientID: bobID,
+ RecipientWallID: bobWall.WallID,
+ MessageCipher: "alice-bob-cipher",
+ SenderEncryptedMessageKey: "alice-bob-sender-key",
+ RecipientEncryptedMessageKey: "alice-bob-recipient-key",
+ })
+ require.NoError(t, err)
+ setMessageCreatedAt(t, module, 1001, aliceMessageToBob.MessageID)
+ require.NoError(t, module.Messages.SetLike(ctx, aliceMessageToBob.MessageID, bobID, true))
+ setMessageLikeCreatedAt(t, module, 1002, aliceMessageToBob.MessageID, bobID)
+ charlieMessage, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{
+ Kind: "regular",
+ SenderID: charlieID,
+ SenderWallID: charlieWall.WallID,
+ RecipientID: aliceID,
+ RecipientWallID: aliceWall.WallID,
+ MessageCipher: "charlie-cipher",
+ SenderEncryptedMessageKey: "charlie-sender-key",
+ RecipientEncryptedMessageKey: "charlie-recipient-key",
+ })
+ require.NoError(t, err)
+ setMessageCreatedAt(t, module, 2000, charlieMessage.MessageID)
+
+ conversationByWallID := func(wallID string) WallMessageConversationRecord {
+ t.Helper()
+ conversations, _, err := module.Messages.ListConversations(ctx, aliceID, "", 10)
+ require.NoError(t, err)
+ for _, conversation := range conversations {
+ if conversation.Friend.WallID == wallID {
+ return conversation
+ }
+ }
+ require.FailNowf(t, "conversation not found", "wallID=%s", wallID)
+ return WallMessageConversationRecord{}
+ }
+
+ require.True(t, conversationByWallID(bobWall.WallID).Unread)
+ require.True(t, conversationByWallID(charlieWall.WallID).Unread)
+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID)
+ require.NoError(t, err)
+ require.True(t, notificationsUnread)
+
+ bobLatestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, aliceID, bobWall.WallID)
+ require.NoError(t, err)
+ require.Equal(t, int64(1002), bobLatestActivityAt)
+ require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, bobWall.WallID, bobLatestActivityAt))
+ require.False(t, conversationByWallID(bobWall.WallID).Unread)
+ require.True(t, conversationByWallID(charlieWall.WallID).Unread)
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID)
+ require.NoError(t, err)
+ require.True(t, notificationsUnread)
+
+ require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, charlieWall.WallID, 2000))
+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID)
+ require.NoError(t, err)
+ require.False(t, notificationsUnread)
+}
+
+func TestUnreadNotificationsFollowLatestConversationActivity(t *testing.T) {
+ ctx := context.Background()
+ module := newWallTestModule(t)
+
+ aliceID := insertWallUser(t, module, "[email protected]", "alice-latest-unread-public")
+ bobID := insertWallUser(t, module, "[email protected]", "bob-latest-unread-public")
+ aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice-latest-unread", "alice-wall-key", "alice-profile")
+ require.NoError(t, err)
+ bobWall, err := module.Walls.CreateWall(ctx, bobID, "bob-latest-unread", "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, 100, "friend_add", bobID, aliceID)
+
+ incoming, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{
+ Kind: "regular",
+ SenderID: bobID,
+ SenderWallID: bobWall.WallID,
+ RecipientID: aliceID,
+ RecipientWallID: aliceWall.WallID,
+ MessageCipher: "incoming-cipher",
+ SenderEncryptedMessageKey: "incoming-sender-key",
+ RecipientEncryptedMessageKey: "incoming-recipient-key",
+ })
+ require.NoError(t, err)
+ setMessageCreatedAt(t, module, 1000, incoming.MessageID)
+ outgoing, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{
+ Kind: "regular",
+ SenderID: aliceID,
+ SenderWallID: aliceWall.WallID,
+ RecipientID: bobID,
+ RecipientWallID: bobWall.WallID,
+ MessageCipher: "outgoing-cipher",
+ SenderEncryptedMessageKey: "outgoing-sender-key",
+ RecipientEncryptedMessageKey: "outgoing-recipient-key",
+ })
+ require.NoError(t, err)
+ setMessageCreatedAt(t, module, 2000, outgoing.MessageID)
+
+ conversations, _, err := module.Messages.ListConversations(ctx, aliceID, "", 10)
+ require.NoError(t, err)
+ require.Len(t, conversations, 1)
+ require.Equal(t, outgoing.MessageID, conversations[0].LatestActivity.Message.MessageID)
+ require.False(t, conversations[0].Unread)
+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID)
+ require.NoError(t, err)
+ require.False(t, notificationsUnread)
+}
+
func TestListPostLikersPaginates(t *testing.T) {
ctx := context.Background()
module := newWallTestModule(t)
diff --git a/server/wall/repo/posts.go b/server/wall/repo/posts.go
index 302955fc6c..4c74e583c4 100644
--- a/server/wall/repo/posts.go
+++ b/server/wall/repo/posts.go
@@ -67,7 +67,8 @@ func (r *PostsRepository) GetPost(ctx context.Context, postID int64, viewerID in
p.encrypted_post_key, p.caption_cipher,
p.key_version, p.created_at,
(SELECT COUNT(*) FROM wall_post_likes pl WHERE pl.post_id = p.post_id) AS likes,
- EXISTS (SELECT 1 FROM wall_post_likes pl WHERE pl.post_id = p.post_id AND pl.user_id = $2) AS viewer_liked
+ EXISTS (SELECT 1 FROM wall_post_likes pl WHERE pl.post_id = p.post_id AND pl.user_id = $2) AS viewer_liked,
+ FALSE AS viewer_unread
FROM wall_posts p
JOIN walls w ON w.wall_id = p.wall_id
JOIN walls owner_wall ON owner_wall.owner_id = p.owner_id
@@ -92,7 +93,8 @@ func (r *PostsRepository) ListPostsByWall(ctx context.Context, wallID string, vi
p.encrypted_post_key, p.caption_cipher,
p.key_version, p.created_at,
(SELECT COUNT(*) FROM wall_post_likes pl WHERE pl.post_id = p.post_id) AS likes,
- EXISTS (SELECT 1 FROM wall_post_likes pl WHERE pl.post_id = p.post_id AND pl.user_id = $2) AS viewer_liked
+ EXISTS (SELECT 1 FROM wall_post_likes pl WHERE pl.post_id = p.post_id AND pl.user_id = $2) AS viewer_liked,
+ FALSE AS viewer_unread
FROM wall_posts p
JOIN walls w ON w.wall_id = p.wall_id
JOIN walls owner_wall ON owner_wall.owner_id = p.owner_id
@@ -128,12 +130,12 @@ func (r *PostsRepository) ListPostsByWall(ctx context.Context, wallID string, vi
return out, nextCursor, nil
}
-func (r *PostsRepository) ListFeed(ctx context.Context, viewerID int64, cursor string, limit int) ([]WallPostRecord, string, error) {
+func (r *PostsRepository) ListFeed(ctx context.Context, viewerID int64, cursor string, limit int, readCreatedAt int64, readPostID int64) ([]WallPostRecord, string, error) {
limit = optionalInt(limit, 25)
if limit > 100 {
limit = 100
}
- args := []any{viewerID}
+ args := []any{viewerID, readCreatedAt, readPostID}
query := `
SELECT p.post_id, p.wall_id, w.wall_slug, p.owner_id,
owner_wall.owner_id, owner_wall.wall_id, owner_wall.wall_slug, owner_ka.public_key,
@@ -144,7 +146,8 @@ func (r *PostsRepository) ListFeed(ctx context.Context, viewerID int64, cursor s
p.encrypted_post_key, p.caption_cipher,
p.key_version, p.created_at,
(SELECT COUNT(*) FROM wall_post_likes pl WHERE pl.post_id = p.post_id) AS likes,
- EXISTS (SELECT 1 FROM wall_post_likes pl WHERE pl.post_id = p.post_id AND pl.user_id = $1) AS viewer_liked
+ EXISTS (SELECT 1 FROM wall_post_likes pl WHERE pl.post_id = p.post_id AND pl.user_id = $1) AS viewer_liked,
+ ((p.created_at, p.post_id) > ($2::bigint, $3::bigint)) AS viewer_unread
FROM wall_posts p
JOIN walls w ON w.wall_id = p.wall_id
JOIN walls owner_wall ON owner_wall.owner_id = p.owner_id
@@ -157,7 +160,7 @@ func (r *PostsRepository) ListFeed(ctx context.Context, viewerID int64, cursor s
)`
if cursorCreatedAt, cursorPostID, ok := parsePostCursor(cursor); ok {
args = append(args, cursorCreatedAt, cursorPostID)
- query += ` AND (p.created_at, p.post_id) < ($2, $3)`
+ query += ` AND (p.created_at, p.post_id) < ($4, $5)`
}
args = append(args, limit+1)
query += ` ORDER BY p.created_at DESC, p.post_id DESC LIMIT $` + strconv.Itoa(len(args))
@@ -185,6 +188,45 @@ func (r *PostsRepository) ListFeed(ctx context.Context, viewerID int64, cursor s
return out, nextCursor, nil
}
+func (r *PostsRepository) GetFeedPostMarker(ctx context.Context, viewerID, postID int64) (int64, int64, error) {
+ var createdAt int64
+ if err := r.DB.QueryRowContext(ctx, `
+ SELECT p.created_at
+ FROM wall_posts p
+ WHERE p.post_id = $2
+ AND p.is_deleted = FALSE
+ AND p.owner_id <> $1
+ AND EXISTS (
+ SELECT 1 FROM wall_friend_shares fs
+ WHERE fs.friend_id = $1 AND fs.wall_id = p.wall_id
+ )
+ `, viewerID, postID).Scan(&createdAt); err != nil {
+ return 0, 0, stacktrace.Propagate(err, "")
+ }
+ return createdAt, postID, nil
+}
+
+func (r *PostsRepository) HasUnreadFeed(ctx context.Context, viewerID, readCreatedAt, readPostID int64) (bool, error) {
+ var exists bool
+ if err := r.DB.QueryRowContext(ctx, `
+ SELECT EXISTS (
+ SELECT 1
+ FROM wall_posts p
+ WHERE p.is_deleted = FALSE
+ AND p.owner_id <> $1
+ AND (p.created_at, p.post_id) > ($2::bigint, $3::bigint)
+ AND EXISTS (
+ SELECT 1 FROM wall_friend_shares fs
+ WHERE fs.friend_id = $1 AND fs.wall_id = p.wall_id
+ )
+ LIMIT 1
+ )
+ `, viewerID, readCreatedAt, readPostID).Scan(&exists); err != nil {
+ return false, stacktrace.Propagate(err, "")
+ }
+ return exists, nil
+}
+
func (r *PostsRepository) ListAssetsByPostIDs(ctx context.Context, postIDs []int64) (map[int64][]WallPostAssetRecord, error) {
if len(postIDs) == 0 {
return map[int64][]WallPostAssetRecord{}, nil
@@ -349,7 +391,7 @@ func scanPostRecord(scanner interface{ Scan(dest ...any) error }) (*WallPostReco
var rec WallPostRecord
dest := []any{&rec.PostID, &rec.WallID, &rec.WallSlug, &rec.OwnerID}
dest = append(dest, wallActorScanDest(&rec.Author)...)
- dest = append(dest, &rec.EncryptedPostKey, &rec.CaptionCipher, &rec.KeyVersion, &rec.CreatedAt, &rec.Likes, &rec.ViewerLiked)
+ dest = append(dest, &rec.EncryptedPostKey, &rec.CaptionCipher, &rec.KeyVersion, &rec.CreatedAt, &rec.Likes, &rec.ViewerLiked, &rec.ViewerUnread)
if err := scanner.Scan(dest...); err != nil {
return nil, stacktrace.Propagate(err, "")
}
diff --git a/server/wall/repo/read_markers.go b/server/wall/repo/read_markers.go
new file mode 100644
index 0000000000..dca1209f73
--- /dev/null
+++ b/server/wall/repo/read_markers.go
@@ -0,0 +1,80 @@
+package repo
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "strings"
+
+ "github.com/ente-io/stacktrace"
+)
+
+func (r *ReadMarkersRepository) Get(ctx context.Context, userID int64) (*WallReadMarkerRecord, error) {
+ rec, err := scanReadMarkerRecord(r.DB.QueryRowContext(ctx, `
+ SELECT user_id, feed_read_created_at, feed_read_post_id, created_at, updated_at
+ FROM wall_read_markers
+ WHERE user_id = $1
+ `, userID))
+ if err != nil {
+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {
+ return &WallReadMarkerRecord{UserID: userID}, nil
+ }
+ return nil, err
+ }
+ return rec, nil
+}
+
+func (r *ReadMarkersRepository) UpsertFeedReadMarker(ctx context.Context, userID, createdAt, postID int64) error {
+ if userID <= 0 || createdAt <= 0 || postID <= 0 {
+ return nil
+ }
+ _, err := r.DB.ExecContext(ctx, `
+ INSERT INTO wall_read_markers (user_id, feed_read_created_at, feed_read_post_id)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (user_id) DO UPDATE
+ SET feed_read_created_at = CASE
+ WHEN (EXCLUDED.feed_read_created_at, EXCLUDED.feed_read_post_id) >
+ (wall_read_markers.feed_read_created_at, wall_read_markers.feed_read_post_id)
+ THEN EXCLUDED.feed_read_created_at
+ ELSE wall_read_markers.feed_read_created_at
+ END,
+ feed_read_post_id = CASE
+ WHEN (EXCLUDED.feed_read_created_at, EXCLUDED.feed_read_post_id) >
+ (wall_read_markers.feed_read_created_at, wall_read_markers.feed_read_post_id)
+ THEN EXCLUDED.feed_read_post_id
+ ELSE wall_read_markers.feed_read_post_id
+ END
+ `, userID, createdAt, postID)
+ return stacktrace.Propagate(err, "")
+}
+
+func (r *ReadMarkersRepository) UpsertNotificationReadMarker(ctx context.Context, userID int64, friendWallID string, readAt int64) error {
+ friendWallID = strings.TrimSpace(friendWallID)
+ if userID <= 0 || friendWallID == "" || readAt <= 0 {
+ return nil
+ }
+ _, err := r.DB.ExecContext(ctx, `
+ INSERT INTO wall_notification_read_markers (user_id, friend_wall_id, read_at)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (user_id, friend_wall_id) DO UPDATE
+ SET read_at = GREATEST(
+ wall_notification_read_markers.read_at,
+ EXCLUDED.read_at
+ )
+ `, userID, friendWallID, readAt)
+ return stacktrace.Propagate(err, "")
+}
+
+func scanReadMarkerRecord(scanner interface{ Scan(dest ...any) error }) (*WallReadMarkerRecord, error) {
+ var rec WallReadMarkerRecord
+ if err := scanner.Scan(
+ &rec.UserID,
+ &rec.FeedReadCreatedAt,
+ &rec.FeedReadPostID,
+ &rec.CreatedAt,
+ &rec.UpdatedAt,
+ ); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return &rec, nil
+}
diff --git a/web/apps/social/src/pages/app/index.tsx b/web/apps/social/src/pages/app/index.tsx
index e5752197f3..c1d17851d5 100644
--- a/web/apps/social/src/pages/app/index.tsx
+++ b/web/apps/social/src/pages/app/index.tsx
@@ -9,7 +9,9 @@ import {
createCurrentProfileLink,
loadCurrentFeedPage,
loadCurrentPostLikers,
+ loadCurrentUnreadStatus,
loadCurrentWallFriends,
+ markCurrentFeedRead,
replyToCurrentPost,
setCurrentPostLiked,
type SocialWallPost,
@@ -27,6 +29,8 @@ const Page: React.FC = () => {
useSocialAppState();
const [addedFriendToastName, setAddedFriendToastName] = useState<string>();
const [feedItems, setFeedItems] = useState<SocialWallPost[]>([]);
+ const [hasUnreadNotifications, setHasUnreadNotifications] =
+ useState(false);
const [isFeedLoading, setIsFeedLoading] = useState(true);
const closeAddedFriendToast = React.useCallback(
() => setAddedFriendToastName(undefined),
@@ -55,6 +59,7 @@ const Page: React.FC = () => {
const wallId = profile?.wallId;
if (!wallId) {
+ setHasUnreadNotifications(false);
setIsFeedLoading(false);
return;
}
@@ -63,12 +68,21 @@ const Page: React.FC = () => {
setIsFeedLoading(true);
void Promise.all([
loadCurrentFeedPage(),
+ loadCurrentUnreadStatus(),
loadCurrentWallFriends(wallId),
])
- .then(([feed, nextFriends]) => {
+ .then(([feed, unreadStatus, nextFriends]) => {
if (cancelled) return;
setFeedItems(feed.items);
+ setHasUnreadNotifications(unreadStatus.notificationsUnread);
setFriends(nextFriends);
+ const latestFeedPost = feed.items[0];
+ if (latestFeedPost) {
+ void markCurrentFeedRead(latestFeedPost.postId).catch(
+ (error: unknown) =>
+ console.warn("Failed to mark feed read", error),
+ );
+ }
})
.catch((error: unknown) =>
console.error("Failed to load social home", error),
@@ -95,6 +109,7 @@ const Page: React.FC = () => {
feedItems={feedItems}
friendsCount={friends.length}
addedFriendToastName={addedFriendToastName}
+ hasUnreadNotifications={hasUnreadNotifications}
isFeedLoading={isFeedLoading}
profile={screenProfile}
onAddedFriendToastClose={closeAddedFriendToast}
diff --git a/web/apps/social/src/pages/app/notifications.tsx b/web/apps/social/src/pages/app/notifications.tsx
index 3759f386ab..15f388b837 100644
--- a/web/apps/social/src/pages/app/notifications.tsx
+++ b/web/apps/social/src/pages/app/notifications.tsx
@@ -7,6 +7,7 @@ import {
deleteCurrentMessage,
loadCurrentMessageConversations,
loadCurrentMessageThread,
+ markCurrentNotificationsRead,
replyToCurrentMessage,
sendCurrentMessage,
setCurrentMessageLiked,
@@ -33,13 +34,38 @@ const Page: React.FC = () => {
const refreshConversations = React.useCallback(() => {
setIsConversationsLoading(true);
void loadCurrentMessageConversations()
- .then((page) => setConversations(page.items))
+ .then((page) => {
+ setConversations(page.items);
+ })
.catch((error: unknown) =>
console.error("Failed to load message conversations", error),
)
.finally(() => setIsConversationsLoading(false));
}, []);
+ const openConversation = React.useCallback(
+ (conversation: SocialWallMessageConversation) => {
+ setSelectedFriend(conversation.friend);
+ const friendWallId = conversation.friend.wallId ?? conversation.friend.id;
+ setConversations((currentConversations) =>
+ currentConversations.map((currentConversation) =>
+ (currentConversation.friend.wallId ??
+ currentConversation.friend.id) == friendWallId
+ ? { ...currentConversation, unread: false }
+ : currentConversation,
+ ),
+ );
+ void markCurrentNotificationsRead(friendWallId).catch(
+ (error: unknown) =>
+ console.warn(
+ "Failed to mark notification conversation read",
+ error,
+ ),
+ );
+ },
+ [],
+ );
+
React.useEffect(() => {
if (profileLoadStatus == "ready" && !profile) {
void router.replace(socialRoutes.onboarding);
@@ -91,7 +117,7 @@ const Page: React.FC = () => {
messages={messages}
onBack={() => void router.push(socialRoutes.home)}
onCloseThread={() => setSelectedFriend(undefined)}
- onOpenThread={setSelectedFriend}
+ onOpenThread={openConversation}
onSendMessage={async (wallId, text) => {
const message = await sendCurrentMessage(wallId, text);
setMessages((currentMessages) => [
diff --git a/web/apps/social/src/screens/HomeScreen.tsx b/web/apps/social/src/screens/HomeScreen.tsx
index 24767a8675..847d7914d6 100644
--- a/web/apps/social/src/screens/HomeScreen.tsx
+++ b/web/apps/social/src/screens/HomeScreen.tsx
@@ -74,6 +74,7 @@ interface HomeScreenProps {
addedFriendToastName?: string;
feedItems: SocialWallPost[];
friendsCount: number;
+ hasUnreadNotifications?: boolean;
isFeedLoading?: boolean;
onAddedFriendToastClose?: () => void;
onCreatePost?: (
@@ -122,6 +123,7 @@ interface FeedItemProps {
postId: number;
timestampMs: number;
viewerLiked: boolean;
+ viewerUnread: boolean;
}
interface AddedFriendToastProps {
@@ -153,6 +155,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
postId,
timestampMs,
viewerLiked,
+ viewerUnread,
}) => {
const [isLiked, setIsLiked] = useState(viewerLiked);
const [localLikeCount, setLocalLikeCount] = useState(likeCount);
@@ -247,7 +250,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
fontFamily: '"Inter Variable", Inter, sans-serif',
fontSize: 14,
gap: "8px",
- gridTemplateColumns: `${feedAvatarSize}px minmax(0, 1fr) auto`,
+ gridTemplateColumns: `${feedAvatarSize}px minmax(0, 1fr) auto${viewerUnread ? " 8px" : ""}`,
lineHeight: "20px",
mb: "10px",
minHeight: 32,
@@ -355,6 +358,18 @@ const FeedItem: React.FC<FeedItemProps> = ({
>
{dateLabel}
</Box>
+ {viewerUnread && (
+ <Box
+ aria-hidden
+ sx={{
+ bgcolor: green,
+ borderRadius: "50%",
+ height: 8,
+ justifySelf: "end",
+ width: 8,
+ }}
+ />
+ )}
</Box>
<Box
sx={{
@@ -616,6 +631,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
addedFriendToastName,
feedItems,
friendsCount,
+ hasUnreadNotifications = false,
isFeedLoading = false,
onAddedFriendToastClose,
onCreatePost,
@@ -833,7 +849,11 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
<Box
component="button"
type="button"
- aria-label="Open notifications"
+ aria-label={
+ hasUnreadNotifications
+ ? "Open notifications with unread activity"
+ : "Open notifications"
+ }
onClick={onOpenNotifications}
sx={{
appearance: "none",
@@ -851,6 +871,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
justifyContent: "center",
lineHeight: 0,
p: 0,
+ position: "relative",
width: headerActionSize,
"& svg": { display: "block" },
"&:focus-visible": {
@@ -865,6 +886,21 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
size={headerIconSize}
strokeWidth={1.8}
/>
+ {hasUnreadNotifications && (
+ <Box
+ aria-hidden
+ sx={{
+ bgcolor: green,
+ border: `2px solid ${homeBackground}`,
+ borderRadius: "50%",
+ height: 11,
+ position: "absolute",
+ right: 4,
+ top: 6,
+ width: 11,
+ }}
+ />
+ )}
</Box>
<Box
component="button"
@@ -975,6 +1011,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
postId={item.postId}
timestampMs={item.timestampMs}
viewerLiked={item.viewerLiked}
+ viewerUnread={item.viewerUnread}
/>
))
) : isEmptyFeedLoading ? (
diff --git a/web/apps/social/src/screens/MessagesScreen.tsx b/web/apps/social/src/screens/MessagesScreen.tsx
index ba96450268..236ee1a4f7 100644
--- a/web/apps/social/src/screens/MessagesScreen.tsx
+++ b/web/apps/social/src/screens/MessagesScreen.tsx
@@ -57,7 +57,7 @@ interface MessagesScreenProps {
onBack?: () => void;
onCloseThread: () => void;
onDeleteMessage: (messageId: string) => Promise<void>;
- onOpenThread: (friend: SocialWallMessageConversation["friend"]) => void;
+ onOpenThread: (conversation: SocialWallMessageConversation) => void;
onReplyToMessage: (
wallId: string,
messageId: string,
@@ -251,7 +251,7 @@ const ConversationPreviewLine: React.FC<{
color: textSecondary,
fontFamily: '"Inter Variable", Inter, sans-serif',
fontSize: 13,
- fontWeight: 500,
+ fontWeight: conversation.unread ? 650 : 500,
lineHeight: "18px",
minWidth: 0,
overflow: "hidden",
@@ -1629,9 +1629,7 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
component="button"
type="button"
onClick={() =>
- onOpenThread(
- conversation.friend,
- )
+ onOpenThread(conversation)
}
sx={{
alignItems: "center",
@@ -1733,6 +1731,19 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({
>
{timestampLabel}
</Box>
+ {conversation.unread && (
+ <Box
+ aria-hidden
+ sx={{
+ bgcolor: green,
+ borderRadius:
+ "50%",
+ flexShrink: 0,
+ height: 8,
+ width: 8,
+ }}
+ />
+ )}
</Box>
<ConversationPreviewLine
conversation={
diff --git a/web/apps/social/src/services/socialWall.ts b/web/apps/social/src/services/socialWall.ts
index 96ac13f6b8..ade0008598 100644
--- a/web/apps/social/src/services/socialWall.ts
+++ b/web/apps/social/src/services/socialWall.ts
@@ -55,6 +55,7 @@ interface WallPost {
objects?: WallPostObject[];
postId: number;
viewerLiked: boolean;
+ viewerUnread?: boolean;
wallId: string;
wallSlug: string;
}
@@ -136,6 +137,7 @@ interface WallMessagePage {
interface WallMessageConversation {
friend: WallActor;
latestActivity: WallMessageConversationActivity;
+ unread?: boolean;
}
interface WallMessageConversationPage {
@@ -154,6 +156,7 @@ export interface SocialWallPost {
postId: number;
timestampMs: number;
viewerLiked: boolean;
+ viewerUnread: boolean;
wallId: string;
width?: number;
}
@@ -237,6 +240,7 @@ export interface SocialWallMessagePage {
export interface SocialWallMessageConversation {
friend: FriendProfile;
latestActivity: SocialWallMessageActivity;
+ unread: boolean;
}
export interface SocialWallMessageConversationPage {
@@ -244,6 +248,11 @@ export interface SocialWallMessageConversationPage {
nextCursor?: string;
}
+export interface SocialWallUnreadStatus {
+ feedUnread: boolean;
+ notificationsUnread: boolean;
+}
+
const parseWallProfilePayload = (profile: string): WallProfilePayload => {
if (!profile.trim()) return {};
try {
@@ -362,6 +371,7 @@ const postFromAccountPost = async (
postId: post.postId,
timestampMs: timestampMsFromWallDate(post.createdAt),
viewerLiked: post.viewerLiked,
+ viewerUnread: Boolean(post.viewerUnread),
wallId: post.wallId,
width: object.width,
};
@@ -392,6 +402,7 @@ const postFromLinkPost = async (
postId: post.postId,
timestampMs: timestampMsFromWallDate(post.createdAt),
viewerLiked: post.viewerLiked,
+ viewerUnread: Boolean(post.viewerUnread),
wallId: post.wallId,
width: object.width,
};
@@ -623,6 +634,26 @@ export const loadCurrentFeedPage = async (
}
};
+export const loadCurrentUnreadStatus =
+ async (): Promise<SocialWallUnreadStatus> => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ return (await ctx.unread_status()) as SocialWallUnreadStatus;
+ } finally {
+ ctx.free();
+ }
+ };
+
+export const markCurrentFeedRead = async (postId: number) => {
+ if (postId <= 0) return;
+ const ctx = await ensureCurrentWallContext();
+ try {
+ await ctx.mark_feed_read(BigInt(postId));
+ } finally {
+ ctx.free();
+ }
+};
+
export const loadCurrentWallPostsPage = async (
wallId: string,
cursor?: string,
@@ -799,6 +830,7 @@ export const loadCurrentMessageConversations =
ctx,
conversation.latestActivity,
),
+ unread: Boolean(conversation.unread),
};
}),
);
@@ -831,6 +863,16 @@ export const loadCurrentMessageThread = async (
}
};
+export const markCurrentNotificationsRead = async (friendWallId: string) => {
+ if (!friendWallId.trim()) return;
+ const ctx = await ensureCurrentWallContext();
+ try {
+ await ctx.mark_notifications_read(friendWallId);
+ } finally {
+ ctx.free();
+ }
+};
+
export const deleteCurrentPost = async (postId: number) => {
const ctx = await ensureCurrentWallContext();
try {
diff --git a/web/packages/wasm/src/wall.rs b/web/packages/wasm/src/wall.rs
index 59177e9afa..a6c2e4f7ea 100644
--- a/web/packages/wasm/src/wall.rs
+++ b/web/packages/wasm/src/wall.rs
@@ -162,6 +162,7 @@ struct PostJs {
created_at: String,
likes: i64,
viewer_liked: bool,
+ viewer_unread: bool,
}
#[derive(Serialize)]
@@ -227,6 +228,7 @@ struct MessagePageJs {
struct MessageConversationJs {
friend: ActorJs,
latest_activity: MessageConversationActivityJs,
+ unread: bool,
}
#[derive(Serialize)]
@@ -365,6 +367,7 @@ async fn account_post_to_js(
created_at: post.created_at,
likes: post.likes,
viewer_liked: post.viewer_liked,
+ viewer_unread: post.viewer_unread,
})
}
@@ -386,6 +389,7 @@ async fn link_post_to_js(
created_at: post.created_at,
likes: post.likes,
viewer_liked: post.viewer_liked,
+ viewer_unread: post.viewer_unread,
})
}
@@ -699,6 +703,7 @@ impl WallAccountCtxHandle {
created_at: item.created_at,
likes: item.likes,
viewer_liked: item.viewer_liked,
+ viewer_unread: item.viewer_unread,
})
.collect(),
next_cursor: page.next_cursor,
@@ -709,6 +714,30 @@ impl WallAccountCtxHandle {
.map_err(Into::into)
}
+ /// Return whether the current account has unread feed or notification activity.
+ pub async fn unread_status(&self) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.unread_status().await?).map_err(Into::into)
+ }
+
+ /// Mark feed posts read through the given visible post.
+ pub async fn mark_feed_read(&self, post_id: i64) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.mark_feed_read(post_id).await?).map_err(Into::into)
+ }
+
+ /// Mark notification activity for one friend as read.
+ pub async fn mark_notifications_read(
+ &self,
+ friend_wall_id: String,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(
+ &self
+ .inner
+ .mark_notifications_read(friend_wall_id)
+ .await?,
+ )
+ .map_err(Into::into)
+ }
+
/// List posts on a wall with captions decrypted.
pub async fn list_posts(
&self,
@@ -890,6 +919,7 @@ impl WallAccountCtxHandle {
conversation.latest_activity,
)
.await?,
+ unread: conversation.unread,
});
}
swb::to_value(&MessageConversationPageJs {