π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Implement Wall friends backend
Anand Baburajan5ac205ab2476
diff --git a/rust/e2e/tests/wall_e2e.rs b/rust/e2e/tests/wall_e2e.rsindex 8564fe0a3a..096a6685d8 100644--- a/rust/e2e/tests/wall_e2e.rs+++ b/rust/e2e/tests/wall_e2e.rs@@ -6,7 +6,7 @@ use support::{auth, wall};#[tokio::test]#[ignore = "requires local Museum at ENTE_E2E_ENDPOINT or http://localhost:8080"]-async fn wall_bootstrap_posts_follow_share_and_link_suite() {+async fn wall_bootstrap_posts_friend_share_and_link_suite() {let endpoint = support::endpoint();if !support::assert_server_or_skip(&endpoint, "wall rust e2e suite").await {return;@@ -18,10 +18,10 @@ async fn wall_bootstrap_posts_follow_share_and_link_suite() {support::unique_password("WallOwner"),).await;- let follower = auth::create_account(+ let friend = auth::create_account(&endpoint,- support::unique_test_email("wall-follower"),- support::unique_password("WallFollower"),+ support::unique_test_email("wall-friend"),+ support::unique_password("WallFriender"),).await;let outsider = auth::create_account(@@ -32,11 +32,11 @@ async fn wall_bootstrap_posts_follow_share_and_link_suite() {.await;let owner_ctx = wall::open_ctx(&endpoint, &owner);- let follower_ctx = wall::open_ctx(&endpoint, &follower);+ let friend_ctx = wall::open_ctx(&endpoint, &friend);let outsider_ctx = wall::open_ctx(&endpoint, &outsider);let owner_slug = format!("owner-{}", owner.user_id);- let follower_slug = format!("follower-{}", follower.user_id);+ let friend_slug = format!("friend-{}", friend.user_id);let outsider_slug = format!("outsider-{}", outsider.user_id);let owner_profile = wall::profile_payload("Owner", "Owner bio");@@ -44,13 +44,11 @@ async fn wall_bootstrap_posts_follow_share_and_link_suite() {.create_wall(&owner_slug, &owner_profile).await.expect("owner wall creation failed");- follower_ctx- .create_wall(- &follower_slug,- &wall::profile_payload("Follower", "Follower bio"),- )+ let friend_profile_payload = wall::profile_payload("Friender", "Friender bio");+ let friend_wall = friend_ctx+ .create_wall(&friend_slug, &friend_profile_payload).await- .expect("follower wall creation failed");+ .expect("friend wall creation failed");outsider_ctx.create_wall(&outsider_slug,@@ -121,59 +119,70 @@ async fn wall_bootstrap_posts_follow_share_and_link_suite() {);wall::assert_http_status(- follower_ctx+ friend_ctx.get_wall_profile_raw(&owner_wall.wall_id, None).await,403,);- follower_ctx- .request_follow_by_wall(&owner_wall.wall_id)- .await- .expect("follow request should succeed");- let incoming = owner_ctx- .list_incoming_follow_requests()+ let link = owner_ctx+ .create_wall_link(&owner_wall.wall_id).await- .expect("incoming follow requests should load");- assert_eq!(incoming.len(), 1);- assert_eq!(incoming[0].wall_id, owner_wall.wall_id);- owner_ctx- .approve_follow_request(&incoming[0])+ .expect("wall link should be created");+ let link_ctx = WallLinkCtx::open(OpenWallLinkCtxInput {+ base_url: endpoint.clone(),+ wall_username: link.wall_username.clone(),+ access_key: link.access_key.clone(),+ user_agent: Some("ente-e2e".to_string()),+ client_package: Some("io.ente.photos".to_string()),+ client_version: Some("ente-e2e".to_string()),+ })+ .await+ .expect("wall link should open");+ friend_ctx+ .add_friend_from_link(&link_ctx).await- .expect("follow approval should succeed");+ .expect("friend add should succeed");- let shares = follower_ctx- .list_follow_shares()+ let shares = friend_ctx+ .list_friend_shares().await- .expect("follow shares should load");+ .expect("friend shares should load");assert_eq!(shares.len(), 1);- let decrypted_share = follower_ctx- .decrypt_follow_share(&shares[0])- .expect("follow share should decrypt");+ let decrypted_share = friend_ctx+ .decrypt_friend_share(&shares[0])+ .expect("friend share should decrypt");assert_eq!(decrypted_share.wall_id, owner_wall.wall_id);- let hydrated = follower_ctx+ let hydrated = friend_ctx.hydrate_wall_keys().await.expect("wall keys should hydrate");assert_eq!(hydrated.owned.len(), 1);- assert_eq!(hydrated.followed.len(), 1);- assert_eq!(hydrated.followed[0].wall_id, owner_wall.wall_id);+ assert_eq!(hydrated.friends.len(), 1);+ assert_eq!(hydrated.friends[0].wall_id, owner_wall.wall_id);- let follower_profile = follower_ctx+ let friend_profile = friend_ctx.get_wall_profile_decrypted(&owner_wall.wall_id, None).await- .expect("approved follower should decrypt profile");- assert_eq!(follower_profile.profile, updated_profile);- assert_eq!(follower_profile.wall_slug, updated_slug);+ .expect("approved friend should decrypt profile");+ assert_eq!(friend_profile.profile, updated_profile);+ assert_eq!(friend_profile.wall_slug, updated_slug);++ let owner_view_of_friend = owner_ctx+ .get_wall_profile_decrypted(&friend_wall.wall_id, None)+ .await+ .expect("approved owner should decrypt friend profile");+ assert_eq!(owner_view_of_friend.profile, friend_profile_payload);+ assert_eq!(owner_view_of_friend.wall_slug, friend_slug);- let feed = follower_ctx+ let feed = friend_ctx.list_feed(None, Some(10)).await- .expect("feed should load after follow approval");+ .expect("feed should load after friend approval");assert_eq!(feed.items.len(), 1);assert_eq!(feed.items[0].post_id, post_id);- let feed_post = follower_ctx+ let feed_post = friend_ctx.decrypt_feed_item(&feed.items[0]).await.expect("feed item should decrypt");@@ -182,12 +191,12 @@ async fn wall_bootstrap_posts_follow_share_and_link_suite() {Some(br#"{"caption":"hello world"}"#.as_slice()));- let liked = follower_ctx+ let liked = friend_ctx.like_post(post_id, true).await.expect("liking post should succeed");assert!(liked.liked);- let top_level = follower_ctx+ let top_level = friend_ctx.create_comment(post_id, &post_key, b"looks great", None).await.expect("comment creation should succeed");@@ -196,37 +205,22 @@ async fn wall_bootstrap_posts_follow_share_and_link_suite() {.await.expect("reply creation should succeed");- let comments = follower_ctx+ let comments = friend_ctx.list_comments(post_id, None, None).await.expect("comments should load");- assert_eq!(comments.comments.len(), 1);- assert_eq!(comments.comments[0].replies.len(), 1);- let parent = follower_ctx- .decrypt_comment(&post_key, &comments.comments[0])+ assert_eq!(comments.comments.len(), 2);+ let parent = friend_ctx+ .decrypt_comment(&post_key, &comments.comments[1]).expect("parent comment should decrypt");- let reply = follower_ctx- .decrypt_comment(&post_key, &comments.comments[0].replies[0])+ let reply = friend_ctx+ .decrypt_comment(&post_key, &comments.comments[0]).expect("reply comment should decrypt");assert_eq!(parent.plaintext, b"looks great");assert_eq!(reply.plaintext, b"thanks");wall::assert_http_status(outsider_ctx.fetch_post_decrypted(post_id).await, 403);- let link = owner_ctx- .create_wall_link(&owner_wall.wall_id)- .await- .expect("wall link should be created");- let link_ctx = WallLinkCtx::open(OpenWallLinkCtxInput {- base_url: endpoint.clone(),- wall_username: link.wall_username.clone(),- access_key: link.access_key.clone(),- user_agent: Some("ente-e2e".to_string()),- client_package: Some("io.ente.photos".to_string()),- client_version: Some("ente-e2e".to_string()),- })- .await- .expect("wall link should open");let link_profile = link_ctx.get_wall_profile_decrypted(None).await@@ -250,13 +244,12 @@ async fn wall_bootstrap_posts_follow_share_and_link_suite() {.list_comments(post_id, None, None).await.expect("link session should list comments");- assert_eq!(link_comments.comments.len(), 1);- assert_eq!(link_comments.comments[0].replies.len(), 1);+ assert_eq!(link_comments.comments.len(), 2);let link_parent = link_ctx- .decrypt_comment(&link_post.post_key, &link_comments.comments[0])+ .decrypt_comment(&link_post.post_key, &link_comments.comments[1]).expect("link session should decrypt parent comment");let link_reply = link_ctx- .decrypt_comment(&link_post.post_key, &link_comments.comments[0].replies[0])+ .decrypt_comment(&link_post.post_key, &link_comments.comments[0]).expect("link session should decrypt reply comment");assert_eq!(link_parent.plaintext, b"looks great");assert_eq!(link_reply.plaintext, b"thanks");@@ -282,30 +275,30 @@ async fn wall_rotation_history_refresh_and_link_suite() {support::unique_password("WallRotationOwner"),).await;- let follower = auth::create_account(+ let friend = auth::create_account(&endpoint,- support::unique_test_email("wall-rotation-follower"),- support::unique_password("WallRotationFollower"),+ support::unique_test_email("wall-rotation-friend"),+ support::unique_password("WallRotationFriender"),).await;let owner_ctx = wall::open_ctx(&endpoint, &owner);- let follower_ctx = wall::open_ctx(&endpoint, &follower);+ let friend_ctx = wall::open_ctx(&endpoint, &friend);let owner_slug = format!("rotation-owner-{}", owner.user_id);- let follower_slug = format!("rotation-follower-{}", follower.user_id);+ let friend_slug = format!("rotation-friend-{}", friend.user_id);let profile_v1 = wall::profile_payload("Rotation Owner", "Profile v1");let owner_wall = owner_ctx.create_wall(&owner_slug, &profile_v1).await.expect("owner wall creation failed");- follower_ctx+ friend_ctx.create_wall(- &follower_slug,- &wall::profile_payload("Rotation Follower", "Follower bio"),+ &friend_slug,+ &wall::profile_payload("Rotation Friender", "Friender bio"),).await- .expect("follower wall creation failed");+ .expect("friend wall creation failed");let post_key_v1 = owner_ctx.generate_post_key();let object_v1 = owner_ctx@@ -322,24 +315,30 @@ async fn wall_rotation_history_refresh_and_link_suite() {.await.expect("v1 post creation should succeed");- follower_ctx- .request_follow_by_wall(&owner_wall.wall_id)- .await- .expect("follow request should succeed");- let incoming = owner_ctx- .list_incoming_follow_requests()+ let link = owner_ctx+ .create_wall_link(&owner_wall.wall_id).await- .expect("incoming follow requests should load");- owner_ctx- .approve_follow_request(&incoming[0])+ .expect("rotation wall link should be created");+ let link_ctx = WallLinkCtx::open(OpenWallLinkCtxInput {+ base_url: endpoint.clone(),+ wall_username: link.wall_username.clone(),+ access_key: link.access_key.clone(),+ user_agent: Some("ente-e2e".to_string()),+ client_package: Some("io.ente.photos".to_string()),+ client_version: Some("ente-e2e".to_string()),+ })+ .await+ .expect("rotation wall link should open");+ friend_ctx+ .add_friend_from_link(&link_ctx).await- .expect("follow approval should succeed");+ .expect("friend add should succeed");- let follower_profile_v1 = follower_ctx+ let friend_profile_v1 = friend_ctx.get_wall_profile_decrypted(&owner_wall.wall_id, Some(owner_wall.key_version)).await- .expect("follower should decrypt v1 profile");- assert_eq!(follower_profile_v1.profile, profile_v1);+ .expect("friend should decrypt v1 profile");+ assert_eq!(friend_profile_v1.profile, profile_v1);let profile_v2 = wall::profile_payload("Rotation Owner", "Profile v2");let rotated_wall = owner_ctx@@ -349,14 +348,14 @@ async fn wall_rotation_history_refresh_and_link_suite() {assert_eq!(rotated_wall.key_version, owner_wall.key_version + 1);let refreshed = owner_ctx- .refresh_follow_shares(&owner_wall.wall_id)+ .refresh_friend_shares(&owner_wall.wall_id).await- .expect("follow shares should refresh");+ .expect("friend shares should refresh");assert_eq!(refreshed, 1);- let refreshed_shares = follower_ctx- .list_follow_shares()+ let refreshed_shares = friend_ctx+ .list_friend_shares().await- .expect("refreshed follow shares should load");+ .expect("refreshed friend shares should load");assert_eq!(refreshed_shares.len(), 1);assert_eq!(refreshed_shares[0].key_version, rotated_wall.key_version);@@ -385,13 +384,13 @@ async fn wall_rotation_history_refresh_and_link_suite() {.await.expect("owner should decrypt current profile");assert_eq!(owner_profile_v2.profile, profile_v2);- let follower_profile_v2 = follower_ctx+ let friend_profile_v2 = friend_ctx.get_wall_profile_decrypted(&owner_wall.wall_id, None).await- .expect("follower should decrypt current profile");- assert_eq!(follower_profile_v2.profile, profile_v2);+ .expect("friend should decrypt current profile");+ assert_eq!(friend_profile_v2.profile, profile_v2);- let feed = follower_ctx+ let feed = friend_ctx.list_feed(None, Some(10)).await.expect("feed should load after rotation");@@ -399,26 +398,26 @@ async fn wall_rotation_history_refresh_and_link_suite() {.items.iter().find(|item| item.post_id == post_id_v1)- .expect("v1 post should remain in follower feed");+ .expect("v1 post should remain in friend feed");let feed_v2 = feed.items.iter().find(|item| item.post_id == post_id_v2)- .expect("v2 post should appear in follower feed");- let follower_post_v1 = follower_ctx+ .expect("v2 post should appear in friend feed");+ let friend_post_v1 = friend_ctx.decrypt_feed_item(feed_v1).await- .expect("follower should decrypt v1 post after rotation");+ .expect("friend should decrypt v1 post after rotation");assert_eq!(- follower_post_v1.caption_plaintext.as_deref(),+ friend_post_v1.caption_plaintext.as_deref(),Some(br#"{"caption":"version one"}"#.as_slice()));- let follower_post_v2 = follower_ctx+ let friend_post_v2 = friend_ctx.decrypt_feed_item(feed_v2).await- .expect("follower should decrypt v2 post after rotation");+ .expect("friend should decrypt v2 post after rotation");assert_eq!(- follower_post_v2.caption_plaintext.as_deref(),+ friend_post_v2.caption_plaintext.as_deref(),Some(br#"{"caption":"version two"}"#.as_slice()));diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rsindex 25e00ba980..59cfbd3826 100644--- a/rust/wall/src/client.rs+++ b/rust/wall/src/client.rs@@ -8,22 +8,21 @@ use crate::crypto::{};use crate::error::{Result, WallError};use crate::models::{- CreatedWall, CreatedWallLink, DecryptedComment, DecryptedFollowShare, DecryptedPost,+ CreatedWall, CreatedWallLink, DecryptedComment, DecryptedFriendShare, DecryptedPost,DecryptedWallProfile, FeedItem, FeedPage, HydratedKeys, OpenAccountWallCtxInput,OpenWallLinkCtxInput, PrivateKeySource,};use crate::transport::{- ApproveFollowPayload, AssetDownloadResponse, CancelFollowRequestPayload, CommentResponse,- CommunityResponse, CreateCommentRequest, CreateEntityKeyRequest, CreatePostRequest,- CreatePostResponse, CreateWallRequest, EntityKeyPayload, EntityKeyResponse,- FollowRequestCreatedResponse, FollowRequestPayload, FollowRequestResponse, FollowShareResponse,- LikePostRequest, LikePostResponse, ListCommentsResponse, OutgoingFollowRequestResponse,- PostObjectPayload, PostPage, PostResponse, PresignUploadRequest, PresignUploadResponse,- ProfileAvatarPayload, RefreshFollowSharesRequest, RejectFollowPayload, RotateWallKeyRequest,- ShareUpdatePayload, UpdatePostCaptionRequest, UpdateWallProfileRequest,- UpdateWallProfileResponse, UpdateWallSlugRequest, WallFollowerResponse, WallKeyResponse,+ AddFriendPayload, AssetDownloadResponse, CommentResponse, CreateCommentRequest,+ CreateEntityKeyRequest, CreatePostRequest, CreatePostResponse, CreateWallRequest,+ EntityKeyPayload, EntityKeyResponse, FriendShareResponse, FriendStatusResponse,+ FriendTargetPayload, LikeCommentRequest, LikeCommentResponse, LikePostRequest,+ LikePostResponse, ListCommentsResponse, PostObjectPayload, PostPage, PostResponse,+ PresignUploadRequest, PresignUploadResponse, ProfileAvatarPayload, RefreshFriendSharesRequest,+ RotateWallKeyRequest, ShareUpdatePayload, UpdatePostCaptionRequest, UpdateWallProfileRequest,+ UpdateWallProfileResponse, UpdateWallSlugRequest, WallFriendResponse, WallKeyResponse,WallKeyVersionResponse, WallLinkCreateRequest, WallLinkLoginRequest, WallLinkLoginResponse,- WallLinkStatusResponse, WallLookupResponse, WallProfileResponse,+ WallLinkStatusResponse, WallLookupResponse, WallNotificationPage, WallProfileResponse,};use ente_core::crypto::{sealed, secretbox};use ente_core::http::{Error as HttpError, HttpClient, HttpConfig};@@ -47,9 +46,11 @@ pub struct AccountWallCtx {pub struct WallLinkCtx {client: HttpClient,+ session_token: String,owner_handle: String,wall_id: String,wall_slug: String,+ owner_public_key: Vec<u8>,wall_key: Vec<u8>,key_version: i32,}@@ -149,25 +150,25 @@ impl AccountWallCtx {self.client.get_json("/wall", &[]).await.map_err(Into::into)}- pub async fn list_follow_shares(&self) -> Result<Vec<FollowShareResponse>> {+ pub async fn list_friend_shares(&self) -> Result<Vec<FriendShareResponse>> {self.client- .get_json("/wall/follow/shares", &[])+ .get_json("/wall/friends/shares", &[]).await.map_err(Into::into)}- pub fn decrypt_follow_share(+ pub fn decrypt_friend_share(&self,- share: &FollowShareResponse,- ) -> Result<DecryptedFollowShare> {+ share: &FriendShareResponse,+ ) -> Result<DecryptedFriendShare> {let packed = decode_b64(&share.encrypted_wall_key)?;let (ciphertext, _) = unpack_payload(&packed)?;if ciphertext.is_empty() {return Err(WallError::MissingEncryptedWallKey);}let wall_key = sealed::open(&ciphertext, &self.public_key, &self.private_key)?;- Ok(DecryptedFollowShare {- followee: share.followee.clone(),+ Ok(DecryptedFriendShare {+ friend: share.friend.clone(),wall_id: share.wall_id.clone(),wall_slug: share.wall_slug.clone(),wall_key,@@ -175,6 +176,19 @@ impl AccountWallCtx {})}+ async fn default_owned_wall_access(&self) -> Result<(WallKeyResponse, Vec<u8>)> {+ let root_wall_key = self.get_or_create_root_wall_key().await?;+ let wall = self+ .list_owned_walls()+ .await?+ .into_iter()+ .next()+ .ok_or_else(|| WallError::InvalidInput("no owned wall is available".into()))?;+ let packed = decode_b64(&wall.encrypted_wall_key)?;+ let wall_key = decrypt_secretbox_packed(&root_wall_key, &packed)?;+ Ok((wall, wall_key))+ }+pub async fn resolve_owned_wall_key(&self, wall_id: &str) -> Result<Option<Vec<u8>>> {Ok(self.resolve_owned_wall_access(wall_id)@@ -243,25 +257,6 @@ impl AccountWallCtx {self.client.get_json(&path, &[]).await.map_err(Into::into)}- pub async fn search_community(- &self,- query: &str,- cursor: Option<String>,- limit: Option<i32>,- ) -> Result<CommunityResponse> {- let mut query_params = vec![("q", query.to_owned())];- if let Some(value) = cursor.filter(|value| !value.trim().is_empty()) {- query_params.push(("cursor", value));- }- if let Some(value) = limit {- query_params.push(("limit", value.to_string()));- }- self.client- .get_json("/wall/community", &query_params)- .await- .map_err(Into::into)- }-pub async fn update_wall_slug(&self,wall_id: &str,@@ -462,6 +457,9 @@ impl AccountWallCtx {position,blur_hash_cipher: None,variant: None,+ width: None,+ height: None,+ media_type: None,})}@@ -593,6 +591,24 @@ impl AccountWallCtx {.map_err(Into::into)}+ pub async fn list_notifications(+ &self,+ cursor: Option<String>,+ limit: Option<i32>,+ ) -> Result<WallNotificationPage> {+ let mut query = Vec::new();+ if let Some(value) = cursor.filter(|value| !value.trim().is_empty()) {+ query.push(("cursor", value));+ }+ if let Some(value) = limit {+ query.push(("limit", value.to_string()));+ }+ self.client+ .get_json("/wall/notifications", &query)+ .await+ .map_err(Into::into)+ }+pub async fn fetch_post_decrypted(&self, post_id: i64) -> Result<DecryptedPost> {let path = format!("/wall/posts/{post_id}");let post: PostResponse = self.client.get_json(&path, &[]).await?;@@ -611,13 +627,13 @@ impl AccountWallCtx {}}- let followed_records = self.list_follow_shares().await?;- let mut followed = Vec::with_capacity(followed_records.len());- for record in &followed_records {- followed.push(self.decrypt_follow_share(record)?);+ let friends_records = self.list_friend_shares().await?;+ let mut friends = Vec::with_capacity(friends_records.len());+ for record in &friends_records {+ friends.push(self.decrypt_friend_share(record)?);}- Ok(HydratedKeys { owned, followed })+ Ok(HydratedKeys { owned, friends })}pub fn decrypt_post_key(&self, wall_key: &[u8], post: &PostResponse) -> Result<Vec<u8>> {@@ -709,6 +725,20 @@ impl AccountWallCtx {.map_err(Into::into)}+ pub async fn like_comment(+ &self,+ post_id: i64,+ comment_id: i64,+ like: bool,+ ) -> Result<LikeCommentResponse> {+ let path = format!("/wall/posts/{post_id}/comments/{comment_id}/like");+ let request = LikeCommentRequest { like };+ self.client+ .post_json(&path, &request)+ .await+ .map_err(Into::into)+ }+pub async fn list_comments(&self,post_id: i64,@@ -766,170 +796,91 @@ impl AccountWallCtx {.map_err(Into::into)}- pub async fn request_follow_by_wall(- &self,- wall_id: &str,- ) -> Result<FollowRequestCreatedResponse> {- let request = FollowRequestPayload {- target_username: None,- target_wall_id: Some(wall_id.to_owned()),- };- self.client- .post_json("/wall/follow/request", &request)- .await- .map_err(Into::into)- }-- pub async fn request_follow_by_username(- &self,- username: &str,- ) -> Result<FollowRequestCreatedResponse> {- let request = FollowRequestPayload {- target_username: Some(username.to_owned()),- target_wall_id: None,- };- self.client- .post_json("/wall/follow/request", &request)- .await- .map_err(Into::into)- }-- pub async fn list_incoming_follow_requests(&self) -> Result<Vec<FollowRequestResponse>> {- self.client- .get_json("/wall/follow/requests", &[])- .await- .map_err(Into::into)- }-- pub async fn list_follow_requests(&self) -> Result<Vec<FollowRequestResponse>> {- self.list_incoming_follow_requests().await- }-- pub async fn list_outgoing_follow_requests(- &self,- ) -> Result<Vec<OutgoingFollowRequestResponse>> {- self.client- .get_json("/wall/follow/requests/outgoing", &[])- .await- .map_err(Into::into)- }-- pub async fn approve_follow_request(- &self,- request: &FollowRequestResponse,- ) -> Result<FollowRequestCreatedResponse> {- let access = self- .resolve_owned_wall_access(&request.wall_id)- .await?- .ok_or_else(|| {- WallError::InvalidInput(format!(- "wall {} is not owned by the account",- request.wall_id- ))- })?;- let follower_public_key = decode_b64(&request.follower_public_key)?;- let sealed_share = sealed::seal(&access.wall_key, &follower_public_key)?;- let payload = ApproveFollowPayload {- request_id: request.request_id,- wall_id: request.wall_id.clone(),- encrypted_wall_key: encode_b64(&pack_payload(&sealed_share, &[])),- key_version: access.key_version,+ pub async fn add_friend_from_link(&self, link: &WallLinkCtx) -> Result<FriendStatusResponse> {+ if link.owner_public_key().is_empty() {+ return Err(WallError::InvalidInput(+ "target public key is required".into(),+ ));+ }+ let (requester_wall, requester_wall_key) = self.default_owned_wall_access().await?;+ let target_share = sealed::seal(link.wall_key(), &self.public_key)?;+ let requester_share = sealed::seal(&requester_wall_key, link.owner_public_key())?;+ let payload = AddFriendPayload {+ target_wall_id: link.wall_id().to_owned(),+ link_session_token: link.session_token().to_owned(),+ requester_wall_id: requester_wall.wall_id,+ target_encrypted_wall_key: encode_b64(&pack_payload(&target_share, &[])),+ target_key_version: link.key_version(),+ requester_encrypted_wall_key: encode_b64(&pack_payload(&requester_share, &[])),+ requester_key_version: requester_wall.key_version,};self.client- .post_json("/wall/follow/approve", &payload)- .await- .map_err(Into::into)- }-- pub async fn reject_follow_request(&self, request_id: i64) -> Result<()> {- let payload = RejectFollowPayload { request_id };- self.client- .post_empty("/wall/follow/reject", &payload)+ .post_json("/wall/friends/add", &payload).await.map_err(Into::into)}- pub async fn cancel_follow_request(&self, request_id: i64) -> Result<()> {- let payload = CancelFollowRequestPayload { request_id };- self.client- .post_empty("/wall/follow/request/cancel", &payload)- .await- .map_err(Into::into)- }-- pub async fn cancel_follow_request_by_wall(&self, wall_id: &str) -> Result<()> {- let request = self- .list_outgoing_follow_requests()- .await?- .into_iter()- .find(|request| request.wall_id == wall_id)- .ok_or_else(|| {- WallError::InvalidInput(format!("no pending follow request for wall {wall_id}"))- })?;- self.cancel_follow_request(request.request_id).await- }-- pub async fn unfollow_by_wall(&self, wall_id: &str) -> Result<()> {- let request = FollowRequestPayload {+ pub async fn unfriend_by_wall(&self, wall_id: &str) -> Result<()> {+ let request = FriendTargetPayload {target_username: None,target_wall_id: Some(wall_id.to_owned()),};self.client- .post_empty("/wall/follow/unfollow", &request)+ .post_empty("/wall/friends/unfriend", &request).await.map_err(Into::into)}- pub async fn unfollow_by_username(&self, username: &str) -> Result<()> {- let request = FollowRequestPayload {+ pub async fn unfriend_by_username(&self, username: &str) -> Result<()> {+ let request = FriendTargetPayload {target_username: Some(username.to_owned()),target_wall_id: None,};self.client- .post_empty("/wall/follow/unfollow", &request)+ .post_empty("/wall/friends/unfriend", &request).await.map_err(Into::into)}- pub async fn list_wall_followers(&self, wall_id: &str) -> Result<Vec<WallFollowerResponse>> {+ pub async fn list_wall_friends(&self, wall_id: &str) -> Result<Vec<WallFriendResponse>> {let query = vec![("wallId", wall_id.to_owned())];self.client- .get_json("/wall/follow/followers", &query)+ .get_json("/wall/friends", &query).await.map_err(Into::into)}- pub async fn refresh_follow_shares(&self, wall_id: &str) -> Result<usize> {+ pub async fn refresh_friend_shares(&self, wall_id: &str) -> Result<usize> {let access = self.resolve_owned_wall_access(wall_id).await?.ok_or_else(|| {WallError::InvalidInput(format!("wall {wall_id} is not owned by the account"))})?;- let followers = self.list_wall_followers(wall_id).await?;+ let friends = self.list_wall_friends(wall_id).await?;let mut updates = Vec::new();- for follower in followers {- if follower.key_version == access.key_version {+ for friend in friends {+ if friend.key_version == access.key_version {continue;}- let public_key = decode_b64(&follower.public_key)?;+ let public_key = decode_b64(&friend.public_key)?;let sealed_share = sealed::seal(&access.wall_key, &public_key)?;updates.push(ShareUpdatePayload {- follower_id: follower.follower_id,+ friend_id: friend.friend_id,encrypted_wall_key: encode_b64(&pack_payload(&sealed_share, &[])),});}if updates.is_empty() {return Ok(0);}- let payload = RefreshFollowSharesRequest {+ let payload = RefreshFriendSharesRequest {wall_id: wall_id.to_owned(),key_version: access.key_version,shares: updates,};let updated = payload.shares.len();self.client- .post_empty("/wall/follow/shares/refresh", &payload)+ .post_empty("/wall/friends/shares/refresh", &payload).await?;Ok(updated)}@@ -992,11 +943,11 @@ impl AccountWallCtx {&self,wall_id: &str,) -> Result<Option<ResolvedWallAccess>> {- let shares = self.list_follow_shares().await?;+ let shares = self.list_friend_shares().await?;let Some(record) = shares.into_iter().find(|value| value.wall_id == wall_id) else {return Ok(None);};- let share = self.decrypt_follow_share(&record)?;+ let share = self.decrypt_friend_share(&record)?;Ok(Some(ResolvedWallAccess {wall_key: share.wall_key,key_version: share.key_version,@@ -1076,9 +1027,15 @@ impl WallLinkCtx {decrypt_secretbox_packed(&wrap_key, &decode_b64(&response.encrypted_wall_key)?)?;Ok(Self {client,+ session_token: response.session_token,owner_handle: response.owner,wall_id: response.wall_id,wall_slug: response.wall_slug,+ owner_public_key: if response.public_key.trim().is_empty() {+ Vec::new()+ } else {+ decode_b64(&response.public_key)?+ },wall_key,key_version: response.key_version,})@@ -1088,6 +1045,10 @@ impl WallLinkCtx {&self.client}+ pub fn session_token(&self) -> &str {+ &self.session_token+ }+pub fn owner(&self) -> &str {&self.owner_handle}@@ -1100,6 +1061,10 @@ impl WallLinkCtx {&self.wall_slug}+ pub fn owner_public_key(&self) -> &[u8] {+ &self.owner_public_key+ }+pub fn key_version(&self) -> i32 {self.key_version}@@ -1613,9 +1578,11 @@ mod tests {None,).expect("http client"),+ session_token: "link-token".to_owned(),owner_handle: "owner".to_owned(),wall_id: "wall_owner_gallery".to_owned(),wall_slug: "owner-gallery".to_owned(),+ owner_public_key: Vec::new(),wall_key: current_wall_key,key_version: 2,};@@ -1753,12 +1720,13 @@ mod tests {}#[tokio::test]- async fn approve_follow_request_includes_wall_key_version() {+ async fn add_friend_from_link_sends_reciprocal_wall_shares() {let mut server = Server::new_async().await;let ctx = test_account_ctx(&server.url());let root_wall_key = generate_key();- let wall_key = generate_key();- let (follower_public_key, _) = keys::generate_keypair().expect("valid follower keypair");+ let requester_wall_key = generate_key();+ let target_wall_key = generate_key();+ let (target_public_key, _) = keys::generate_keypair().expect("valid target keypair");let entity_payload =encrypt_entity_key(&ctx.master_key, &root_wall_key).expect("root wall entity");@@ -1786,120 +1754,59 @@ mod tests {.with_status(200).with_body(json!([{- "wallId": "wall_owner_main",- "wallSlug": "owner-main",- "encryptedWallKey": encode_b64(&encrypt_secretbox_packed(&root_wall_key, &wall_key).expect("wall key wrap")),+ "wallId": "wall_viewer_main",+ "wallSlug": "viewer-main",+ "encryptedWallKey": encode_b64(&encrypt_secretbox_packed(&root_wall_key, &requester_wall_key).expect("wall key wrap")),"encryptedProfile": "",- "keyVersion": 3+ "keyVersion": 4}]).to_string(),).create_async().await;- let approve = server- .mock("POST", "/wall/follow/approve")+ let add = server+ .mock("POST", "/wall/friends/add").match_header("x-auth-token", "token")- .match_body(Matcher::Regex("\"keyVersion\":3".into()))+ .match_body(Matcher::AllOf(vec![+ Matcher::Regex("\"targetWallId\":\"wall_owner_main\"".into()),+ Matcher::Regex("\"linkSessionToken\":\"link-session-token\"".into()),+ Matcher::Regex("\"requesterWallId\":\"wall_viewer_main\"".into()),+ Matcher::Regex("\"targetKeyVersion\":5".into()),+ Matcher::Regex("\"requesterKeyVersion\":4".into()),+ Matcher::Regex("\"targetEncryptedWallKey\":\"[^\"]+\"".into()),+ Matcher::Regex("\"requesterEncryptedWallKey\":\"[^\"]+\"".into()),+ ])).with_status(200)- .with_body(json!({"requestId": 11, "status": "approved"}).to_string())+ .with_body(json!({"status": "friend"}).to_string()).create_async().await;- let request = FollowRequestResponse {- request_id: 11,- follower: "viewer".to_owned(),+ let link = WallLinkCtx {+ client: build_http_client(+ &server.url(),+ Some("link-session-token".to_owned()),+ None,+ None,+ None,+ )+ .expect("http client"),+ session_token: "link-session-token".to_owned(),+ owner_handle: "owner".to_owned(),wall_id: "wall_owner_main".to_owned(),wall_slug: "owner-main".to_owned(),- follower_public_key: encode_b64(&follower_public_key),- status: "pending".to_owned(),- created_at: "2026-04-16T00:00:00Z".to_owned(),+ owner_public_key: target_public_key,+ wall_key: target_wall_key,+ key_version: 5,};let response = ctx- .approve_follow_request(&request)+ .add_friend_from_link(&link).await- .expect("approval should send key version");+ .expect("direct friendship should send reciprocal shares");- assert_eq!(response.request_id, 11);+ assert_eq!(response.status, "friend");entity.assert_async().await;walls.assert_async().await;- approve.assert_async().await;- }-- #[tokio::test]- async fn follow_request_helpers_use_explicit_incoming_and_outgoing_routes() {- let mut server = Server::new_async().await;- let ctx = test_account_ctx(&server.url());-- let incoming = server- .mock("GET", "/wall/follow/requests")- .match_header("x-auth-token", "token")- .with_status(200)- .with_body(- json!([{- "requestId": 41,- "follower": "viewer",- "wallId": "wall_owner_main",- "wallSlug": "owner-main",- "followerPublicKey": "cHVi",- "status": "pending",- "createdAt": "2026-04-16T00:00:00Z"- }])- .to_string(),- )- .create_async()- .await;- let outgoing = server- .mock("GET", "/wall/follow/requests/outgoing")- .match_header("x-auth-token", "token")- .with_status(200)- .with_body(- json!([{- "requestId": 42,- "followee": "owner",- "wallId": "wall_owner_main",- "wallSlug": "owner-main",- "status": "pending",- "createdAt": "2026-04-16T00:00:00Z"- }])- .to_string(),- )- .expect(2)- .create_async()- .await;- let cancel = server- .mock("POST", "/wall/follow/request/cancel")- .match_header("x-auth-token", "token")- .match_body(Matcher::JsonString(json!({"requestId": 42}).to_string()))- .with_status(200)- .expect(2)- .create_async()- .await;-- let incoming_requests = ctx- .list_incoming_follow_requests()- .await- .expect("incoming follow requests should load");- assert_eq!(incoming_requests.len(), 1);- assert_eq!(incoming_requests[0].request_id, 41);-- let outgoing_requests = ctx- .list_outgoing_follow_requests()- .await- .expect("outgoing follow requests should load");- assert_eq!(outgoing_requests.len(), 1);- assert_eq!(outgoing_requests[0].followee, "owner");-- ctx.cancel_follow_request(42)- .await- .expect("direct cancel should succeed");-- ctx.cancel_follow_request_by_wall("wall_owner_main")- .await- .expect("cancel by wall should resolve outgoing request");-- incoming.assert_async().await;- outgoing.assert_async().await;- cancel.assert_async().await;+ add.assert_async().await;}#[tokio::test]@@ -1919,15 +1826,8 @@ mod tests {.with_status(200).create_async().await;- let reject = server- .mock("POST", "/wall/follow/reject")- .match_header("x-auth-token", "token")- .match_body(Matcher::JsonString(json!({"requestId": 11}).to_string()))- .with_status(200)- .create_async()- .await;- let unfollow_wall = server- .mock("POST", "/wall/follow/unfollow")+ let unfriend_wall = server+ .mock("POST", "/wall/friends/unfriend").match_header("x-auth-token", "token").match_body(Matcher::JsonString(json!({"targetWallId": "wall_owner_main"}).to_string(),@@ -1935,8 +1835,8 @@ mod tests {.with_status(200).create_async().await;- let unfollow_username = server- .mock("POST", "/wall/follow/unfollow")+ let unfriend_username = server+ .mock("POST", "/wall/friends/unfriend").match_header("x-auth-token", "token").match_body(Matcher::JsonString(json!({"targetUsername": "owner"}).to_string(),@@ -1951,30 +1851,48 @@ mod tests {ctx.delete_comment(42, 7).await.expect("delete comment should accept empty response");- ctx.reject_follow_request(11)+ ctx.unfriend_by_wall("wall_owner_main").await- .expect("reject should accept empty response");- ctx.unfollow_by_wall("wall_owner_main")+ .expect("unfriend by wall should accept empty response");+ ctx.unfriend_by_username("owner").await- .expect("unfollow by wall should accept empty response");- ctx.unfollow_by_username("owner")- .await- .expect("unfollow by username should accept empty response");+ .expect("unfriend by username should accept empty response");delete_post.assert_async().await;delete_comment.assert_async().await;- reject.assert_async().await;- unfollow_wall.assert_async().await;- unfollow_username.assert_async().await;+ unfriend_wall.assert_async().await;+ unfriend_username.assert_async().await;}#[tokio::test]- async fn refresh_follow_shares_accepts_empty_server_response() {+ async fn like_comment_uses_comment_like_endpoint() {+ let mut server = Server::new_async().await;+ let ctx = test_account_ctx(&server.url());+ let like = server+ .mock("POST", "/wall/posts/42/comments/7/like")+ .match_header("x-auth-token", "token")+ .match_body(Matcher::JsonString(json!({"like": true}).to_string()))+ .with_status(200)+ .with_body(json!({"liked": true}).to_string())+ .create_async()+ .await;++ let response = ctx+ .like_comment(42, 7, true)+ .await+ .expect("comment like should succeed");++ assert!(response.liked);+ like.assert_async().await;+ }++ #[tokio::test]+ async fn refresh_friend_shares_accepts_empty_server_response() {let mut server = Server::new_async().await;let ctx = test_account_ctx(&server.url());let root_wall_key = generate_key();let wall_key = generate_key();- let (follower_public_key, _) = keys::generate_keypair().expect("valid follower keypair");+ let (friend_public_key, _) = keys::generate_keypair().expect("valid friend keypair");let entity_payload =encrypt_entity_key(&ctx.master_key, &root_wall_key).expect("root wall entity");@@ -2012,8 +1930,8 @@ mod tests {).create_async().await;- let followers = server- .mock("GET", "/wall/follow/followers")+ let friends = server+ .mock("GET", "/wall/friends").match_header("x-auth-token", "token").match_query(Matcher::UrlEncoded("wallId".into(),@@ -2022,9 +1940,9 @@ mod tests {.with_status(200).with_body(json!([{- "followerId": 7,+ "friendId": 7,"username": "viewer",- "publicKey": encode_b64(&follower_public_key),+ "publicKey": encode_b64(&friend_public_key),"keyVersion": 2,"createdAt": "2026-04-16T00:00:00Z"}])@@ -2033,10 +1951,10 @@ mod tests {.create_async().await;let refresh = server- .mock("POST", "/wall/follow/shares/refresh")+ .mock("POST", "/wall/friends/shares/refresh").match_header("x-auth-token", "token").match_body(Matcher::AllOf(vec![- Matcher::Regex("\"followerId\":7".into()),+ Matcher::Regex("\"friendId\":7".into()),Matcher::Regex("\"keyVersion\":3".into()),])).with_status(200)@@ -2044,14 +1962,14 @@ mod tests {.await;let updated = ctx- .refresh_follow_shares("wall_owner_main")+ .refresh_friend_shares("wall_owner_main").await.expect("refresh should accept empty response");assert_eq!(updated, 1);entity.assert_async().await;walls.assert_async().await;- followers.assert_async().await;+ friends.assert_async().await;refresh.assert_async().await;}@@ -2101,6 +2019,60 @@ mod tests {feed.assert_async().await;}+ #[tokio::test]+ async fn list_notifications_uses_wall_notifications_endpoint() {+ let mut server = Server::new_async().await;+ let ctx = test_account_ctx(&server.url());+ let notifications = server+ .mock("GET", "/wall/notifications")+ .match_header("x-auth-token", "token")+ .match_query(Matcher::AllOf(vec![+ Matcher::UrlEncoded("cursor".into(), "cursor-1".into()),+ Matcher::UrlEncoded("limit".into(), "5".into()),+ ]))+ .with_status(200)+ .with_body(+ json!({+ "items": [{+ "id": "post_like:42:9",+ "type": "likedPost",+ "createdAt": "2026-04-16T00:00:00Z",+ "actor": {+ "userId": 9,+ "username": "mira",+ "wallId": "wall_mira",+ "wallSlug": "mira"+ },+ "post": {+ "postId": 42,+ "wallId": "wall_owner_gallery",+ "wallSlug": "owner-gallery",+ "ownerUserId": 7,+ "author": "owner-gallery"+ }+ }],+ "nextCursor": "cursor-2"+ })+ .to_string(),+ )+ .create_async()+ .await;++ let page = ctx+ .list_notifications(Some("cursor-1".to_owned()), Some(5))+ .await+ .expect("notifications should load");++ assert_eq!(page.items.len(), 1);+ assert_eq!(+ page.items[0].notification_type,+ crate::transport::WallNotificationType::LikedPost+ );+ assert_eq!(page.items[0].actor.username, "mira");+ assert_eq!(page.next_cursor, "cursor-2");+ notifications.assert_async().await;+ }+#[tokio::test]async fn list_posts_uses_wall_posts_page_endpoint() {let mut server = Server::new_async().await;@@ -2234,7 +2206,7 @@ mod tests {}#[tokio::test]- async fn hydrate_wall_keys_loads_owned_and_followed_walls() {+ async fn hydrate_wall_keys_loads_owned_and_friends_walls() {let mut server = Server::new_async().await;let ctx = test_account_ctx(&server.url());let root_wall_key = generate_key();@@ -2280,12 +2252,12 @@ mod tests {.create_async().await;let shares = server- .mock("GET", "/wall/follow/shares")+ .mock("GET", "/wall/friends/shares").match_header("x-auth-token", "token").with_status(200).with_body(json!([{- "followee": "owner",+ "friend": "owner","wallId": "wall_shared_gallery","wallSlug": "shared-gallery","encryptedWallKey": encode_b64(&pack_payload(&sealed_share, &[])),@@ -2305,9 +2277,9 @@ mod tests {assert_eq!(hydrated.owned.len(), 1);assert_eq!(hydrated.owned[0].0, "wall_owner_gallery");assert_eq!(hydrated.owned[0].1, owned_wall_key);- assert_eq!(hydrated.followed.len(), 1);- assert_eq!(hydrated.followed[0].wall_id, "wall_shared_gallery");- assert_eq!(hydrated.followed[0].wall_key, shared_wall_key);+ assert_eq!(hydrated.friends.len(), 1);+ assert_eq!(hydrated.friends[0].wall_id, "wall_shared_gallery");+ assert_eq!(hydrated.friends[0].wall_key, shared_wall_key);entity.assert_async().await;owned.assert_async().await;shares.assert_async().await;diff --git a/rust/wall/src/lib.rs b/rust/wall/src/lib.rsindex 249e845ae2..eac985231e 100644--- a/rust/wall/src/lib.rs+++ b/rust/wall/src/lib.rs@@ -7,15 +7,15 @@ pub mod transport;pub use client::{AccountWallCtx, WallLinkCtx};pub use error::{Result, WallError};pub use models::{- AuthKeyAttributes, CreatedWall, CreatedWallLink, DecryptedComment, DecryptedFollowShare,+ AuthKeyAttributes, CreatedWall, CreatedWallLink, DecryptedComment, DecryptedFriendShare,DecryptedPost, DecryptedWallProfile, FeedItem, FeedPage, HydratedKeys, OpenAccountWallCtxInput,OpenWallLinkCtxInput, PrivateKeySource,};pub use transport::{- CommentResponse, CommunityResponse, CommunityUserResponse, EntityKeyPayload,- FollowRequestCreatedResponse, FollowRequestResponse, FollowShareResponse,- OutgoingFollowRequestResponse, PostObjectPayload, PostPage, PostResponse,- PresignUploadResponse, ProfileAvatarPayload, ProfileAvatarResponse, WallFollowerResponse,+ CommentResponse, EntityKeyPayload, FriendShareResponse, FriendStatusResponse,+ LikeCommentResponse, LikePostResponse, PostObjectPayload, PostPage, PostResponse,+ PresignUploadResponse, ProfileAvatarPayload, ProfileAvatarResponse, WallFriendResponse,WallKeyResponse, WallKeyVersionResponse, WallLinkLoginResponse, WallLinkStatusResponse,- WallLookupResponse, WallProfileResponse,+ WallLookupResponse, WallNotification, WallNotificationActor, WallNotificationComment,+ WallNotificationPage, WallNotificationPost, WallNotificationType, WallProfileResponse,};diff --git a/rust/wall/src/models.rs b/rust/wall/src/models.rsindex 19a7f9d51b..0badd9b945 100644--- a/rust/wall/src/models.rs+++ b/rust/wall/src/models.rs@@ -85,8 +85,8 @@ pub struct DecryptedComment {}#[derive(Debug, Clone)]-pub struct DecryptedFollowShare {- pub followee: String,+pub struct DecryptedFriendShare {+ pub friend: String,pub wall_id: String,pub wall_slug: String,pub wall_key: Vec<u8>,@@ -123,5 +123,5 @@ pub struct FeedPage {#[derive(Debug, Clone)]pub struct HydratedKeys {pub owned: Vec<(String, Vec<u8>)>,- pub followed: Vec<DecryptedFollowShare>,+ pub friends: Vec<DecryptedFriendShare>,}diff --git a/rust/wall/src/transport.rs b/rust/wall/src/transport.rsindex 7300dd3b66..8071843831 100644--- a/rust/wall/src/transport.rs+++ b/rust/wall/src/transport.rs@@ -92,6 +92,12 @@ pub struct PostObjectPayload {pub blur_hash_cipher: Option<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub variant: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub width: Option<i32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub height: Option<i32>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub media_type: Option<String>,}#[derive(Debug, Clone, Serialize)]@@ -122,6 +128,17 @@ pub struct LikePostResponse {pub liked: bool,}+#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct LikeCommentRequest {+ pub like: bool,+}++#[derive(Debug, Clone, Deserialize)]+pub struct LikeCommentResponse {+ pub liked: bool,+}+#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct UpdatePostCaptionRequest {@@ -168,14 +185,18 @@ pub struct CreateCommentRequest {#[serde(rename_all = "camelCase")]pub struct CommentResponse {pub comment_id: i64,+ #[serde(default)]+ pub author_id: i64,pub author: String,pub comment_cipher: String,pub created_at: String,+ #[serde(default)]+ pub likes: i64,+ #[serde(default)]+ pub viewer_liked: bool,pub viewer_can_delete: bool,#[serde(default)]pub parent_comment_id: Option<i64>,- #[serde(default)]- pub replies: Vec<CommentResponse>,}#[derive(Debug, Clone, Deserialize)]@@ -186,6 +207,75 @@ pub struct ListCommentsResponse {pub next_cursor: String,}+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum WallNotificationType {+ LikedPost,+ CommentedOnPost,+ LikedComment,+ RepliedToComment,+ AddedYouAsFriend,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WallNotificationActor {+ pub user_id: i64,+ pub username: String,+ pub wall_id: String,+ pub wall_slug: String,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WallNotificationPost {+ pub post_id: i64,+ pub wall_id: String,+ pub wall_slug: String,+ pub owner_user_id: i64,+ pub author: String,+ #[serde(default)]+ pub objects: Vec<PostObjectPayload>,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WallNotificationComment {+ pub comment_id: i64,+ #[serde(default)]+ pub author_id: i64,+ #[serde(default)]+ pub author: String,+ #[serde(default)]+ pub comment_cipher: String,+ #[serde(default)]+ pub created_at: String,+ #[serde(default)]+ pub parent_comment_id: Option<i64>,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WallNotification {+ pub id: String,+ #[serde(rename = "type")]+ pub notification_type: WallNotificationType,+ pub created_at: String,+ pub actor: WallNotificationActor,+ #[serde(default)]+ pub post: Option<WallNotificationPost>,+ #[serde(default)]+ pub comment: Option<WallNotificationComment>,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WallNotificationPage {+ pub items: Vec<WallNotification>,+ #[serde(default)]+ pub next_cursor: String,+}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "camelCase")]pub struct ProfileAvatarPayload {@@ -272,84 +362,61 @@ mod tests {#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]-pub struct FollowRequestPayload {- #[serde(skip_serializing_if = "Option::is_none")]- pub target_username: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub target_wall_id: Option<String>,-}--#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct FollowRequestCreatedResponse {- pub request_id: i64,- pub status: String,-}--#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct FollowRequestResponse {- pub request_id: i64,- pub follower: String,- pub wall_id: String,- pub wall_slug: String,- pub follower_public_key: String,- pub status: String,- pub created_at: String,+pub struct AddFriendPayload {+ pub target_wall_id: String,+ pub link_session_token: String,+ pub requester_wall_id: String,+ pub target_encrypted_wall_key: String,+ pub target_key_version: i32,+ pub requester_encrypted_wall_key: String,+ pub requester_key_version: i32,}#[derive(Debug, Clone, Deserialize)]#[serde(rename_all = "camelCase")]-pub struct OutgoingFollowRequestResponse {- pub request_id: i64,- pub followee: String,- pub wall_id: String,- pub wall_slug: String,+pub struct FriendStatusResponse {pub status: String,- pub created_at: String,-}--#[derive(Debug, Clone, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ApproveFollowPayload {- pub request_id: i64,- pub wall_id: String,- pub encrypted_wall_key: String,- pub key_version: i32,-}--#[derive(Debug, Clone, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct RejectFollowPayload {- pub request_id: i64,}#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]-pub struct CancelFollowRequestPayload {- pub request_id: i64,+pub struct FriendTargetPayload {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub target_username: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub target_wall_id: Option<String>,}#[derive(Debug, Clone, Deserialize)]#[serde(rename_all = "camelCase")]-pub struct WallFollowerResponse {- pub follower_id: i64,+pub struct WallFriendResponse {+ pub friend_id: i64,+ #[serde(default)]+ pub wall_id: String,pub username: String,pub public_key: String,pub key_version: i32,+ #[serde(default)]+ pub encrypted_profile: String,+ #[serde(default)]+ pub avatar: Option<ProfileAvatarResponse>,+ #[serde(default)]+ pub friends: i64,+ #[serde(default)]+ pub posts: i64,pub created_at: String,}#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct ShareUpdatePayload {- pub follower_id: i64,+ pub friend_id: i64,pub encrypted_wall_key: String,}#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]-pub struct RefreshFollowSharesRequest {+pub struct RefreshFriendSharesRequest {pub wall_id: String,pub key_version: i32,pub shares: Vec<ShareUpdatePayload>,@@ -357,8 +424,8 @@ pub struct RefreshFollowSharesRequest {#[derive(Debug, Clone, Deserialize)]#[serde(rename_all = "camelCase")]-pub struct FollowShareResponse {- pub followee: String,+pub struct FriendShareResponse {+ pub friend: String,pub wall_id: String,pub wall_slug: String,pub encrypted_wall_key: String,@@ -399,6 +466,8 @@ pub struct WallLinkLoginResponse {pub wall_id: String,pub wall_slug: String,pub owner: String,+ #[serde(default)]+ pub public_key: String,pub key_version: i32,pub encrypted_wall_key: String,}@@ -420,28 +489,6 @@ pub struct WallLookupResponse {pub wall_id: String,pub wall_slug: String,pub owner: String,-}--#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct CommunityUserResponse {- pub username: String,- pub wall_id: String,- pub wall_slug: String,- pub followers: i64,- #[serde(default)]- pub following: i64,- pub posts: i64,#[serde(default)]- pub relationship: String,- #[serde(default)]- pub bio: String,-}--#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct CommunityResponse {- pub users: Vec<CommunityUserResponse>,- #[serde(default)]- pub next_cursor: String,+ pub public_key: String,}diff --git a/server/migrations/121_wall.down.sql b/server/migrations/121_wall.down.sqlindex c982cd4f03..be317fd327 100644--- a/server/migrations/121_wall.down.sql+++ b/server/migrations/121_wall.down.sql@@ -3,11 +3,12 @@ DROP TABLE IF EXISTS wall_link_sessions;DROP TRIGGER IF EXISTS update_wall_links_updated_at ON wall_links;DROP TABLE IF EXISTS wall_links;-DROP TRIGGER IF EXISTS update_wall_follow_shares_updated_at ON wall_follow_shares;-DROP TABLE IF EXISTS wall_follow_shares;+DROP TABLE IF EXISTS wall_friend_events;-DROP TRIGGER IF EXISTS update_wall_follow_requests_updated_at ON wall_follow_requests;-DROP TABLE IF EXISTS wall_follow_requests;+DROP TRIGGER IF EXISTS update_wall_friend_shares_updated_at ON wall_friend_shares;+DROP TABLE IF EXISTS wall_friend_shares;++DROP TABLE IF EXISTS wall_comment_likes;DROP TRIGGER IF EXISTS update_wall_post_comments_updated_at ON wall_post_comments;DROP TABLE IF EXISTS wall_post_comments;diff --git a/server/migrations/121_wall.up.sql b/server/migrations/121_wall.up.sqlindex 91aa243e8b..58b0319bc7 100644--- a/server/migrations/121_wall.up.sql+++ b/server/migrations/121_wall.up.sql@@ -69,6 +69,9 @@ CREATE TABLE IF NOT EXISTS wall_post_assets (position INTEGER NOT NULL DEFAULT 0,variant TEXT,blur_hash_cipher TEXT,+ width INTEGER,+ height INTEGER,+ media_type TEXT,created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),CONSTRAINT uq_wall_post_assets_object_key UNIQUE (object_key),CONSTRAINT uq_wall_post_assets_position UNIQUE (post_id, position, variant)@@ -130,49 +133,50 @@ CREATE TRIGGER update_wall_post_comments_updated_atFOR EACH ROWEXECUTE PROCEDURE trigger_updated_at_microseconds_column();-CREATE TABLE IF NOT EXISTS wall_follow_requests (- request_id BIGSERIAL PRIMARY KEY,- requester_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,- target_wall_id TEXT NOT NULL REFERENCES walls (wall_id) ON DELETE CASCADE,- status TEXT NOT NULL DEFAULT 'pending',- created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),- updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),- CONSTRAINT chk_wall_follow_requests_status CHECK (status IN ('pending', 'approved', 'rejected', 'cancelled', 'unfollowed'))+CREATE TABLE IF NOT EXISTS wall_comment_likes (+ comment_id BIGINT NOT NULL REFERENCES wall_post_comments (comment_id) ON DELETE CASCADE,+ user_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),+ PRIMARY KEY (comment_id, user_id));-CREATE INDEX IF NOT EXISTS idx_wall_follow_requests_target_status- ON wall_follow_requests (target_wall_id, status, created_at DESC);--CREATE INDEX IF NOT EXISTS idx_wall_follow_requests_requester_status- ON wall_follow_requests (requester_id, status, created_at DESC);+CREATE INDEX IF NOT EXISTS idx_wall_comment_likes_comment_id+ ON wall_comment_likes (comment_id);-CREATE UNIQUE INDEX IF NOT EXISTS uq_wall_follow_requests_pending- ON wall_follow_requests (requester_id, target_wall_id)- WHERE status = 'pending';--CREATE TRIGGER update_wall_follow_requests_updated_at- BEFORE UPDATE ON wall_follow_requests- FOR EACH ROW-EXECUTE PROCEDURE trigger_updated_at_microseconds_column();+CREATE INDEX IF NOT EXISTS idx_wall_comment_likes_user_id+ ON wall_comment_likes (user_id, created_at DESC);-CREATE TABLE IF NOT EXISTS wall_follow_shares (+CREATE TABLE IF NOT EXISTS wall_friend_shares (wall_id TEXT NOT NULL REFERENCES walls (wall_id) ON DELETE CASCADE,- follower_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,+ friend_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,encrypted_wall_key TEXT NOT NULL,key_version INTEGER NOT NULL DEFAULT 1,created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),- PRIMARY KEY (wall_id, follower_id)+ PRIMARY KEY (wall_id, friend_id));-CREATE INDEX IF NOT EXISTS idx_wall_follow_shares_follower- ON wall_follow_shares (follower_id, created_at DESC);+CREATE INDEX IF NOT EXISTS idx_wall_friend_shares_friend+ ON wall_friend_shares (friend_id, created_at DESC);-CREATE TRIGGER update_wall_follow_shares_updated_at- BEFORE UPDATE ON wall_follow_shares+CREATE TRIGGER update_wall_friend_shares_updated_at+ BEFORE UPDATE ON wall_friend_sharesFOR EACH ROWEXECUTE PROCEDURE trigger_updated_at_microseconds_column();+CREATE TABLE IF NOT EXISTS wall_friend_events (+ event_id BIGSERIAL PRIMARY KEY,+ actor_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,+ actor_wall_id TEXT NOT NULL REFERENCES walls (wall_id) ON DELETE CASCADE,+ target_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,+ target_wall_id TEXT NOT NULL REFERENCES walls (wall_id) ON DELETE CASCADE,+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),+ CONSTRAINT chk_wall_friend_events_distinct_users CHECK (actor_id <> target_id)+);++CREATE INDEX IF NOT EXISTS idx_wall_friend_events_target_created+ ON wall_friend_events (target_id, created_at DESC);+CREATE TABLE IF NOT EXISTS wall_links (wall_id TEXT PRIMARY KEY REFERENCES walls (wall_id) ON DELETE CASCADE,auth_key_hash BYTEA NOT NULL UNIQUE,diff --git a/server/wall/api/follow.go b/server/wall/api/follow.godeleted file mode 100644index e09b29cafa..0000000000--- a/server/wall/api/follow.go+++ /dev/null@@ -1,98 +0,0 @@-package api--import (- "github.com/ente-io/museum/ente"- "github.com/ente-io/museum/wall/models"- "github.com/gin-gonic/gin"-)--func (h *Handlers) Community(c *gin.Context) {- var req models.CommunityRequest- if err := c.ShouldBindQuery(&req); err != nil {- respondJSON(c, nil, ente.ErrBadRequest)- return- }- resp, err := h.Module.Follow.Community(c, req)- respondJSON(c, resp, err)-}--func (h *Handlers) FollowRequest(c *gin.Context) {- var req models.FollowRequestPayload- if err := c.ShouldBindJSON(&req); err != nil {- respondJSON(c, nil, ente.ErrBadRequest)- return- }- resp, err := h.Module.Follow.Request(c, req)- respondJSON(c, resp, err)-}--func (h *Handlers) ListFollowRequests(c *gin.Context) {- resp, err := h.Module.Follow.ListRequests(c)- respondJSON(c, resp, err)-}--func (h *Handlers) ListOutgoingFollowRequests(c *gin.Context) {- resp, err := h.Module.Follow.ListOutgoingRequests(c)- respondJSON(c, resp, err)-}--func (h *Handlers) CancelFollowRequest(c *gin.Context) {- var req models.CancelFollowRequestPayload- if err := c.ShouldBindJSON(&req); err != nil {- respondJSON(c, nil, ente.ErrBadRequest)- return- }- respondStatus(c, h.Module.Follow.CancelRequest(c, req))-}--func (h *Handlers) ApproveFollow(c *gin.Context) {- var req models.ApproveFollowPayload- if err := c.ShouldBindJSON(&req); err != nil {- respondJSON(c, nil, ente.ErrBadRequest)- return- }- resp, err := h.Module.Follow.Approve(c, req)- respondJSON(c, resp, err)-}--func (h *Handlers) RejectFollow(c *gin.Context) {- var req models.RejectFollowPayload- if err := c.ShouldBindJSON(&req); err != nil {- respondJSON(c, nil, ente.ErrBadRequest)- return- }- respondStatus(c, h.Module.Follow.Reject(c, req))-}--func (h *Handlers) Unfollow(c *gin.Context) {- var req models.FollowRequestPayload- if err := c.ShouldBindJSON(&req); err != nil {- respondJSON(c, nil, ente.ErrBadRequest)- return- }- respondStatus(c, h.Module.Follow.Unfollow(c, req))-}--func (h *Handlers) ListWallFollowers(c *gin.Context) {- var req models.ListWallFollowersRequest- if err := c.ShouldBindQuery(&req); err != nil {- respondJSON(c, nil, ente.ErrBadRequest)- return- }- resp, err := h.Module.Follow.ListFollowers(c, req)- respondJSON(c, resp, err)-}--func (h *Handlers) RefreshFollowShares(c *gin.Context) {- var req models.RefreshFollowSharesRequest- if err := c.ShouldBindJSON(&req); err != nil {- respondJSON(c, nil, ente.ErrBadRequest)- return- }- respondStatus(c, h.Module.Follow.RefreshShares(c, req))-}--func (h *Handlers) ListFollowShares(c *gin.Context) {- resp, err := h.Module.Follow.ListShares(c)- respondJSON(c, resp, err)-}diff --git a/server/wall/api/friends.go b/server/wall/api/friends.gonew file mode 100644index 0000000000..a4fb59bbd5--- /dev/null+++ b/server/wall/api/friends.go@@ -0,0 +1,50 @@+package api++import (+ "github.com/ente-io/museum/ente"+ "github.com/ente-io/museum/wall/models"+ "github.com/gin-gonic/gin"+)++func (h *Handlers) AddFriend(c *gin.Context) {+ var req models.AddFriendPayload+ if err := c.ShouldBindJSON(&req); err != nil {+ respondJSON(c, nil, ente.ErrBadRequest)+ return+ }+ resp, err := h.Module.Friends.Add(c, req)+ respondJSON(c, resp, err)+}++func (h *Handlers) Unfriend(c *gin.Context) {+ var req models.FriendTargetPayload+ if err := c.ShouldBindJSON(&req); err != nil {+ respondJSON(c, nil, ente.ErrBadRequest)+ return+ }+ respondStatus(c, h.Module.Friends.Unfriend(c, req))+}++func (h *Handlers) ListWallFriends(c *gin.Context) {+ var req models.ListWallFriendsRequest+ if err := c.ShouldBindQuery(&req); err != nil {+ respondJSON(c, nil, ente.ErrBadRequest)+ return+ }+ resp, err := h.Module.Friends.ListFriends(c, req)+ respondJSON(c, resp, err)+}++func (h *Handlers) RefreshFriendShares(c *gin.Context) {+ var req models.RefreshFriendSharesRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ respondJSON(c, nil, ente.ErrBadRequest)+ return+ }+ respondStatus(c, h.Module.Friends.RefreshShares(c, req))+}++func (h *Handlers) ListFriendShares(c *gin.Context) {+ resp, err := h.Module.Friends.ListShares(c)+ respondJSON(c, resp, err)+}diff --git a/server/wall/api/notifications.go b/server/wall/api/notifications.gonew file mode 100644index 0000000000..ee4f1d02b8--- /dev/null+++ b/server/wall/api/notifications.go@@ -0,0 +1,17 @@+package api++import (+ "github.com/ente-io/museum/ente"+ "github.com/ente-io/museum/wall/models"+ "github.com/gin-gonic/gin"+)++func (h *Handlers) ListNotifications(c *gin.Context) {+ var req models.ListNotificationsRequest+ if err := c.ShouldBindQuery(&req); err != nil {+ respondJSON(c, nil, ente.ErrBadRequest)+ return+ }+ resp, err := h.Module.Notifications.List(c, req)+ respondJSON(c, resp, err)+}diff --git a/server/wall/api/posts.go b/server/wall/api/posts.goindex 1ad0f97aaf..14eb3a62fa 100644--- a/server/wall/api/posts.go+++ b/server/wall/api/posts.go@@ -80,6 +80,16 @@ func (h *Handlers) CreateComment(c *gin.Context) {respondJSON(c, resp, err)}+func (h *Handlers) ToggleCommentLike(c *gin.Context) {+ var req models.LikeCommentRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ respondJSON(c, nil, ente.ErrBadRequest)+ return+ }+ resp, err := h.Module.Posts.ToggleCommentLike(c, c.Param("postID"), c.Param("commentID"), req)+ respondJSON(c, resp, err)+}+func (h *Handlers) DeleteComment(c *gin.Context) {respondStatus(c, h.Module.Posts.DeleteComment(c, c.Param("postID"), c.Param("commentID")))}diff --git a/server/wall/api/register.go b/server/wall/api/register.goindex b5091591b3..f8396968f1 100644--- a/server/wall/api/register.go+++ b/server/wall/api/register.go@@ -16,18 +16,14 @@ func Register(privateAPI, publicAPI gin.IRoutes, handlers *Handlers) {privateAPI.POST("/wall/posts/:postID/like", handlers.TogglePostLike)privateAPI.DELETE("/wall/posts/:postID", handlers.DeletePost)privateAPI.POST("/wall/posts/:postID/comments", handlers.CreateComment)+ privateAPI.POST("/wall/posts/:postID/comments/:commentID/like", handlers.ToggleCommentLike)privateAPI.DELETE("/wall/posts/:postID/comments/:commentID", handlers.DeleteComment)- privateAPI.GET("/wall/community", handlers.Community)- privateAPI.POST("/wall/follow/request", handlers.FollowRequest)- privateAPI.GET("/wall/follow/requests", handlers.ListFollowRequests)- privateAPI.GET("/wall/follow/requests/outgoing", handlers.ListOutgoingFollowRequests)- privateAPI.POST("/wall/follow/request/cancel", handlers.CancelFollowRequest)- privateAPI.POST("/wall/follow/approve", handlers.ApproveFollow)- privateAPI.POST("/wall/follow/reject", handlers.RejectFollow)- privateAPI.POST("/wall/follow/unfollow", handlers.Unfollow)- privateAPI.GET("/wall/follow/followers", handlers.ListWallFollowers)- privateAPI.POST("/wall/follow/shares/refresh", handlers.RefreshFollowShares)- privateAPI.GET("/wall/follow/shares", handlers.ListFollowShares)+ privateAPI.GET("/wall/notifications", handlers.ListNotifications)+ privateAPI.POST("/wall/friends/add", handlers.AddFriend)+ privateAPI.POST("/wall/friends/unfriend", handlers.Unfriend)+ privateAPI.GET("/wall/friends", handlers.ListWallFriends)+ privateAPI.POST("/wall/friends/shares/refresh", handlers.RefreshFriendShares)+ privateAPI.GET("/wall/friends/shares", handlers.ListFriendShares)privateAPI.POST("/wall/rotate", handlers.RotateWallKey)privateAPI.GET("/wall/links/:wallID", handlers.GetWallLink)privateAPI.POST("/wall/links", handlers.CreateWallLink)diff --git a/server/wall/controller/assets.go b/server/wall/controller/assets.goindex f23354effb..ab84acb29c 100644--- a/server/wall/controller/assets.go+++ b/server/wall/controller/assets.go@@ -18,7 +18,7 @@ import ()const (- maxUploadBytes int64 = 2 * 1024 * 1024+ maxUploadBytes int64 = 20 * 1024 * 1024uploadURLExpiry = 15 * time.MinuteuploadTempObjectExpiry = 2 * uploadURLExpiryuploadPurposePost = wallrepo.TempObjectPurposePost@@ -29,7 +29,6 @@ const (type AssetsController struct {AssetsRepo *wallrepo.AssetsRepositoryWallsRepo *wallrepo.WallsRepository- FollowRepo *wallrepo.FollowRepositoryLinksRepo *wallrepo.LinksRepositoryauth authDeps}diff --git a/server/wall/controller/auth.go b/server/wall/controller/auth.goindex 6fb2efb41a..09e93d8bc7 100644--- a/server/wall/controller/auth.go+++ b/server/wall/controller/auth.go@@ -5,6 +5,7 @@ import ("crypto/sha256""database/sql""errors"+ "strings""github.com/ente-io/museum/ente"baserepo "github.com/ente-io/museum/pkg/repo"@@ -24,7 +25,7 @@ type authDeps struct {UserAuthRepo *baserepo.UserAuthRepositoryLinksRepo *wallrepo.LinksRepositoryWallsRepo *wallrepo.WallsRepository- FollowRepo *wallrepo.FollowRepository+ FriendsRepo *wallrepo.FriendsRepository}func (a authDeps) requireUser(c *gin.Context) (int64, error) {@@ -78,6 +79,26 @@ func (a authDeps) requireWallOwner(ctx context.Context, ownerID int64, wallID streturn wall, nil}+func (a authDeps) requireLinkSession(ctx context.Context, token string) (*wallrepo.WallLinkSessionRecord, error) {+ token = strings.TrimSpace(token)+ if token == "" || a.LinksRepo == nil {+ return nil, ente.ErrAuthenticationRequired+ }+ sum := sha256.Sum256([]byte(token))+ session, err := a.LinksRepo.GetSession(ctx, sum[:])+ if err != nil {+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {+ return nil, ente.ErrAuthenticationRequired+ }+ return nil, err+ }+ if session.ExpiresAt <= timeutil.Microseconds() {+ _ = a.LinksRepo.DeleteSession(ctx, sum[:])+ return nil, ente.ErrAuthenticationRequired+ }+ return session, nil+}+func (a authDeps) canViewWall(ctx context.Context, viewer *viewerAuth, wall *wallrepo.WallRecord) error {switch {case viewer == nil:@@ -86,7 +107,7 @@ func (a authDeps) canViewWall(ctx context.Context, viewer *viewerAuth, wall *walif viewer.UserID == wall.OwnerID {return nil}- _, err := a.FollowRepo.GetShareForFollowerAndWall(ctx, viewer.UserID, wall.WallID)+ _, err := a.FriendsRepo.GetShareForFriendAndWall(ctx, viewer.UserID, wall.WallID)if err != nil {if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {return ente.ErrPermissionDenieddiff --git a/server/wall/controller/follow.go b/server/wall/controller/follow.godeleted file mode 100644index cf8d834872..0000000000--- a/server/wall/controller/follow.go+++ /dev/null@@ -1,299 +0,0 @@-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 FollowController struct {- FollowRepo *repo.FollowRepository- WallsRepo *repo.WallsRepository- auth authDeps-}--func (c *FollowController) Community(ctx *gin.Context, req models.CommunityRequest) (*models.CommunityResponse, error) {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return nil, err- }- users, next, err := c.FollowRepo.ListCommunity(ctx.Request.Context(), userID, req.Query, req.Cursor, req.Limit)- if err != nil {- return nil, err- }- resp := &models.CommunityResponse{NextCursor: next, Users: make([]models.CommunityUserResponse, 0, len(users))}- for _, user := range users {- resp.Users = append(resp.Users, models.CommunityUserResponse{- Username: user.Username,- WallID: user.WallID,- WallSlug: user.WallSlug,- Followers: user.Followers,- Following: user.Following,- Posts: user.Posts,- Relationship: user.Relationship,- Bio: user.Bio,- })- }- return resp, nil-}--func (c *FollowController) Request(ctx *gin.Context, req models.FollowRequestPayload) (*models.FollowRequestCreatedResponse, error) {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return nil, err- }- var wall *repo.WallRecord- switch {- case req.TargetWallID != nil && strings.TrimSpace(*req.TargetWallID) != "":- wall, err = c.WallsRepo.GetWallByID(ctx.Request.Context(), strings.TrimSpace(*req.TargetWallID))- case req.TargetUsername != nil && strings.TrimSpace(*req.TargetUsername) != "":- wall, err = c.WallsRepo.GetWallBySlug(ctx.Request.Context(), strings.TrimSpace(*req.TargetUsername))- default:- return nil, ente.NewBadRequestWithMessage("targetUsername or targetWallId is required")- }- if err != nil {- return nil, err- }- if wall.OwnerID == userID {- return nil, ente.NewBadRequestWithMessage("cannot follow yourself")- }- created, err := c.FollowRepo.CreateRequest(ctx.Request.Context(), userID, wall.WallID)- if err != nil {- if errors.Is(stacktrace.RootCause(err), repo.ErrAlreadyFollowing) {- return nil, ente.NewBadRequestWithMessage("already following this wall")- }- return nil, err- }- return &models.FollowRequestCreatedResponse{RequestID: created.RequestID, Status: created.Status}, nil-}--func (c *FollowController) ListRequests(ctx *gin.Context) ([]models.FollowRequestResponse, error) {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return nil, err- }- requests, err := c.FollowRepo.ListIncomingRequests(ctx.Request.Context(), userID)- if err != nil {- return nil, err- }- resp := make([]models.FollowRequestResponse, 0, len(requests))- for _, request := range requests {- resp = append(resp, models.FollowRequestResponse{- RequestID: request.RequestID,- Follower: request.RequesterSlug,- WallID: request.TargetWallID,- WallSlug: request.TargetSlug,- FollowerPublicKey: request.RequesterKey,- Status: request.Status,- CreatedAt: formatMicros(request.CreatedAt),- })- }- return resp, nil-}--func (c *FollowController) ListOutgoingRequests(ctx *gin.Context) ([]models.OutgoingFollowRequestResponse, error) {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return nil, err- }- requests, err := c.FollowRepo.ListOutgoingRequests(ctx.Request.Context(), userID)- if err != nil {- return nil, err- }- resp := make([]models.OutgoingFollowRequestResponse, 0, len(requests))- for _, request := range requests {- resp = append(resp, models.OutgoingFollowRequestResponse{- RequestID: request.RequestID,- Followee: request.TargetSlug,- WallID: request.TargetWallID,- WallSlug: request.TargetSlug,- Status: request.Status,- CreatedAt: formatMicros(request.CreatedAt),- })- }- return resp, nil-}--func (c *FollowController) CancelRequest(ctx *gin.Context, req models.CancelFollowRequestPayload) error {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return err- }- record, err := c.FollowRepo.GetRequest(ctx.Request.Context(), req.RequestID)- if err != nil {- return err- }- if record.RequesterID != userID {- return ente.ErrPermissionDenied- }- if err := c.FollowRepo.UpdatePendingRequestStatus(ctx.Request.Context(), req.RequestID, "cancelled"); err != nil {- if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {- return ente.NewBadRequestWithMessage("follow request is not pending")- }- return err- }- return nil-}--func (c *FollowController) Approve(ctx *gin.Context, req models.ApproveFollowPayload) (*models.FollowRequestCreatedResponse, error) {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return nil, err- }- if req.RequestID <= 0 || strings.TrimSpace(req.WallID) == "" || strings.TrimSpace(req.EncryptedWallKey) == "" || req.KeyVersion <= 0 {- return nil, ente.NewBadRequestWithMessage("requestId, wallId, encryptedWallKey and keyVersion are required")- }- wall, err := c.auth.requireWallOwner(ctx.Request.Context(), userID, req.WallID)- if err != nil {- return nil, err- }- record, err := c.FollowRepo.ApproveRequest(ctx.Request.Context(), req.RequestID, wall.WallID, req.EncryptedWallKey, req.KeyVersion)- if err != nil {- if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {- return nil, ente.NewBadRequestWithMessage("follow request is not pending or keyVersion does not match current wall version")- }- return nil, err- }- return &models.FollowRequestCreatedResponse{RequestID: record.RequestID, Status: record.Status}, nil-}--func (c *FollowController) Reject(ctx *gin.Context, req models.RejectFollowPayload) error {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return err- }- record, err := c.FollowRepo.GetRequest(ctx.Request.Context(), req.RequestID)- if err != nil {- return err- }- wall, err := c.WallsRepo.GetWallByID(ctx.Request.Context(), record.TargetWallID)- if err != nil {- return err- }- if wall.OwnerID != userID {- return ente.ErrPermissionDenied- }- if err := c.FollowRepo.UpdatePendingRequestStatus(ctx.Request.Context(), req.RequestID, "rejected"); err != nil {- if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {- return ente.NewBadRequestWithMessage("follow request is not pending")- }- return err- }- return nil-}--func (c *FollowController) Unfollow(ctx *gin.Context, req models.FollowRequestPayload) error {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return err- }- var wall *repo.WallRecord- switch {- case req.TargetWallID != nil && strings.TrimSpace(*req.TargetWallID) != "":- wall, err = c.WallsRepo.GetWallByID(ctx.Request.Context(), strings.TrimSpace(*req.TargetWallID))- case req.TargetUsername != nil && strings.TrimSpace(*req.TargetUsername) != "":- wall, err = c.WallsRepo.GetWallBySlug(ctx.Request.Context(), strings.TrimSpace(*req.TargetUsername))- default:- return ente.NewBadRequestWithMessage("targetUsername or targetWallId is required")- }- if err != nil {- return err- }- if err := c.FollowRepo.DeleteShareByWallAndFollower(ctx.Request.Context(), wall.WallID, userID); err != nil {- return err- }- requests, err := c.FollowRepo.ListOutgoingRequests(ctx.Request.Context(), userID)- if err == nil {- for _, request := range requests {- if request.TargetWallID == wall.WallID {- _ = c.FollowRepo.UpdateRequestStatus(ctx.Request.Context(), request.RequestID, "unfollowed")- }- }- }- return nil-}--func (c *FollowController) ListFollowers(ctx *gin.Context, req models.ListWallFollowersRequest) ([]models.WallFollowerResponse, error) {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return nil, err- }- wall, err := c.auth.requireWallOwner(ctx.Request.Context(), userID, req.WallID)- if err != nil {- return nil, err- }- followers, err := c.FollowRepo.ListFollowersForWall(ctx.Request.Context(), wall.WallID)- if err != nil {- return nil, err- }- resp := make([]models.WallFollowerResponse, 0, len(followers))- for _, follower := range followers {- resp = append(resp, models.WallFollowerResponse{- FollowerID: follower.FollowerID,- Username: follower.Username,- PublicKey: follower.PublicKey,- KeyVersion: follower.KeyVersion,- CreatedAt: formatMicros(follower.CreatedAt),- })- }- return resp, nil-}--func (c *FollowController) RefreshShares(ctx *gin.Context, req models.RefreshFollowSharesRequest) error {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return err- }- wall, err := c.auth.requireWallOwner(ctx.Request.Context(), userID, req.WallID)- if err != nil {- return err- }- if req.KeyVersion <= 0 {- return ente.NewBadRequestWithMessage("keyVersion is required")- }- updates := make([]repo.WallShareUpdateRecord, 0, len(req.Shares))- for _, share := range req.Shares {- if share.FollowerID == 0 || strings.TrimSpace(share.EncryptedWallKey) == "" {- return ente.NewBadRequestWithMessage("followerId and encryptedWallKey are required for each share")- }- updates = append(updates, repo.WallShareUpdateRecord{- FollowerID: share.FollowerID,- EncryptedWallKey: share.EncryptedWallKey,- })- }- if err := c.FollowRepo.UpdateShares(ctx.Request.Context(), wall.WallID, updates, req.KeyVersion); err != nil {- if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {- return ente.NewBadRequestWithMessage("keyVersion does not match current wall version or follow share does not exist")- }- return err- }- return nil-}--func (c *FollowController) ListShares(ctx *gin.Context) ([]models.FollowShareResponse, error) {- userID, err := c.auth.requireUser(ctx)- if err != nil {- return nil, err- }- shares, err := c.FollowRepo.ListSharesForFollower(ctx.Request.Context(), userID)- if err != nil {- return nil, err- }- resp := make([]models.FollowShareResponse, 0, len(shares))- for _, share := range shares {- resp = append(resp, models.FollowShareResponse{- Followee: share.FolloweeSlug,- WallID: share.WallID,- WallSlug: share.FolloweeSlug,- EncryptedWallKey: share.EncryptedWallKey,- KeyVersion: share.KeyVersion,- })- }- return resp, nil-}diff --git a/server/wall/controller/friends.go b/server/wall/controller/friends.gonew file mode 100644index 0000000000..66c10e3b24--- /dev/null+++ b/server/wall/controller/friends.go@@ -0,0 +1,180 @@+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 FriendsController struct {+ FriendsRepo *repo.FriendsRepository+ WallsRepo *repo.WallsRepository+ auth authDeps+}++func (c *FriendsController) Add(ctx *gin.Context, req models.AddFriendPayload) (*models.FriendStatusResponse, error) {+ userID, err := c.auth.requireUser(ctx)+ if err != nil {+ return nil, err+ }+ if strings.TrimSpace(req.TargetWallID) == "" ||+ strings.TrimSpace(req.LinkSessionToken) == "" ||+ strings.TrimSpace(req.RequesterWallID) == "" ||+ strings.TrimSpace(req.TargetEncryptedWallKey) == "" ||+ strings.TrimSpace(req.RequesterEncryptedWallKey) == "" ||+ req.TargetKeyVersion <= 0 ||+ req.RequesterKeyVersion <= 0 {+ return nil, ente.NewBadRequestWithMessage("targetWallId, linkSessionToken, requesterWallId, encrypted wall keys and key versions are required")+ }+ session, err := c.auth.requireLinkSession(ctx.Request.Context(), req.LinkSessionToken)+ if err != nil {+ return nil, err+ }+ if session.WallID != strings.TrimSpace(req.TargetWallID) {+ return nil, ente.ErrPermissionDenied+ }+ if session.KeyVersion != req.TargetKeyVersion {+ return nil, ente.NewBadRequestWithMessage("targetKeyVersion does not match link session")+ }+ if _, err := c.auth.requireWallOwner(ctx.Request.Context(), userID, strings.TrimSpace(req.RequesterWallID)); err != nil {+ return nil, err+ }+ if err := c.FriendsRepo.AddFriend(+ ctx.Request.Context(),+ userID,+ strings.TrimSpace(req.RequesterWallID),+ strings.TrimSpace(req.TargetWallID),+ strings.TrimSpace(req.TargetEncryptedWallKey),+ req.TargetKeyVersion,+ strings.TrimSpace(req.RequesterEncryptedWallKey),+ req.RequesterKeyVersion,+ ); err != nil {+ if errors.Is(stacktrace.RootCause(err), repo.ErrAlreadyFriends) {+ return &models.FriendStatusResponse{Status: "friend"}, nil+ }+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {+ return nil, ente.NewBadRequestWithMessage("wall key version is stale")+ }+ return nil, err+ }+ return &models.FriendStatusResponse{Status: "friend"}, nil+}++func (c *FriendsController) Unfriend(ctx *gin.Context, req models.FriendTargetPayload) error {+ userID, err := c.auth.requireUser(ctx)+ if err != nil {+ return err+ }+ var wall *repo.WallRecord+ switch {+ case req.TargetWallID != nil && strings.TrimSpace(*req.TargetWallID) != "":+ wall, err = c.WallsRepo.GetWallByID(ctx.Request.Context(), strings.TrimSpace(*req.TargetWallID))+ case req.TargetUsername != nil && strings.TrimSpace(*req.TargetUsername) != "":+ wall, err = c.WallsRepo.GetWallBySlug(ctx.Request.Context(), strings.TrimSpace(*req.TargetUsername))+ default:+ return ente.NewBadRequestWithMessage("targetUsername or targetWallId is required")+ }+ if err != nil {+ return err+ }+ return c.FriendsRepo.DeleteFriendship(ctx.Request.Context(), userID, wall.WallID)+}++func (c *FriendsController) ListFriends(ctx *gin.Context, req models.ListWallFriendsRequest) ([]models.WallFriendResponse, error) {+ userID, err := c.auth.requireUser(ctx)+ if err != nil {+ return nil, err+ }+ wall, err := c.auth.requireWallOwner(ctx.Request.Context(), userID, req.WallID)+ if err != nil {+ return nil, err+ }+ friends, err := c.FriendsRepo.ListFriendsForWall(ctx.Request.Context(), wall.WallID)+ if err != nil {+ return nil, err+ }+ resp := make([]models.WallFriendResponse, 0, len(friends))+ for _, friend := range friends {+ var avatar *models.ProfileAvatarResponse+ if friend.AvatarObjectKey.Valid {+ avatar = &models.ProfileAvatarResponse{+ ObjectKey: friend.AvatarObjectKey.String,+ }+ if friend.AvatarSize.Valid {+ avatar.Size = friend.AvatarSize.Int64+ }+ }+ resp = append(resp, models.WallFriendResponse{+ FriendID: friend.FriendID,+ WallID: friend.WallID,+ Username: friend.Username,+ PublicKey: friend.PublicKey,+ KeyVersion: friend.KeyVersion,+ EncryptedProfile: friend.EncryptedProfile,+ Avatar: avatar,+ Friends: friend.Friends,+ Posts: friend.Posts,+ CreatedAt: formatMicros(friend.CreatedAt),+ })+ }+ return resp, nil+}++func (c *FriendsController) RefreshShares(ctx *gin.Context, req models.RefreshFriendSharesRequest) error {+ userID, err := c.auth.requireUser(ctx)+ if err != nil {+ return err+ }+ wall, err := c.auth.requireWallOwner(ctx.Request.Context(), userID, req.WallID)+ if err != nil {+ return err+ }+ if req.KeyVersion <= 0 {+ return ente.NewBadRequestWithMessage("keyVersion is required")+ }+ updates := make([]repo.WallShareUpdateRecord, 0, len(req.Shares))+ for _, share := range req.Shares {+ if share.FriendID == 0 || strings.TrimSpace(share.EncryptedWallKey) == "" {+ return ente.NewBadRequestWithMessage("friendId and encryptedWallKey are required for each share")+ }+ updates = append(updates, repo.WallShareUpdateRecord{+ FriendID: share.FriendID,+ EncryptedWallKey: share.EncryptedWallKey,+ })+ }+ if err := c.FriendsRepo.UpdateShares(ctx.Request.Context(), wall.WallID, updates, req.KeyVersion); err != nil {+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {+ return ente.NewBadRequestWithMessage("keyVersion does not match current wall version or friend share does not exist")+ }+ return err+ }+ return nil+}++func (c *FriendsController) ListShares(ctx *gin.Context) ([]models.FriendShareResponse, error) {+ userID, err := c.auth.requireUser(ctx)+ if err != nil {+ return nil, err+ }+ shares, err := c.FriendsRepo.ListSharesForFriend(ctx.Request.Context(), userID)+ if err != nil {+ return nil, err+ }+ resp := make([]models.FriendShareResponse, 0, len(shares))+ for _, share := range shares {+ resp = append(resp, models.FriendShareResponse{+ Friend: share.WallSlug,+ WallID: share.WallID,+ WallSlug: share.WallSlug,+ EncryptedWallKey: share.EncryptedWallKey,+ KeyVersion: share.KeyVersion,+ })+ }+ return resp, nil+}diff --git a/server/wall/controller/helpers.go b/server/wall/controller/helpers.goindex 122d089212..8eb9089c8a 100644--- a/server/wall/controller/helpers.go+++ b/server/wall/controller/helpers.go@@ -52,6 +52,15 @@ func toPostObjectPayload(asset wallrepo.WallPostAssetRecord) models.PostObjectPaif asset.BlurHashCipher.Valid {resp.BlurHashCipher = asset.BlurHashCipher.String}+ if asset.Width.Valid {+ resp.Width = int(asset.Width.Int64)+ }+ if asset.Height.Valid {+ resp.Height = int(asset.Height.Int64)+ }+ if asset.MediaType.Valid {+ resp.MediaType = asset.MediaType.String+ }return resp}@@ -79,14 +88,16 @@ func toPostResponse(post *wallrepo.WallPostRecord, assets []wallrepo.WallPostAssreturn resp}-func toCommentResponse(comment wallrepo.WallCommentRecord, replies []models.CommentResponse) models.CommentResponse {+func toCommentResponse(comment wallrepo.WallCommentRecord) models.CommentResponse {resp := models.CommentResponse{CommentID: comment.CommentID,+ AuthorID: comment.AuthorID,Author: comment.Author,CommentCipher: comment.CommentCipher,CreatedAt: formatMicros(comment.CreatedAt),+ Likes: comment.Likes,+ ViewerLiked: comment.ViewerLiked,ViewerCanDelete: comment.ViewerCanDelete,- Replies: replies,}if comment.ParentCommentID.Valid {parentID := comment.ParentCommentID.Int64diff --git a/server/wall/controller/links.go b/server/wall/controller/links.goindex 5c762f404c..556af50974 100644--- a/server/wall/controller/links.go+++ b/server/wall/controller/links.go@@ -121,11 +121,16 @@ func (c *LinksController) Login(ctx *gin.Context, req models.WallLinkLoginRequesif err := c.LinksRepo.CreateSession(ctx.Request.Context(), sessionHash[:], link.WallID, link.AuthKeyHash, link.KeyVersion, timeutil.MicrosecondsAfterMinutes(wallLinkSessionDurationMinutes)); err != nil {return nil, err}+ publicKey, err := c.WallsRepo.GetOwnerPublicKey(ctx.Request.Context(), link.OwnerID)+ if err != nil {+ return nil, err+ }return &models.WallLinkLoginResponse{SessionToken: sessionToken,WallID: link.WallID,WallSlug: link.WallSlug,Owner: link.OwnerSlug,+ PublicKey: publicKey,KeyVersion: link.KeyVersion,EncryptedWallKey: link.EncryptedWallKey,}, nildiff --git a/server/wall/controller/module.go b/server/wall/controller/module.goindex 543d6ac47f..a52047f72a 100644--- a/server/wall/controller/module.go+++ b/server/wall/controller/module.go@@ -6,13 +6,14 @@ import ()type Module struct {- Walls *WallsController- Posts *PostsController- Follow *FollowController- Links *LinksController- Assets *AssetsController- Cleanup *CleanupController- UserAuth *baserepo.UserAuthRepository+ Walls *WallsController+ Posts *PostsController+ Friends *FriendsController+ Notifications *NotificationsController+ Links *LinksController+ Assets *AssetsController+ Cleanup *CleanupController+ UserAuth *baserepo.UserAuthRepository}func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository) *Module {@@ -20,15 +21,16 @@ func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository) *MUserAuthRepo: userAuthRepo,LinksRepo: repos.Links,WallsRepo: repos.Walls,- FollowRepo: repos.Follow,+ FriendsRepo: repos.Friends,}return &Module{- Walls: &WallsController{WallsRepo: repos.Walls, AssetsRepo: repos.Assets, auth: authDeps},- Posts: &PostsController{PostsRepo: repos.Posts, WallsRepo: repos.Walls, FollowRepo: repos.Follow, AssetsRepo: repos.Assets, auth: authDeps},- Follow: &FollowController{FollowRepo: repos.Follow, WallsRepo: repos.Walls, auth: authDeps},- Links: &LinksController{LinksRepo: repos.Links, WallsRepo: repos.Walls, auth: authDeps},- Assets: &AssetsController{AssetsRepo: repos.Assets, WallsRepo: repos.Walls, FollowRepo: repos.Follow, LinksRepo: repos.Links, auth: authDeps},- Cleanup: &CleanupController{AssetsRepo: repos.Assets},- UserAuth: userAuthRepo,+ Walls: &WallsController{WallsRepo: repos.Walls, AssetsRepo: repos.Assets, auth: authDeps},+ Posts: &PostsController{PostsRepo: repos.Posts, WallsRepo: repos.Walls, AssetsRepo: repos.Assets, auth: authDeps},+ Friends: &FriendsController{FriendsRepo: repos.Friends, WallsRepo: repos.Walls, auth: authDeps},+ Notifications: &NotificationsController{NotificationsRepo: repos.Notifications, 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},+ Cleanup: &CleanupController{AssetsRepo: repos.Assets},+ UserAuth: userAuthRepo,}}diff --git a/server/wall/controller/notifications.go b/server/wall/controller/notifications.gonew file mode 100644index 0000000000..083d223c3c--- /dev/null+++ b/server/wall/controller/notifications.go@@ -0,0 +1,102 @@+package controller++import (+ "github.com/ente-io/museum/wall/models"+ "github.com/ente-io/museum/wall/repo"+ "github.com/gin-gonic/gin"+)++type NotificationsController struct {+ NotificationsRepo *repo.NotificationsRepository+ auth authDeps+}++func (c *NotificationsController) List(ctx *gin.Context, req models.ListNotificationsRequest) (*models.NotificationPage, error) {+ userID, err := c.auth.requireUser(ctx)+ if err != nil {+ return nil, err+ }+ notifications, nextCursor, err := c.NotificationsRepo.List(ctx.Request.Context(), userID, req.Cursor, req.Limit)+ if err != nil {+ return nil, err+ }+ items := make([]models.NotificationResponse, 0, len(notifications))+ for _, notification := range notifications {+ items = append(items, toNotificationResponse(notification))+ }+ return &models.NotificationPage{Items: items, NextCursor: nextCursor}, nil+}++func toNotificationResponse(notification repo.WallNotificationRecord) models.NotificationResponse {+ resp := models.NotificationResponse{+ ID: notification.ID,+ Type: notification.Type,+ CreatedAt: formatMicros(notification.CreatedAt),+ Actor: models.NotificationActorResponse{+ UserID: notification.ActorID,+ Username: notification.ActorUsername,+ WallID: notification.ActorWallID,+ WallSlug: notification.ActorWallSlug,+ },+ }+ if notification.PostID.Valid {+ post := &models.NotificationPostResponse{+ PostID: notification.PostID.Int64,+ WallID: notification.PostWallID.String,+ WallSlug: notification.PostWallSlug.String,+ OwnerUserID: notification.PostOwnerID.Int64,+ Author: notification.PostAuthor.String,+ }+ if notification.PostObjectKey.Valid {+ object := models.PostObjectPayload{+ ObjectKey: notification.PostObjectKey.String,+ }+ if notification.PostObjectSize.Valid {+ object.Size = notification.PostObjectSize.Int64+ }+ if notification.PostObjectPosition.Valid {+ object.Position = int(notification.PostObjectPosition.Int64)+ }+ if notification.PostObjectVariant.Valid {+ object.Variant = notification.PostObjectVariant.String+ }+ if notification.PostObjectBlurHashCipher.Valid {+ object.BlurHashCipher = notification.PostObjectBlurHashCipher.String+ }+ if notification.PostObjectWidth.Valid {+ object.Width = int(notification.PostObjectWidth.Int64)+ }+ if notification.PostObjectHeight.Valid {+ object.Height = int(notification.PostObjectHeight.Int64)+ }+ if notification.PostObjectMediaType.Valid {+ object.MediaType = notification.PostObjectMediaType.String+ }+ post.Objects = []models.PostObjectPayload{object}+ }+ resp.Post = post+ }+ if notification.CommentID.Valid {+ comment := &models.NotificationCommentResponse{+ CommentID: notification.CommentID.Int64,+ }+ if notification.CommentAuthorID.Valid {+ comment.AuthorID = notification.CommentAuthorID.Int64+ }+ if notification.CommentAuthor.Valid {+ comment.Author = notification.CommentAuthor.String+ }+ if notification.CommentCipher.Valid {+ comment.CommentCipher = notification.CommentCipher.String+ }+ if notification.CommentCreatedAt.Valid {+ comment.CreatedAt = formatMicros(notification.CommentCreatedAt.Int64)+ }+ if notification.ParentCommentID.Valid {+ parentID := notification.ParentCommentID.Int64+ comment.ParentCommentID = &parentID+ }+ resp.Comment = comment+ }+ return resp+}diff --git a/server/wall/controller/posts.go b/server/wall/controller/posts.goindex 252c579887..027f9ec87f 100644--- a/server/wall/controller/posts.go+++ b/server/wall/controller/posts.go@@ -16,7 +16,6 @@ import (type PostsController struct {PostsRepo *repo.PostsRepositoryWallsRepo *repo.WallsRepository- FollowRepo *repo.FollowRepositoryAssetsRepo *repo.AssetsRepositoryauth authDeps}@@ -52,6 +51,9 @@ func (c *PostsController) Create(ctx *gin.Context, req models.CreatePostRequest)Position: object.Position,Variant: sql.NullString{String: object.Variant, Valid: strings.TrimSpace(object.Variant) != ""},BlurHashCipher: sql.NullString{String: object.BlurHashCipher, Valid: strings.TrimSpace(object.BlurHashCipher) != ""},+ Width: sql.NullInt64{Int64: int64(object.Width), Valid: object.Width > 0},+ Height: sql.NullInt64{Int64: int64(object.Height), Valid: object.Height > 0},+ MediaType: sql.NullString{String: object.MediaType, Valid: strings.TrimSpace(object.MediaType) != ""},})}postID, err := c.PostsRepo.CreatePost(ctx.Request.Context(), userID, wall.WallID, req.EncryptedPostKey, req.CaptionCipher, req.KeyVersion, assets)@@ -247,26 +249,13 @@ func (c *PostsController) ListComments(ctx *gin.Context, postID string) (*modelsreturn nil, err}limit, _ := strconv.Atoi(strings.TrimSpace(ctx.Query("limit")))- comments, nextCursor, err := c.PostsRepo.ListTopLevelComments(ctx.Request.Context(), id, viewerID, ctx.Query("cursor"), limit)- if err != nil {- return nil, err- }- parentIDs := make([]int64, 0, len(comments))- for _, comment := range comments {- parentIDs = append(parentIDs, comment.CommentID)- }- repliesByParent, err := c.PostsRepo.ListReplies(ctx.Request.Context(), id, viewerID, parentIDs)+ comments, nextCursor, err := c.PostsRepo.ListComments(ctx.Request.Context(), id, viewerID, ctx.Query("cursor"), limit)if err != nil {return nil, err}resp := make([]models.CommentResponse, 0, len(comments))for _, comment := range comments {- replies := repliesByParent[comment.CommentID]- replyResp := make([]models.CommentResponse, 0, len(replies))- for _, reply := range replies {- replyResp = append(replyResp, toCommentResponse(reply, nil))- }- resp = append(resp, toCommentResponse(comment, replyResp))+ resp = append(resp, toCommentResponse(comment))}return &models.ListCommentsResponse{Comments: resp, NextCursor: nextCursor}, nil}@@ -305,7 +294,7 @@ func (c *PostsController) CreateComment(ctx *gin.Context, postID string, req mod}return nil, err}- if parent.PostID != id || parent.ParentCommentID.Valid {+ if parent.PostID != id {return nil, ente.NewBadRequestWithMessage("invalid parentCommentId")}}@@ -313,10 +302,47 @@ func (c *PostsController) CreateComment(ctx *gin.Context, postID string, req modif err != nil {return nil, err}- resp := toCommentResponse(*comment, nil)+ resp := toCommentResponse(*comment)return &resp, nil}+func (c *PostsController) ToggleCommentLike(ctx *gin.Context, postID, commentID string, req models.LikeCommentRequest) (*models.LikeCommentResponse, error) {+ userID, err := c.auth.requireUser(ctx)+ if err != nil {+ return nil, err+ }+ postIDInt, err := strconv.ParseInt(strings.TrimSpace(postID), 10, 64)+ if err != nil || postIDInt <= 0 {+ return nil, ente.NewBadRequestWithMessage("invalid postID")+ }+ commentIDInt, err := strconv.ParseInt(strings.TrimSpace(commentID), 10, 64)+ if err != nil || commentIDInt <= 0 {+ return nil, ente.NewBadRequestWithMessage("invalid commentID")+ }+ post, err := c.PostsRepo.GetPost(ctx.Request.Context(), postIDInt, userID)+ if err != nil {+ return nil, err+ }+ wall, err := c.WallsRepo.GetWallByID(ctx.Request.Context(), post.WallID)+ if err != nil {+ return nil, err+ }+ if err := c.auth.canViewWall(ctx.Request.Context(), &viewerAuth{UserID: userID}, wall); err != nil {+ return nil, err+ }+ comment, err := c.PostsRepo.GetComment(ctx.Request.Context(), commentIDInt, userID)+ if err != nil {+ return nil, err+ }+ if comment.PostID != postIDInt {+ return nil, ente.NewBadRequestWithMessage("invalid commentID")+ }+ if err := c.PostsRepo.SetCommentLike(ctx.Request.Context(), postIDInt, commentIDInt, userID, req.Like); err != nil {+ return nil, err+ }+ return &models.LikeCommentResponse{Liked: req.Like}, nil+}+func (c *PostsController) DeleteComment(ctx *gin.Context, postID, commentID string) error {userID, err := c.auth.requireUser(ctx)if err != nil {diff --git a/server/wall/controller/posts_test.go b/server/wall/controller/posts_test.goindex 46d141efe3..b35195f09d 100644--- a/server/wall/controller/posts_test.go+++ b/server/wall/controller/posts_test.go@@ -90,7 +90,7 @@ func TestCreateCommentRejectsParentFromAnotherPost(t *testing.T) {require.Equal(t, 0, countWallComments(t, repos.Posts.DB, secondPostID))}-func TestCreateCommentRejectsReplyAsParent(t *testing.T) {+func TestCreateCommentAcceptsReplyAsParent(t *testing.T) {posts, repos, ctx := setupPostsControllerTest(t)aliceID := insertWallControllerUser(t, repos, "[email protected]", "alice-public")wall, err := repos.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")@@ -107,9 +107,10 @@ func TestCreateCommentRejectsReplyAsParent(t *testing.T) {ParentCommentID: &reply.CommentID,})- require.Nil(t, resp)- require.Error(t, err)- require.Equal(t, 2, countWallComments(t, repos.Posts.DB, postID))+ require.NoError(t, err)+ require.NotNil(t, resp)+ require.Equal(t, reply.CommentID, *resp.ParentCommentID)+ require.Equal(t, 3, countWallComments(t, repos.Posts.DB, postID))}func TestCreateCommentAcceptsTopLevelParentOnSamePost(t *testing.T) {diff --git a/server/wall/controller/walls.go b/server/wall/controller/walls.goindex 146dca16b9..16de1e8876 100644--- a/server/wall/controller/walls.go+++ b/server/wall/controller/walls.go@@ -143,7 +143,11 @@ func (c *WallsController) UpdateSlug(ctx *gin.Context, wallID string, req modelsif err != nil {return nil, err}- return &models.WallLookupResponse{WallID: wall.WallID, WallSlug: wall.WallSlug, Owner: wall.WallSlug}, nil+ publicKey, err := c.WallsRepo.GetOwnerPublicKey(ctx.Request.Context(), wall.OwnerID)+ if err != nil {+ return nil, err+ }+ return &models.WallLookupResponse{WallID: wall.WallID, WallSlug: wall.WallSlug, Owner: wall.WallSlug, PublicKey: publicKey}, nil}func (c *WallsController) LookupBySlug(ctx *gin.Context, wallSlug string) (*models.WallLookupResponse, error) {@@ -151,10 +155,15 @@ func (c *WallsController) LookupBySlug(ctx *gin.Context, wallSlug string) (*modeif err != nil {return nil, err}+ publicKey, err := c.WallsRepo.GetOwnerPublicKey(ctx.Request.Context(), wall.OwnerID)+ if err != nil {+ return nil, err+ }return &models.WallLookupResponse{- WallID: wall.WallID,- WallSlug: wall.WallSlug,- Owner: wall.WallSlug,+ WallID: wall.WallID,+ WallSlug: wall.WallSlug,+ Owner: wall.WallSlug,+ PublicKey: publicKey,}, nil}diff --git a/server/wall/models/models.go b/server/wall/models/models.goindex b1b95a5818..1d616c2a4c 100644--- a/server/wall/models/models.go+++ b/server/wall/models/models.go@@ -26,13 +26,12 @@ type ListFeedRequest struct {Limit int `form:"limit"`}-type CommunityRequest struct {- Query string `form:"q"`+type ListNotificationsRequest struct {Cursor string `form:"cursor"`Limit int `form:"limit"`}-type ListWallFollowersRequest struct {+type ListWallFriendsRequest struct {WallID string `form:"wallId"`}@@ -100,60 +99,36 @@ type WallLinkLoginResponse struct {WallID string `json:"wallId"`WallSlug string `json:"wallSlug"`Owner string `json:"owner"`+ PublicKey string `json:"publicKey,omitempty"`KeyVersion int `json:"keyVersion"`EncryptedWallKey string `json:"encryptedWallKey"`}-type FollowRequestPayload struct {- TargetUsername *string `json:"targetUsername,omitempty"`- TargetWallID *string `json:"targetWallId,omitempty"`-}--type ApproveFollowPayload struct {- RequestID int64 `json:"requestId"`- WallID string `json:"wallId"`- EncryptedWallKey string `json:"encryptedWallKey"`- KeyVersion int `json:"keyVersion"`-}--type RejectFollowPayload struct {- RequestID int64 `json:"requestId"`-}--type CancelFollowRequestPayload struct {- RequestID int64 `json:"requestId"`+type AddFriendPayload struct {+ TargetWallID string `json:"targetWallId"`+ LinkSessionToken string `json:"linkSessionToken"`+ RequesterWallID string `json:"requesterWallId"`+ TargetEncryptedWallKey string `json:"targetEncryptedWallKey"`+ TargetKeyVersion int `json:"targetKeyVersion"`+ RequesterEncryptedWallKey string `json:"requesterEncryptedWallKey"`+ RequesterKeyVersion int `json:"requesterKeyVersion"`}-type FollowRequestResponse struct {- RequestID int64 `json:"requestId"`- Follower string `json:"follower"`- WallID string `json:"wallId"`- WallSlug string `json:"wallSlug"`- FollowerPublicKey string `json:"followerPublicKey"`- Status string `json:"status"`- CreatedAt string `json:"createdAt"`-}--type OutgoingFollowRequestResponse struct {- RequestID int64 `json:"requestId"`- Followee string `json:"followee"`- WallID string `json:"wallId"`- WallSlug string `json:"wallSlug"`- Status string `json:"status"`- CreatedAt string `json:"createdAt"`+type FriendTargetPayload struct {+ TargetUsername *string `json:"targetUsername,omitempty"`+ TargetWallID *string `json:"targetWallId,omitempty"`}-type FollowShareResponse struct {- Followee string `json:"followee"`+type FriendShareResponse struct {+ Friend string `json:"friend"`WallID string `json:"wallId"`WallSlug string `json:"wallSlug"`EncryptedWallKey string `json:"encryptedWallKey"`KeyVersion int `json:"keyVersion"`}-type FollowRequestCreatedResponse struct {- RequestID int64 `json:"requestId"`- Status string `json:"status"`+type FriendStatusResponse struct {+ Status string `json:"status"`}type UpdateWallProfileRequest struct {@@ -188,9 +163,10 @@ type UpdateWallSlugRequest struct {}type WallLookupResponse struct {- WallID string `json:"wallId"`- WallSlug string `json:"wallSlug"`- Owner string `json:"owner"`+ WallID string `json:"wallId"`+ WallSlug string `json:"wallSlug"`+ Owner string `json:"owner"`+ PublicKey string `json:"publicKey,omitempty"`}type RotateWallKeyRequest struct {@@ -206,22 +182,27 @@ type WallKeyVersionResponse struct {CreatedAt string `json:"createdAt"`}-type WallFollowerResponse struct {- FollowerID int64 `json:"followerId"`- Username string `json:"username"`- PublicKey string `json:"publicKey"`- KeyVersion int `json:"keyVersion"`- CreatedAt string `json:"createdAt"`+type WallFriendResponse struct {+ FriendID int64 `json:"friendId"`+ WallID string `json:"wallId"`+ Username string `json:"username"`+ PublicKey string `json:"publicKey"`+ KeyVersion int `json:"keyVersion"`+ EncryptedProfile string `json:"encryptedProfile,omitempty"`+ Avatar *ProfileAvatarResponse `json:"avatar,omitempty"`+ Friends int64 `json:"friends"`+ Posts int64 `json:"posts"`+ CreatedAt string `json:"createdAt"`}-type RefreshFollowSharesRequest struct {+type RefreshFriendSharesRequest struct {WallID string `json:"wallId"`KeyVersion int `json:"keyVersion"`Shares []ShareUpdatePayload `json:"shares"`}type ShareUpdatePayload struct {- FollowerID int64 `json:"followerId"`+ FriendID int64 `json:"friendId"`EncryptedWallKey string `json:"encryptedWallKey"`}@@ -245,6 +226,14 @@ type LikePostResponse struct {Liked bool `json:"liked"`}+type LikeCommentRequest struct {+ Like bool `json:"like"`+}++type LikeCommentResponse struct {+ Liked bool `json:"liked"`+}+type UpdatePostCaptionRequest struct {CaptionCipher *string `json:"captionCipher,omitempty"`}@@ -255,6 +244,9 @@ type PostObjectPayload struct {Position int `json:"position,omitempty"`Variant string `json:"variant,omitempty"`BlurHashCipher string `json:"blurHashCipher,omitempty"`+ Width int `json:"width,omitempty"`+ Height int `json:"height,omitempty"`+ MediaType string `json:"mediaType,omitempty"`}type PostResponse struct {@@ -284,13 +276,15 @@ type FeedPage struct {}type CommentResponse struct {- CommentID int64 `json:"commentId"`- Author string `json:"author"`- CommentCipher string `json:"commentCipher"`- CreatedAt string `json:"createdAt"`- ViewerCanDelete bool `json:"viewerCanDelete"`- ParentCommentID *int64 `json:"parentCommentId,omitempty"`- Replies []CommentResponse `json:"replies,omitempty"`+ CommentID int64 `json:"commentId"`+ AuthorID int64 `json:"authorId"`+ Author string `json:"author"`+ CommentCipher string `json:"commentCipher"`+ CreatedAt string `json:"createdAt"`+ Likes int64 `json:"likes"`+ ViewerLiked bool `json:"viewerLiked"`+ ViewerCanDelete bool `json:"viewerCanDelete"`+ ParentCommentID *int64 `json:"parentCommentId,omitempty"`}type ListCommentsResponse struct {@@ -303,20 +297,43 @@ type CreateCommentRequest struct {ParentCommentID *int64 `json:"parentCommentId,omitempty"`}-type CommunityUserResponse struct {- Username string `json:"username"`- WallID string `json:"wallId"`- WallSlug string `json:"wallSlug"`- Followers int64 `json:"followers"`- Following int64 `json:"following"`- Posts int64 `json:"posts"`- Relationship string `json:"relationship,omitempty"`- Bio string `json:"bio,omitempty"`+type NotificationActorResponse struct {+ UserID int64 `json:"userId"`+ Username string `json:"username"`+ WallID string `json:"wallId"`+ WallSlug string `json:"wallSlug"`+}++type NotificationPostResponse struct {+ PostID int64 `json:"postId"`+ WallID string `json:"wallId"`+ WallSlug string `json:"wallSlug"`+ OwnerUserID int64 `json:"ownerUserId"`+ Author string `json:"author"`+ Objects []PostObjectPayload `json:"objects,omitempty"`+}++type NotificationCommentResponse struct {+ CommentID int64 `json:"commentId"`+ AuthorID int64 `json:"authorId,omitempty"`+ Author string `json:"author,omitempty"`+ CommentCipher string `json:"commentCipher,omitempty"`+ CreatedAt string `json:"createdAt,omitempty"`+ ParentCommentID *int64 `json:"parentCommentId,omitempty"`+}++type NotificationResponse struct {+ ID string `json:"id"`+ Type string `json:"type"`+ CreatedAt string `json:"createdAt"`+ Actor NotificationActorResponse `json:"actor"`+ Post *NotificationPostResponse `json:"post,omitempty"`+ Comment *NotificationCommentResponse `json:"comment,omitempty"`}-type CommunityResponse struct {- Users []CommunityUserResponse `json:"users"`- NextCursor string `json:"nextCursor,omitempty"`+type NotificationPage struct {+ Items []NotificationResponse `json:"items"`+ NextCursor string `json:"nextCursor,omitempty"`}type UpdatedCountResponse struct {diff --git a/server/wall/repo/follow.go b/server/wall/repo/follow.godeleted file mode 100644index edf4d72f43..0000000000--- a/server/wall/repo/follow.go+++ /dev/null@@ -1,461 +0,0 @@-package repo--import (- "context"- "database/sql"- "errors"- "fmt"- "strconv"- "strings"-- "github.com/ente-io/stacktrace"-)--var ErrAlreadyFollowing = errors.New("wall follower already has access")--func (r *FollowRepository) CreateRequest(ctx context.Context, requesterID int64, targetWallID string) (*WallFollowRequestRecord, error) {- tx, err := r.DB.BeginTx(ctx, nil)- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- defer tx.Rollback()- var wallExists int- if err := tx.QueryRowContext(ctx, `SELECT 1 FROM walls WHERE wall_id = $1 FOR UPDATE`, targetWallID).Scan(&wallExists); err != nil {- return nil, stacktrace.Propagate(err, "")- }- var hasShare bool- if err := tx.QueryRowContext(ctx, `- SELECT EXISTS (- SELECT 1- FROM wall_follow_shares- WHERE follower_id = $1 AND wall_id = $2- )- `, requesterID, targetWallID).Scan(&hasShare); err != nil {- return nil, stacktrace.Propagate(err, "")- }- if hasShare {- return nil, ErrAlreadyFollowing- }- if _, err := tx.ExecContext(ctx, `- UPDATE wall_follow_requests- SET status = 'pending'- WHERE requester_id = $1 AND target_wall_id = $2 AND status IN ('cancelled', 'rejected', 'unfollowed')- `, requesterID, targetWallID); err != nil {- return nil, stacktrace.Propagate(err, "")- }- _, err = tx.ExecContext(ctx, `- INSERT INTO wall_follow_requests (requester_id, target_wall_id, status)- VALUES ($1, $2, 'pending')- ON CONFLICT DO NOTHING- `, requesterID, targetWallID)- if err != nil && !strings.Contains(strings.ToLower(err.Error()), "conflict") {- return nil, stacktrace.Propagate(err, "")- }- rec, err := scanFollowRequest(tx.QueryRowContext(ctx, `- SELECT r.request_id, r.requester_id, r.target_wall_id, r.status, r.created_at, r.updated_at,- requester_wall.wall_slug,- ka.public_key,- target_wall.wall_slug- FROM wall_follow_requests r- JOIN walls requester_wall ON requester_wall.owner_id = r.requester_id- JOIN key_attributes ka ON ka.user_id = r.requester_id- JOIN walls target_wall ON target_wall.wall_id = r.target_wall_id- WHERE r.requester_id = $1 AND r.target_wall_id = $2- ORDER BY r.request_id DESC- LIMIT 1- `, requesterID, targetWallID))- if err != nil {- return nil, err- }- if err := tx.Commit(); err != nil {- return nil, stacktrace.Propagate(err, "")- }- return rec, nil-}--func (r *FollowRepository) GetRequest(ctx context.Context, requestID int64) (*WallFollowRequestRecord, error) {- return scanFollowRequest(r.DB.QueryRowContext(ctx, `- SELECT r.request_id, r.requester_id, r.target_wall_id, r.status, r.created_at, r.updated_at,- requester_wall.wall_slug,- ka.public_key,- target_wall.wall_slug- FROM wall_follow_requests r- JOIN walls requester_wall ON requester_wall.owner_id = r.requester_id- JOIN key_attributes ka ON ka.user_id = r.requester_id- JOIN walls target_wall ON target_wall.wall_id = r.target_wall_id- WHERE r.request_id = $1- `, requestID))-}--func (r *FollowRepository) UpdateRequestStatus(ctx context.Context, requestID int64, status string) error {- _, err := r.DB.ExecContext(ctx, `UPDATE wall_follow_requests SET status = $1 WHERE request_id = $2`, status, requestID)- return stacktrace.Propagate(err, "")-}--func (r *FollowRepository) UpdatePendingRequestStatus(ctx context.Context, requestID int64, status string) error {- res, err := r.DB.ExecContext(ctx, `- UPDATE wall_follow_requests- SET status = $1- WHERE request_id = $2 AND status = 'pending'- `, status, requestID)- if err != nil {- return stacktrace.Propagate(err, "")- }- affected, err := res.RowsAffected()- if err != nil {- return stacktrace.Propagate(err, "")- }- if affected == 0 {- return sql.ErrNoRows- }- return nil-}--func (r *FollowRepository) ListIncomingRequests(ctx context.Context, ownerID int64) ([]WallFollowRequestRecord, error) {- rows, err := r.DB.QueryContext(ctx, `- SELECT r.request_id, r.requester_id, r.target_wall_id, r.status, r.created_at, r.updated_at,- requester_wall.wall_slug,- ka.public_key,- target_wall.wall_slug- FROM wall_follow_requests r- JOIN walls target_wall ON target_wall.wall_id = r.target_wall_id- JOIN walls requester_wall ON requester_wall.owner_id = r.requester_id- JOIN key_attributes ka ON ka.user_id = r.requester_id- WHERE target_wall.owner_id = $1 AND r.status = 'pending'- ORDER BY r.created_at ASC- `, ownerID)- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- defer rows.Close()- var out []WallFollowRequestRecord- for rows.Next() {- rec, err := scanFollowRequest(rows)- if err != nil {- return nil, err- }- out = append(out, *rec)- }- return out, stacktrace.Propagate(rows.Err(), "")-}--func (r *FollowRepository) ListOutgoingRequests(ctx context.Context, requesterID int64) ([]WallFollowRequestRecord, error) {- rows, err := r.DB.QueryContext(ctx, `- SELECT r.request_id, r.requester_id, r.target_wall_id, r.status, r.created_at, r.updated_at,- requester_wall.wall_slug,- ka.public_key,- target_wall.wall_slug- FROM wall_follow_requests r- JOIN walls target_wall ON target_wall.wall_id = r.target_wall_id- JOIN walls requester_wall ON requester_wall.owner_id = r.requester_id- JOIN key_attributes ka ON ka.user_id = r.requester_id- WHERE r.requester_id = $1 AND r.status = 'pending'- ORDER BY r.created_at ASC- `, requesterID)- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- defer rows.Close()- var out []WallFollowRequestRecord- for rows.Next() {- rec, err := scanFollowRequest(rows)- if err != nil {- return nil, err- }- out = append(out, *rec)- }- return out, stacktrace.Propagate(rows.Err(), "")-}--func (r *FollowRepository) UpsertShare(ctx context.Context, wallID string, followerID int64, encryptedWallKey string, keyVersion int) error {- _, err := r.DB.ExecContext(ctx, `- INSERT INTO wall_follow_shares (wall_id, follower_id, encrypted_wall_key, key_version)- VALUES ($1, $2, $3, $4)- ON CONFLICT (wall_id, follower_id) DO UPDATE- SET encrypted_wall_key = EXCLUDED.encrypted_wall_key,- key_version = EXCLUDED.key_version- `, wallID, followerID, encryptedWallKey, keyVersion)- return stacktrace.Propagate(err, "")-}--func (r *FollowRepository) UpdateShare(ctx context.Context, wallID string, followerID int64, encryptedWallKey string, keyVersion int) error {- return r.UpdateShares(ctx, wallID, []WallShareUpdateRecord{- {FollowerID: followerID, EncryptedWallKey: encryptedWallKey},- }, keyVersion)-}--func (r *FollowRepository) UpdateShares(ctx context.Context, wallID string, shares []WallShareUpdateRecord, keyVersion int) error {- if len(shares) == 0 {- return nil- }- tx, err := r.DB.BeginTx(ctx, nil)- if err != nil {- return stacktrace.Propagate(err, "")- }- defer tx.Rollback()-- var currentVersion int- if err := tx.QueryRowContext(ctx, `- SELECT current_version- FROM walls- WHERE wall_id = $1- FOR UPDATE- `, wallID).Scan(¤tVersion); err != nil {- return stacktrace.Propagate(err, "")- }- if currentVersion != keyVersion {- return sql.ErrNoRows- }-- for _, share := range shares {- res, err := tx.ExecContext(ctx, `- UPDATE wall_follow_shares- SET encrypted_wall_key = $3,- key_version = $4- WHERE wall_id = $1 AND follower_id = $2- `, wallID, share.FollowerID, share.EncryptedWallKey, keyVersion)- if err != nil {- return stacktrace.Propagate(err, "")- }- affected, err := res.RowsAffected()- if err != nil {- return stacktrace.Propagate(err, "")- }- if affected == 0 {- return sql.ErrNoRows- }- }- return stacktrace.Propagate(tx.Commit(), "")-}--func (r *FollowRepository) ApproveRequest(ctx context.Context, requestID int64, wallID string, encryptedWallKey string, keyVersion int) (*WallFollowRequestRecord, error) {- tx, err := r.DB.BeginTx(ctx, nil)- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- defer tx.Rollback()-- var currentVersion int- if err := tx.QueryRowContext(ctx, `- SELECT current_version- FROM walls- WHERE wall_id = $1- FOR UPDATE- `, wallID).Scan(¤tVersion); err != nil {- return nil, stacktrace.Propagate(err, "")- }- if currentVersion != keyVersion {- return nil, sql.ErrNoRows- }-- rec, err := scanFollowRequest(tx.QueryRowContext(ctx, `- SELECT r.request_id, r.requester_id, r.target_wall_id, r.status, r.created_at, r.updated_at,- requester_wall.wall_slug,- ka.public_key,- target_wall.wall_slug- FROM wall_follow_requests r- JOIN walls requester_wall ON requester_wall.owner_id = r.requester_id- JOIN key_attributes ka ON ka.user_id = r.requester_id- JOIN walls target_wall ON target_wall.wall_id = r.target_wall_id- WHERE r.request_id = $1 AND r.target_wall_id = $2 AND r.status = 'pending'- FOR UPDATE OF r- `, requestID, wallID))- if err != nil {- return nil, err- }-- if _, err := tx.ExecContext(ctx, `- INSERT INTO wall_follow_shares (wall_id, follower_id, encrypted_wall_key, key_version)- VALUES ($1, $2, $3, $4)- ON CONFLICT (wall_id, follower_id) DO UPDATE- SET encrypted_wall_key = EXCLUDED.encrypted_wall_key,- key_version = EXCLUDED.key_version- `, wallID, rec.RequesterID, encryptedWallKey, keyVersion); err != nil {- return nil, stacktrace.Propagate(err, "")- }-- res, err := tx.ExecContext(ctx, `- UPDATE wall_follow_requests- SET status = 'approved'- WHERE request_id = $1 AND status = 'pending'- `, requestID)- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- affected, err := res.RowsAffected()- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- if affected == 0 {- return nil, sql.ErrNoRows- }-- if err := tx.Commit(); err != nil {- return nil, stacktrace.Propagate(err, "")- }- rec.Status = "approved"- return rec, nil-}--func (r *FollowRepository) DeleteShareByWallAndFollower(ctx context.Context, wallID string, followerID int64) error {- _, err := r.DB.ExecContext(ctx, `DELETE FROM wall_follow_shares WHERE wall_id = $1 AND follower_id = $2`, wallID, followerID)- return stacktrace.Propagate(err, "")-}--func (r *FollowRepository) GetShareForFollowerAndWall(ctx context.Context, followerID int64, wallID string) (*WallShareRecord, error) {- return scanShareRecord(r.DB.QueryRowContext(ctx, `- SELECT s.wall_id, s.follower_id, w.owner_id, owner_wall.wall_slug, s.encrypted_wall_key, s.key_version, s.created_at, ka.public_key- FROM wall_follow_shares s- JOIN walls w ON w.wall_id = s.wall_id- JOIN walls owner_wall ON owner_wall.owner_id = w.owner_id- JOIN key_attributes ka ON ka.user_id = w.owner_id- WHERE s.follower_id = $1 AND s.wall_id = $2- `, followerID, wallID))-}--func (r *FollowRepository) ListSharesForFollower(ctx context.Context, followerID int64) ([]WallShareRecord, error) {- rows, err := r.DB.QueryContext(ctx, `- SELECT s.wall_id, s.follower_id, w.owner_id, owner_wall.wall_slug, s.encrypted_wall_key, s.key_version, s.created_at, ka.public_key- FROM wall_follow_shares s- JOIN walls w ON w.wall_id = s.wall_id- JOIN walls owner_wall ON owner_wall.owner_id = w.owner_id- JOIN key_attributes ka ON ka.user_id = w.owner_id- WHERE s.follower_id = $1- ORDER BY s.created_at ASC- `, followerID)- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- defer rows.Close()- var out []WallShareRecord- for rows.Next() {- rec, err := scanShareRecord(rows)- if err != nil {- return nil, err- }- out = append(out, *rec)- }- return out, stacktrace.Propagate(rows.Err(), "")-}--func (r *FollowRepository) ListFollowersForWall(ctx context.Context, wallID string) ([]WallFollowerRecord, error) {- rows, err := r.DB.QueryContext(ctx, `- SELECT s.follower_id, follower_wall.wall_slug, ka.public_key, s.key_version, s.created_at- FROM wall_follow_shares s- JOIN walls follower_wall ON follower_wall.owner_id = s.follower_id- JOIN key_attributes ka ON ka.user_id = s.follower_id- WHERE s.wall_id = $1- ORDER BY lower(follower_wall.wall_slug) ASC- `, wallID)- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- defer rows.Close()- var out []WallFollowerRecord- for rows.Next() {- var rec WallFollowerRecord- if err := rows.Scan(&rec.FollowerID, &rec.Username, &rec.PublicKey, &rec.KeyVersion, &rec.CreatedAt); err != nil {- return nil, stacktrace.Propagate(err, "")- }- out = append(out, rec)- }- return out, stacktrace.Propagate(rows.Err(), "")-}--func (r *FollowRepository) GetRelationship(ctx context.Context, viewerID, targetOwnerID int64, targetWallID string) (string, error) {- if viewerID == targetOwnerID {- return "self", nil- }- var count int64- if err := r.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM wall_follow_shares WHERE follower_id = $1 AND wall_id = $2`, viewerID, targetWallID).Scan(&count); err != nil {- return "", stacktrace.Propagate(err, "")- }- if count > 0 {- return "following", nil- }- if err := r.DB.QueryRowContext(ctx, `- SELECT COUNT(*) FROM wall_follow_requests WHERE requester_id = $1 AND target_wall_id = $2 AND status = 'pending'- `, viewerID, targetWallID).Scan(&count); err != nil {- return "", stacktrace.Propagate(err, "")- }- if count > 0 {- return "pending", nil- }- return "", nil-}--func (r *FollowRepository) ListCommunity(ctx context.Context, viewerID int64, query, cursor string, limit int) ([]CommunityRecord, string, error) {- limit = optionalInt(limit, 25)- if limit > 100 {- limit = 100- }- args := []any{viewerID}- clauses := []string{"TRUE"}- if trimmed := strings.ToLower(strings.TrimSpace(query)); trimmed != "" {- args = append(args, "%"+trimmed+"%")- clauses = append(clauses, fmtPlaceholder(len(args), "lower(w.wall_slug) LIKE %s"))- }- if trimmed := strings.ToLower(strings.TrimSpace(cursor)); trimmed != "" {- args = append(args, trimmed)- clauses = append(clauses, fmtPlaceholder(len(args), "lower(w.wall_slug) > %s"))- }- args = append(args, limit+1)- rows, err := r.DB.QueryContext(ctx, `- SELECT w.wall_slug, w.wall_id, w.wall_slug,- (SELECT COUNT(*) FROM wall_follow_shares fs WHERE fs.wall_id = w.wall_id) AS followers,- (SELECT COUNT(*) FROM wall_follow_shares fs WHERE fs.follower_id = w.owner_id) AS following,- (SELECT COUNT(*) FROM wall_posts p WHERE p.wall_id = w.wall_id AND p.is_deleted = FALSE) AS posts,- CASE- WHEN w.owner_id = $1 THEN 'self'- WHEN EXISTS (SELECT 1 FROM wall_follow_shares fs WHERE fs.follower_id = $1 AND fs.wall_id = w.wall_id) THEN 'following'- WHEN EXISTS (SELECT 1 FROM wall_follow_requests fr WHERE fr.requester_id = $1 AND fr.target_wall_id = w.wall_id AND fr.status = 'pending') THEN 'pending'- ELSE ''- END AS relationship,- '' AS bio- FROM walls w- WHERE `+strings.Join(clauses, " AND ")+`- ORDER BY lower(w.wall_slug) ASC- LIMIT $`+strconv.Itoa(len(args))+`- `, args...)- if err != nil {- return nil, "", stacktrace.Propagate(err, "")- }- defer rows.Close()- var out []CommunityRecord- for rows.Next() {- var rec CommunityRecord- if err := rows.Scan(&rec.Username, &rec.WallID, &rec.WallSlug, &rec.Followers, &rec.Following, &rec.Posts, &rec.Relationship, &rec.Bio); err != nil {- return nil, "", stacktrace.Propagate(err, "")- }- out = append(out, rec)- }- if err := rows.Err(); err != nil {- return nil, "", stacktrace.Propagate(err, "")- }- next := ""- if len(out) > limit {- next = out[limit-1].Username- out = out[:limit]- }- return out, next, nil-}--func scanFollowRequest(scanner interface{ Scan(dest ...any) error }) (*WallFollowRequestRecord, error) {- var rec WallFollowRequestRecord- if err := scanner.Scan(&rec.RequestID, &rec.RequesterID, &rec.TargetWallID, &rec.Status, &rec.CreatedAt, &rec.UpdatedAt, &rec.RequesterSlug, &rec.RequesterKey, &rec.TargetSlug); err != nil {- return nil, stacktrace.Propagate(err, "")- }- return &rec, nil-}--func scanShareRecord(scanner interface{ Scan(dest ...any) error }) (*WallShareRecord, error) {- var rec WallShareRecord- if err := scanner.Scan(&rec.WallID, &rec.FollowerID, &rec.FolloweeID, &rec.FolloweeSlug, &rec.EncryptedWallKey, &rec.KeyVersion, &rec.CreatedAt, &rec.PublicKey); err != nil {- return nil, stacktrace.Propagate(err, "")- }- return &rec, nil-}--func fmtPlaceholder(index int, format string) string {- return fmt.Sprintf(format, "$"+strconv.Itoa(index))-}diff --git a/server/wall/repo/friends.go b/server/wall/repo/friends.gonew file mode 100644index 0000000000..5430b73348--- /dev/null+++ b/server/wall/repo/friends.go@@ -0,0 +1,295 @@+package repo++import (+ "context"+ "database/sql"+ "errors"++ "github.com/ente-io/stacktrace"+)++var ErrAlreadyFriends = errors.New("wall users are already friends")++func (r *FriendsRepository) AddFriend(ctx context.Context, requesterID int64, requesterWallID string, targetWallID string, targetEncryptedWallKey string, targetKeyVersion int, requesterEncryptedWallKey string, requesterKeyVersion int) error {+ tx, err := r.DB.BeginTx(ctx, nil)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ defer tx.Rollback()++ var requesterOwnerID int64+ var requesterCurrentVersion int+ if err := tx.QueryRowContext(ctx, `+ SELECT owner_id, current_version+ FROM walls+ WHERE wall_id = $1+ FOR UPDATE+ `, requesterWallID).Scan(&requesterOwnerID, &requesterCurrentVersion); err != nil {+ return stacktrace.Propagate(err, "")+ }+ if requesterOwnerID != requesterID || requesterCurrentVersion != requesterKeyVersion {+ return sql.ErrNoRows+ }++ var targetOwnerID int64+ var targetCurrentVersion int+ if err := tx.QueryRowContext(ctx, `+ SELECT owner_id, current_version+ FROM walls+ WHERE wall_id = $1+ FOR UPDATE+ `, targetWallID).Scan(&targetOwnerID, &targetCurrentVersion); err != nil {+ return stacktrace.Propagate(err, "")+ }+ if targetOwnerID == requesterID {+ return ErrAlreadyFriends+ }+ if targetCurrentVersion != targetKeyVersion {+ return sql.ErrNoRows+ }++ var alreadyFriends bool+ if err := tx.QueryRowContext(ctx, `+ SELECT EXISTS (+ SELECT 1+ FROM wall_friend_shares target_share+ JOIN wall_friend_shares requester_share+ ON requester_share.wall_id = $1+ AND requester_share.friend_id = $2+ WHERE target_share.wall_id = $3+ AND target_share.friend_id = $4+ )+ `, requesterWallID, targetOwnerID, targetWallID, requesterID).Scan(&alreadyFriends); err != nil {+ return stacktrace.Propagate(err, "")+ }++ if _, err := tx.ExecContext(ctx, `+ INSERT INTO wall_friend_shares (wall_id, friend_id, encrypted_wall_key, key_version)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (wall_id, friend_id) DO UPDATE+ SET encrypted_wall_key = EXCLUDED.encrypted_wall_key,+ key_version = EXCLUDED.key_version+ `, targetWallID, requesterID, targetEncryptedWallKey, targetKeyVersion); err != nil {+ return stacktrace.Propagate(err, "")+ }++ if _, err := tx.ExecContext(ctx, `+ INSERT INTO wall_friend_shares (wall_id, friend_id, encrypted_wall_key, key_version)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (wall_id, friend_id) DO UPDATE+ SET encrypted_wall_key = EXCLUDED.encrypted_wall_key,+ key_version = EXCLUDED.key_version+ `, requesterWallID, targetOwnerID, requesterEncryptedWallKey, requesterKeyVersion); err != nil {+ return stacktrace.Propagate(err, "")+ }++ if !alreadyFriends {+ if _, err := tx.ExecContext(ctx, `+ INSERT INTO wall_friend_events (actor_id, actor_wall_id, target_id, target_wall_id)+ VALUES ($1, $2, $3, $4)+ `, requesterID, requesterWallID, targetOwnerID, targetWallID); err != nil {+ return stacktrace.Propagate(err, "")+ }+ }++ return stacktrace.Propagate(tx.Commit(), "")+}++func (r *FriendsRepository) UpsertShare(ctx context.Context, wallID string, friendID int64, encryptedWallKey string, keyVersion int) error {+ _, err := r.DB.ExecContext(ctx, `+ INSERT INTO wall_friend_shares (wall_id, friend_id, encrypted_wall_key, key_version)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (wall_id, friend_id) DO UPDATE+ SET encrypted_wall_key = EXCLUDED.encrypted_wall_key,+ key_version = EXCLUDED.key_version+ `, wallID, friendID, encryptedWallKey, keyVersion)+ return stacktrace.Propagate(err, "")+}++func (r *FriendsRepository) UpdateShare(ctx context.Context, wallID string, friendID int64, encryptedWallKey string, keyVersion int) error {+ return r.UpdateShares(ctx, wallID, []WallShareUpdateRecord{+ {FriendID: friendID, EncryptedWallKey: encryptedWallKey},+ }, keyVersion)+}++func (r *FriendsRepository) UpdateShares(ctx context.Context, wallID string, shares []WallShareUpdateRecord, keyVersion int) error {+ if len(shares) == 0 {+ return nil+ }+ tx, err := r.DB.BeginTx(ctx, nil)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ defer tx.Rollback()++ var currentVersion int+ if err := tx.QueryRowContext(ctx, `+ SELECT current_version+ FROM walls+ WHERE wall_id = $1+ FOR UPDATE+ `, wallID).Scan(¤tVersion); err != nil {+ return stacktrace.Propagate(err, "")+ }+ if currentVersion != keyVersion {+ return sql.ErrNoRows+ }++ for _, share := range shares {+ res, err := tx.ExecContext(ctx, `+ UPDATE wall_friend_shares+ SET encrypted_wall_key = $3,+ key_version = $4+ WHERE wall_id = $1 AND friend_id = $2+ `, wallID, share.FriendID, share.EncryptedWallKey, keyVersion)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ affected, err := res.RowsAffected()+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ if affected == 0 {+ return sql.ErrNoRows+ }+ }+ return stacktrace.Propagate(tx.Commit(), "")+}++func (r *FriendsRepository) DeleteFriendship(ctx context.Context, userID int64, targetWallID string) error {+ tx, err := r.DB.BeginTx(ctx, nil)+ if err != nil {+ return stacktrace.Propagate(err, "")+ }+ defer tx.Rollback()++ var targetOwnerID int64+ if err := tx.QueryRowContext(ctx, `SELECT owner_id FROM walls WHERE wall_id = $1`, targetWallID).Scan(&targetOwnerID); err != nil {+ return stacktrace.Propagate(err, "")+ }+ if targetOwnerID == userID {+ return nil+ }++ if _, err := tx.ExecContext(ctx, `+ DELETE FROM wall_friend_shares+ WHERE (wall_id = $1 AND friend_id = $2)+ OR (+ friend_id = $3+ AND wall_id IN (SELECT wall_id FROM walls WHERE owner_id = $2)+ )+ `, targetWallID, userID, targetOwnerID); err != nil {+ return stacktrace.Propagate(err, "")+ }++ return stacktrace.Propagate(tx.Commit(), "")+}++func (r *FriendsRepository) DeleteShareByWallAndFriend(ctx context.Context, wallID string, friendID int64) error {+ _, err := r.DB.ExecContext(ctx, `DELETE FROM wall_friend_shares WHERE wall_id = $1 AND friend_id = $2`, wallID, friendID)+ return stacktrace.Propagate(err, "")+}++func (r *FriendsRepository) GetShareForFriendAndWall(ctx context.Context, friendID int64, wallID string) (*WallShareRecord, error) {+ return scanShareRecord(r.DB.QueryRowContext(ctx, `+ SELECT s.wall_id, s.friend_id, w.owner_id, owner_wall.wall_slug, s.encrypted_wall_key, s.key_version, s.created_at, ka.public_key+ FROM wall_friend_shares s+ JOIN walls w ON w.wall_id = s.wall_id+ JOIN walls owner_wall ON owner_wall.owner_id = w.owner_id+ JOIN key_attributes ka ON ka.user_id = w.owner_id+ WHERE s.friend_id = $1 AND s.wall_id = $2+ `, friendID, wallID))+}++func (r *FriendsRepository) ListSharesForFriend(ctx context.Context, friendID int64) ([]WallShareRecord, error) {+ rows, err := r.DB.QueryContext(ctx, `+ SELECT s.wall_id, s.friend_id, w.owner_id, owner_wall.wall_slug, s.encrypted_wall_key, s.key_version, s.created_at, ka.public_key+ FROM wall_friend_shares s+ JOIN walls w ON w.wall_id = s.wall_id+ JOIN walls owner_wall ON owner_wall.owner_id = w.owner_id+ JOIN key_attributes ka ON ka.user_id = w.owner_id+ WHERE s.friend_id = $1+ ORDER BY s.created_at ASC+ `, friendID)+ if err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ defer rows.Close()+ var out []WallShareRecord+ for rows.Next() {+ rec, err := scanShareRecord(rows)+ if err != nil {+ return nil, err+ }+ out = append(out, *rec)+ }+ return out, stacktrace.Propagate(rows.Err(), "")+}++func (r *FriendsRepository) ListFriendsForWall(ctx context.Context, wallID string) ([]WallFriendRecord, error) {+ rows, err := r.DB.QueryContext(ctx, `+ SELECT s.friend_id,+ friend_wall.wall_id,+ friend_wall.wall_slug,+ ka.public_key,+ s.key_version,+ friend_wall.encrypted_profile,+ friend_wall.avatar_object_key,+ friend_wall.avatar_size,+ (SELECT COUNT(*) FROM wall_friend_shares fs WHERE fs.wall_id = friend_wall.wall_id) AS friends,+ (SELECT COUNT(*) FROM wall_posts p WHERE p.wall_id = friend_wall.wall_id AND p.is_deleted = FALSE) AS posts,+ s.created_at+ FROM wall_friend_shares s+ JOIN walls friend_wall ON friend_wall.owner_id = s.friend_id+ JOIN key_attributes ka ON ka.user_id = s.friend_id+ WHERE s.wall_id = $1+ ORDER BY lower(friend_wall.wall_slug) ASC+ `, wallID)+ if err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ defer rows.Close()+ var out []WallFriendRecord+ for rows.Next() {+ var rec WallFriendRecord+ if err := rows.Scan(+ &rec.FriendID,+ &rec.WallID,+ &rec.Username,+ &rec.PublicKey,+ &rec.KeyVersion,+ &rec.EncryptedProfile,+ &rec.AvatarObjectKey,+ &rec.AvatarSize,+ &rec.Friends,+ &rec.Posts,+ &rec.CreatedAt,+ ); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ out = append(out, rec)+ }+ return out, stacktrace.Propagate(rows.Err(), "")+}++func (r *FriendsRepository) GetRelationship(ctx context.Context, viewerID, targetOwnerID int64, targetWallID string) (string, error) {+ if viewerID == targetOwnerID {+ return "self", nil+ }+ var count int64+ if err := r.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM wall_friend_shares WHERE friend_id = $1 AND wall_id = $2`, viewerID, targetWallID).Scan(&count); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if count > 0 {+ return "friend", nil+ }+ return "", nil+}++func scanShareRecord(scanner interface{ Scan(dest ...any) error }) (*WallShareRecord, error) {+ var rec WallShareRecord+ if err := scanner.Scan(&rec.WallID, &rec.FriendID, &rec.OwnerID, &rec.WallSlug, &rec.EncryptedWallKey, &rec.KeyVersion, &rec.CreatedAt, &rec.PublicKey); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ return &rec, nil+}diff --git a/server/wall/repo/module.go b/server/wall/repo/module.goindex 077711f208..74c3ab26e8 100644--- a/server/wall/repo/module.go+++ b/server/wall/repo/module.go@@ -7,11 +7,12 @@ import ()type Module struct {- Walls *WallsRepository- Posts *PostsRepository- Follow *FollowRepository- Links *LinksRepository- Assets *AssetsRepository+ Walls *WallsRepository+ Posts *PostsRepository+ Friends *FriendsRepository+ Notifications *NotificationsRepository+ Links *LinksRepository+ Assets *AssetsRepository}type WallsRepository struct {@@ -22,7 +23,11 @@ type PostsRepository struct {DB *sql.DB}-type FollowRepository struct {+type FriendsRepository struct {+ DB *sql.DB+}++type NotificationsRepository struct {DB *sql.DB}@@ -82,6 +87,9 @@ type WallPostAssetRecord struct {Position intVariant sql.NullStringBlurHashCipher sql.NullString+ Width sql.NullInt64+ Height sql.NullInt64+ MediaType sql.NullStringCreatedAt int64}@@ -104,26 +112,16 @@ type WallCommentRecord struct {CommentCipher stringParentCommentID sql.NullInt64CreatedAt int64+ Likes int64+ ViewerLiked boolViewerCanDelete bool}-type WallFollowRequestRecord struct {- RequestID int64- RequesterID int64- TargetWallID string- Status string- CreatedAt int64- UpdatedAt int64- RequesterSlug string- RequesterKey string- TargetSlug string-}-type WallShareRecord struct {WallID string- FollowerID int64- FolloweeID int64- FolloweeSlug string+ FriendID int64+ OwnerID int64+ WallSlug stringEncryptedWallKey stringKeyVersion intCreatedAt int64@@ -131,16 +129,22 @@ type WallShareRecord struct {}type WallShareUpdateRecord struct {- FollowerID int64+ FriendID int64EncryptedWallKey string}-type WallFollowerRecord struct {- FollowerID int64- Username string- PublicKey string- KeyVersion int- CreatedAt int64+type WallFriendRecord struct {+ FriendID int64+ WallID string+ Username string+ PublicKey string+ KeyVersion int+ EncryptedProfile string+ AvatarObjectKey sql.NullString+ AvatarSize sql.NullInt64+ Friends int64+ Posts int64+ CreatedAt int64}type WallLinkRecord struct {@@ -169,23 +173,42 @@ type WallLinkSessionRecord struct {EncryptedWallKey string}-type CommunityRecord struct {- Username string- WallID string- WallSlug string- Followers int64- Following int64- Posts int64- Relationship string- Bio string+type WallNotificationRecord struct {+ ID string+ Type string+ CreatedAt int64+ ActorID int64+ ActorUsername string+ ActorWallID string+ ActorWallSlug string+ PostID sql.NullInt64+ PostWallID sql.NullString+ PostWallSlug sql.NullString+ PostOwnerID sql.NullInt64+ PostAuthor sql.NullString+ PostObjectKey sql.NullString+ PostObjectSize sql.NullInt64+ PostObjectPosition sql.NullInt64+ PostObjectVariant sql.NullString+ PostObjectBlurHashCipher sql.NullString+ PostObjectWidth sql.NullInt64+ PostObjectHeight sql.NullInt64+ PostObjectMediaType sql.NullString+ CommentID sql.NullInt64+ ParentCommentID sql.NullInt64+ CommentAuthorID sql.NullInt64+ CommentAuthor sql.NullString+ CommentCipher sql.NullString+ CommentCreatedAt sql.NullInt64}func NewModule(db *sql.DB, s3Config *s3config.S3Config) *Module {return &Module{- Walls: &WallsRepository{DB: db},- Posts: &PostsRepository{DB: db},- Follow: &FollowRepository{DB: db},- Links: &LinksRepository{DB: db},- Assets: &AssetsRepository{DB: db, S3Config: s3Config},+ Walls: &WallsRepository{DB: db},+ Posts: &PostsRepository{DB: db},+ Friends: &FriendsRepository{DB: db},+ Notifications: &NotificationsRepository{DB: db},+ Links: &LinksRepository{DB: db},+ Assets: &AssetsRepository{DB: db, S3Config: s3Config},}}diff --git a/server/wall/repo/module_test.go b/server/wall/repo/module_test.goindex 49893801c4..ad6e1cc709 100644--- a/server/wall/repo/module_test.go+++ b/server/wall/repo/module_test.go@@ -88,28 +88,28 @@ func TestWallModuleLifecycle(t *testing.T) {require.NoError(t, err)require.Len(t, versions, 2)- request, err := module.Follow.CreateRequest(ctx, bobID, aliceWall.WallID)+ err = module.Friends.AddFriend(ctx, bobID, bobWall.WallID, aliceWall.WallID, "alice-share-key", rotatedWall.CurrentVersion, "bob-share-key", bobWall.CurrentVersion)require.NoError(t, err)- require.Equal(t, "pending", request.Status)- incoming, err := module.Follow.ListIncomingRequests(ctx, aliceID)+ shares, err := module.Friends.ListSharesForFriend(ctx, bobID)require.NoError(t, err)- require.Len(t, incoming, 1)+ require.Len(t, shares, 1)+ require.Equal(t, "alice-share-key", shares[0].EncryptedWallKey)- err = module.Follow.UpsertShare(ctx, aliceWall.WallID, bobID, "share-key", rotatedWall.CurrentVersion)- require.NoError(t, err)- err = module.Follow.UpdateRequestStatus(ctx, request.RequestID, "approved")+ aliceShares, err := module.Friends.ListSharesForFriend(ctx, aliceID)require.NoError(t, err)+ require.Len(t, aliceShares, 1)+ require.Equal(t, "bob-share-key", aliceShares[0].EncryptedWallKey)- shares, err := module.Follow.ListSharesForFollower(ctx, bobID)+ friends, err := module.Friends.ListFriendsForWall(ctx, aliceWall.WallID)require.NoError(t, err)- require.Len(t, shares, 1)- require.Equal(t, "share-key", shares[0].EncryptedWallKey)+ require.Len(t, friends, 1)+ require.Equal(t, "bob", friends[0].Username)- followers, err := module.Follow.ListFollowersForWall(ctx, aliceWall.WallID)+ bobFriends, err := module.Friends.ListFriendsForWall(ctx, bobWall.WallID)require.NoError(t, err)- require.Len(t, followers, 1)- require.Equal(t, "bob", followers[0].Username)+ require.Len(t, bobFriends, 1)+ require.Equal(t, "alice", bobFriends[0].Username)for _, tempObject := range []WallTempObjectRecord{{@@ -164,14 +164,12 @@ func TestWallModuleLifecycle(t *testing.T) {_, err = module.Posts.CreateComment(ctx, postID, aliceID, "reply-1", &comment.CommentID)require.NoError(t, err)- comments, nextCommentsCursor, err := module.Posts.ListTopLevelComments(ctx, postID, bobID, "", 20)+ comments, nextCommentsCursor, err := module.Posts.ListComments(ctx, postID, bobID, "", 20)require.NoError(t, err)- require.Len(t, comments, 1)+ require.Len(t, comments, 2)require.Empty(t, nextCommentsCursor)-- replies, err := module.Posts.ListReplies(ctx, postID, bobID, []int64{comment.CommentID})- require.NoError(t, err)- require.Len(t, replies[comment.CommentID], 1)+ require.Equal(t, comment.CommentID, comments[1].CommentID)+ require.Equal(t, comment.CommentID, comments[0].ParentCommentID.Int64)assets, err := module.Posts.ListAssetsByPostIDs(ctx, []int64{postID})require.NoError(t, err)@@ -307,7 +305,7 @@ func TestUpdateProfileQueuesOldAvatarForCleanup(t *testing.T) {requireQueuedTempObject(t, module, "wall/alice/avatar-new", TempObjectPurposeAvatar, "b2-us-west")}-func TestApproveRequestCreatesShareAndMarksRequestApproved(t *testing.T) {+func TestAddFriendCreatesReciprocalSharesAndEvent(t *testing.T) {ctx := context.Background()module := newWallTestModule(t)@@ -315,27 +313,29 @@ func TestApproveRequestCreatesShareAndMarksRequestApproved(t *testing.T) {bobID := insertWallUser(t, module, "[email protected]", "bob-public")aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")require.NoError(t, err)- _, err = module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")- require.NoError(t, err)- request, err := module.Follow.CreateRequest(ctx, bobID, aliceWall.WallID)+ bobWall, err := module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")require.NoError(t, err)- approved, err := module.Follow.ApproveRequest(ctx, request.RequestID, aliceWall.WallID, "share-key", aliceWall.CurrentVersion)+ err = module.Friends.AddFriend(ctx, bobID, bobWall.WallID, aliceWall.WallID, "alice-share-key", aliceWall.CurrentVersion, "bob-share-key", bobWall.CurrentVersion)require.NoError(t, err)- require.Equal(t, request.RequestID, approved.RequestID)- require.Equal(t, "approved", approved.Status)- share, err := module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)+ share, err := module.Friends.GetShareForFriendAndWall(ctx, bobID, aliceWall.WallID)require.NoError(t, err)- require.Equal(t, "share-key", share.EncryptedWallKey)+ require.Equal(t, "alice-share-key", share.EncryptedWallKey)require.Equal(t, aliceWall.CurrentVersion, share.KeyVersion)- stored, err := module.Follow.GetRequest(ctx, request.RequestID)+ reciprocalShare, err := module.Friends.GetShareForFriendAndWall(ctx, aliceID, bobWall.WallID)+ require.NoError(t, err)+ require.Equal(t, "bob-share-key", reciprocalShare.EncryptedWallKey)+ require.Equal(t, bobWall.CurrentVersion, reciprocalShare.KeyVersion)++ var eventCount int+ err = module.Friends.DB.QueryRow(`SELECT COUNT(*) FROM wall_friend_events WHERE actor_id = $1 AND target_id = $2`, bobID, aliceID).Scan(&eventCount)require.NoError(t, err)- require.Equal(t, "approved", stored.Status)+ require.Equal(t, 1, eventCount)}-func TestCreateRequestRejectsAlreadyFollowing(t *testing.T) {+func TestAddFriendIsIdempotentForExistingFriends(t *testing.T) {ctx := context.Background()module := newWallTestModule(t)@@ -343,109 +343,21 @@ func TestCreateRequestRejectsAlreadyFollowing(t *testing.T) {bobID := insertWallUser(t, module, "[email protected]", "bob-public")aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")require.NoError(t, err)- _, err = module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")- require.NoError(t, err)- request, err := module.Follow.CreateRequest(ctx, bobID, aliceWall.WallID)+ bobWall, err := module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")require.NoError(t, err)- _, err = module.Follow.ApproveRequest(ctx, request.RequestID, aliceWall.WallID, "share-key", aliceWall.CurrentVersion)+ err = module.Friends.AddFriend(ctx, bobID, bobWall.WallID, aliceWall.WallID, "alice-share-key", aliceWall.CurrentVersion, "bob-share-key", bobWall.CurrentVersion)require.NoError(t, err)- duplicate, err := module.Follow.CreateRequest(ctx, bobID, aliceWall.WallID)+ err = module.Friends.AddFriend(ctx, bobID, bobWall.WallID, aliceWall.WallID, "alice-share-key-v2", aliceWall.CurrentVersion, "bob-share-key-v2", bobWall.CurrentVersion)- require.Nil(t, duplicate)- require.ErrorIs(t, err, ErrAlreadyFollowing)- incoming, err := module.Follow.ListIncomingRequests(ctx, aliceID)require.NoError(t, err)- require.Empty(t, incoming)-}--func TestApproveRequestRejectsStaleRequestStates(t *testing.T) {- for _, status := range []string{"cancelled", "rejected", "unfollowed", "approved"} {- t.Run(status, func(t *testing.T) {- ctx := context.Background()- module := newWallTestModule(t)-- aliceID := insertWallUser(t, module, "[email protected]", "alice-public")- bobID := insertWallUser(t, module, "[email protected]", "bob-public")- aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")- require.NoError(t, err)- _, err = module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")- require.NoError(t, err)- request, err := module.Follow.CreateRequest(ctx, bobID, aliceWall.WallID)- require.NoError(t, err)-- if status == "approved" {- _, err = module.Follow.ApproveRequest(ctx, request.RequestID, aliceWall.WallID, "initial-share-key", aliceWall.CurrentVersion)- require.NoError(t, err)- err = module.Follow.DeleteShareByWallAndFollower(ctx, aliceWall.WallID, bobID)- require.NoError(t, err)- } else {- err = module.Follow.UpdateRequestStatus(ctx, request.RequestID, status)- require.NoError(t, err)- }-- approved, err := module.Follow.ApproveRequest(ctx, request.RequestID, aliceWall.WallID, "stale-share-key", aliceWall.CurrentVersion)- require.Nil(t, approved)- require.ErrorIs(t, err, sql.ErrNoRows)- _, err = module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)- require.ErrorIs(t, err, sql.ErrNoRows)- })- }-}--func TestUpdatePendingRequestStatusOnlyUpdatesPendingRequests(t *testing.T) {- for _, status := range []string{"cancelled", "rejected"} {- t.Run(status, func(t *testing.T) {- ctx := context.Background()- module := newWallTestModule(t)-- aliceID := insertWallUser(t, module, "[email protected]", "alice-public")- bobID := insertWallUser(t, module, "[email protected]", "bob-public")- aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")- require.NoError(t, err)- _, err = module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")- require.NoError(t, err)- request, err := module.Follow.CreateRequest(ctx, bobID, aliceWall.WallID)- require.NoError(t, err)-- err = module.Follow.UpdatePendingRequestStatus(ctx, request.RequestID, status)- require.NoError(t, err)-- stored, err := module.Follow.GetRequest(ctx, request.RequestID)- require.NoError(t, err)- require.Equal(t, status, stored.Status)- })- }-}--func TestUpdatePendingRequestStatusRejectsApprovedRequests(t *testing.T) {- for _, status := range []string{"cancelled", "rejected"} {- t.Run(status, func(t *testing.T) {- ctx := context.Background()- module := newWallTestModule(t)-- aliceID := insertWallUser(t, module, "[email protected]", "alice-public")- bobID := insertWallUser(t, module, "[email protected]", "bob-public")- aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")- require.NoError(t, err)- _, err = module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")- require.NoError(t, err)- request, err := module.Follow.CreateRequest(ctx, bobID, aliceWall.WallID)- require.NoError(t, err)- _, err = module.Follow.ApproveRequest(ctx, request.RequestID, aliceWall.WallID, "share-key", aliceWall.CurrentVersion)- require.NoError(t, err)-- err = module.Follow.UpdatePendingRequestStatus(ctx, request.RequestID, status)- require.ErrorIs(t, err, sql.ErrNoRows)-- stored, err := module.Follow.GetRequest(ctx, request.RequestID)- require.NoError(t, err)- require.Equal(t, "approved", stored.Status)- share, err := module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)- require.NoError(t, err)- require.Equal(t, "share-key", share.EncryptedWallKey)- })- }+ share, err := module.Friends.GetShareForFriendAndWall(ctx, bobID, aliceWall.WallID)+ require.NoError(t, err)+ require.Equal(t, "alice-share-key-v2", share.EncryptedWallKey)+ var eventCount int+ err = module.Friends.DB.QueryRow(`SELECT COUNT(*) FROM wall_friend_events WHERE actor_id = $1 AND target_id = $2`, bobID, aliceID).Scan(&eventCount)+ require.NoError(t, err)+ require.Equal(t, 1, eventCount)}func TestUpdateShareOnlyRefreshesExistingShares(t *testing.T) {@@ -459,25 +371,25 @@ func TestUpdateShareOnlyRefreshesExistingShares(t *testing.T) {_, err = module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")require.NoError(t, err)- err = module.Follow.UpsertShare(ctx, aliceWall.WallID, bobID, "share-key-v1", aliceWall.CurrentVersion)+ err = module.Friends.UpsertShare(ctx, aliceWall.WallID, bobID, "share-key-v1", aliceWall.CurrentVersion)require.NoError(t, err)rotatedWall, err := module.Walls.RotateKey(ctx, aliceID, aliceWall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)require.NoError(t, err)- err = module.Follow.UpdateShare(ctx, aliceWall.WallID, bobID, "share-key-v2", rotatedWall.CurrentVersion)+ err = module.Friends.UpdateShare(ctx, aliceWall.WallID, bobID, "share-key-v2", rotatedWall.CurrentVersion)require.NoError(t, err)- share, err := module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)+ share, err := module.Friends.GetShareForFriendAndWall(ctx, bobID, aliceWall.WallID)require.NoError(t, err)require.Equal(t, "share-key-v2", share.EncryptedWallKey)require.Equal(t, rotatedWall.CurrentVersion, share.KeyVersion)- err = module.Follow.DeleteShareByWallAndFollower(ctx, aliceWall.WallID, bobID)+ err = module.Friends.DeleteShareByWallAndFriend(ctx, aliceWall.WallID, bobID)require.NoError(t, err)- err = module.Follow.UpdateShare(ctx, aliceWall.WallID, bobID, "stale-share-key", rotatedWall.CurrentVersion)+ err = module.Friends.UpdateShare(ctx, aliceWall.WallID, bobID, "stale-share-key", rotatedWall.CurrentVersion)require.ErrorIs(t, err, sql.ErrNoRows)- _, err = module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)+ _, err = module.Friends.GetShareForFriendAndWall(ctx, bobID, aliceWall.WallID)require.ErrorIs(t, err, sql.ErrNoRows)}@@ -501,7 +413,7 @@ func TestCreatePostRejectsStaleKeyVersion(t *testing.T) {require.Empty(t, posts)}-func TestApproveRequestRejectsStaleKeyVersion(t *testing.T) {+func TestAddFriendRejectsStaleKeyVersion(t *testing.T) {ctx := context.Background()module := newWallTestModule(t)@@ -509,21 +421,17 @@ func TestApproveRequestRejectsStaleKeyVersion(t *testing.T) {bobID := insertWallUser(t, module, "[email protected]", "bob-public")aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")require.NoError(t, err)- _, err = module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")- require.NoError(t, err)- request, err := module.Follow.CreateRequest(ctx, bobID, aliceWall.WallID)+ bobWall, err := module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")require.NoError(t, err)_, err = module.Walls.RotateKey(ctx, aliceID, aliceWall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)require.NoError(t, err)- approved, err := module.Follow.ApproveRequest(ctx, request.RequestID, aliceWall.WallID, "stale-share-key", aliceWall.CurrentVersion)- require.Nil(t, approved)+ err = module.Friends.AddFriend(ctx, bobID, bobWall.WallID, aliceWall.WallID, "stale-share-key", aliceWall.CurrentVersion, "bob-share-key", bobWall.CurrentVersion)require.ErrorIs(t, err, sql.ErrNoRows)- stored, err := module.Follow.GetRequest(ctx, request.RequestID)- require.NoError(t, err)- require.Equal(t, "pending", stored.Status)- _, err = module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)+ _, err = module.Friends.GetShareForFriendAndWall(ctx, bobID, aliceWall.WallID)+ require.ErrorIs(t, err, sql.ErrNoRows)+ _, err = module.Friends.GetShareForFriendAndWall(ctx, aliceID, bobWall.WallID)require.ErrorIs(t, err, sql.ErrNoRows)}@@ -537,15 +445,15 @@ func TestUpdateShareRejectsStaleKeyVersion(t *testing.T) {require.NoError(t, err)_, err = module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")require.NoError(t, err)- err = module.Follow.UpsertShare(ctx, aliceWall.WallID, bobID, "share-key-v1", aliceWall.CurrentVersion)+ err = module.Friends.UpsertShare(ctx, aliceWall.WallID, bobID, "share-key-v1", aliceWall.CurrentVersion)require.NoError(t, err)_, err = module.Walls.RotateKey(ctx, aliceID, aliceWall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)require.NoError(t, err)- err = module.Follow.UpdateShare(ctx, aliceWall.WallID, bobID, "stale-share-key", aliceWall.CurrentVersion)+ err = module.Friends.UpdateShare(ctx, aliceWall.WallID, bobID, "stale-share-key", aliceWall.CurrentVersion)require.ErrorIs(t, err, sql.ErrNoRows)- share, err := module.Follow.GetShareForFollowerAndWall(ctx, bobID, aliceWall.WallID)+ share, err := module.Friends.GetShareForFriendAndWall(ctx, bobID, aliceWall.WallID)require.NoError(t, err)require.Equal(t, "share-key-v1", share.EncryptedWallKey)require.Equal(t, aliceWall.CurrentVersion, share.KeyVersion)@@ -770,7 +678,58 @@ func TestListFeedCursorUsesCreatedAtSortOrder(t *testing.T) {require.Equal(t, "2000:"+strconv.FormatInt(second, 10), nextCursor)}-func TestListTopLevelCommentsPaginates(t *testing.T) {+func TestNotificationsIncludeWallSocialEvents(t *testing.T) {+ ctx := context.Background()+ module := newWallTestModule(t)++ aliceID := insertWallUser(t, module, "[email protected]", "alice-public")+ bobID := insertWallUser(t, module, "[email protected]", "bob-public")+ aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")+ require.NoError(t, err)+ bobWall, err := module.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")+ require.NoError(t, err)++ postID, err := module.Posts.CreatePost(ctx, aliceID, aliceWall.WallID, "post-key", nil, aliceWall.CurrentVersion, nil)+ require.NoError(t, err)+ err = module.Posts.SetLike(ctx, postID, bobID, true)+ require.NoError(t, err)+ setPostLikeCreatedAt(t, module, 2000, postID, bobID)++ bobComment, err := module.Posts.CreateComment(ctx, postID, bobID, "bob-comment", nil)+ require.NoError(t, err)+ setCommentCreatedAt(t, module, 3000, bobComment.CommentID)++ aliceComment, err := module.Posts.CreateComment(ctx, postID, aliceID, "alice-comment", nil)+ require.NoError(t, err)+ bobReply, err := module.Posts.CreateComment(ctx, postID, bobID, "bob-reply", &aliceComment.CommentID)+ require.NoError(t, err)+ setCommentCreatedAt(t, module, 4000, bobReply.CommentID)++ err = module.Posts.SetCommentLike(ctx, postID, aliceComment.CommentID, bobID, true)+ require.NoError(t, err)+ setCommentLikeCreatedAt(t, module, 5000, aliceComment.CommentID, bobID)++ err = module.Friends.AddFriend(ctx, bobID, bobWall.WallID, aliceWall.WallID, "alice-share-key", aliceWall.CurrentVersion, "bob-share-key", bobWall.CurrentVersion)+ require.NoError(t, err)+ setFriendEventCreatedAt(t, module, 6000, bobID, aliceID)++ page, nextCursor, err := module.Notifications.List(ctx, aliceID, "", 3)+ require.NoError(t, err)+ require.Len(t, page, 3)+ require.Equal(t, "addedYouAsFriend", page[0].Type)+ require.Equal(t, "likedComment", page[1].Type)+ require.Equal(t, "repliedToComment", page[2].Type)+ require.NotEmpty(t, nextCursor)++ page, nextCursor, err = module.Notifications.List(ctx, aliceID, nextCursor, 3)+ require.NoError(t, err)+ require.Len(t, page, 2)+ require.Equal(t, "commentedOnPost", page[0].Type)+ require.Equal(t, "likedPost", page[1].Type)+ require.Empty(t, nextCursor)+}++func TestListCommentsPaginates(t *testing.T) {ctx := context.Background()module := newWallTestModule(t)@@ -787,14 +746,14 @@ func TestListTopLevelCommentsPaginates(t *testing.T) {third, err := module.Posts.CreateComment(ctx, postID, aliceID, "comment-3", nil)require.NoError(t, err)- page, nextCursor, err := module.Posts.ListTopLevelComments(ctx, postID, aliceID, "", 2)+ page, nextCursor, err := module.Posts.ListComments(ctx, postID, aliceID, "", 2)require.NoError(t, err)require.Len(t, page, 2)require.Equal(t, third.CommentID, page[0].CommentID)require.Equal(t, second.CommentID, page[1].CommentID)require.Equal(t, strconv.FormatInt(second.CommentID, 10), nextCursor)- page, nextCursor, err = module.Posts.ListTopLevelComments(ctx, postID, aliceID, nextCursor, 2)+ page, nextCursor, err = module.Posts.ListComments(ctx, postID, aliceID, nextCursor, 2)require.NoError(t, err)require.Len(t, page, 1)require.Equal(t, first.CommentID, page[0].CommentID)@@ -873,3 +832,27 @@ func setPostCreatedAt(t *testing.T, module *Module, createdAt int64, postIDs ...require.NoError(t, err)}}++func setPostLikeCreatedAt(t *testing.T, module *Module, createdAt, postID, userID int64) {+ t.Helper()+ _, err := module.Posts.DB.Exec(`UPDATE wall_post_likes SET created_at = $1 WHERE post_id = $2 AND user_id = $3`, createdAt, postID, userID)+ require.NoError(t, err)+}++func setCommentCreatedAt(t *testing.T, module *Module, createdAt, commentID int64) {+ t.Helper()+ _, err := module.Posts.DB.Exec(`UPDATE wall_post_comments SET created_at = $1 WHERE comment_id = $2`, createdAt, commentID)+ require.NoError(t, err)+}++func setCommentLikeCreatedAt(t *testing.T, module *Module, createdAt, commentID, userID int64) {+ t.Helper()+ _, err := module.Posts.DB.Exec(`UPDATE wall_comment_likes SET created_at = $1 WHERE comment_id = $2 AND user_id = $3`, createdAt, commentID, userID)+ require.NoError(t, err)+}++func setFriendEventCreatedAt(t *testing.T, module *Module, createdAt, actorID, targetID int64) {+ t.Helper()+ _, err := module.Friends.DB.Exec(`UPDATE wall_friend_events SET created_at = $1 WHERE actor_id = $2 AND target_id = $3`, createdAt, actorID, targetID)+ require.NoError(t, err)+}diff --git a/server/wall/repo/notifications.go b/server/wall/repo/notifications.gonew file mode 100644index 0000000000..9a87eb53fe--- /dev/null+++ b/server/wall/repo/notifications.go@@ -0,0 +1,330 @@+package repo++import (+ "context"+ "strconv"+ "strings"++ "github.com/ente-io/stacktrace"+)++const wallNotificationRows = `+ SELECT+ 'post_like:' || pl.post_id::text || ':' || pl.user_id::text AS notification_id,+ 'likedPost' AS notification_type,+ pl.created_at,+ pl.user_id AS actor_id,+ actor_wall.wall_slug AS actor_username,+ actor_wall.wall_id AS actor_wall_id,+ actor_wall.wall_slug AS actor_wall_slug,+ p.post_id,+ p.wall_id AS post_wall_id,+ post_wall.wall_slug AS post_wall_slug,+ p.owner_id AS post_owner_id,+ owner_wall.wall_slug AS post_author,+ 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,+ NULL::bigint AS comment_id,+ NULL::bigint AS parent_comment_id,+ NULL::bigint AS comment_author_id,+ NULL::text AS comment_author,+ NULL::text AS comment_cipher,+ NULL::bigint AS comment_created_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+ JOIN walls post_wall ON post_wall.wall_id = p.wall_id+ JOIN walls owner_wall ON owner_wall.owner_id = p.owner_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 p.owner_id = $1+ AND pl.user_id <> $1+ AND p.is_deleted = FALSE++ UNION ALL++ SELECT+ 'comment:' || c.comment_id::text AS notification_id,+ 'commentedOnPost' AS notification_type,+ c.created_at,+ c.author_id AS actor_id,+ actor_wall.wall_slug AS actor_username,+ actor_wall.wall_id AS actor_wall_id,+ actor_wall.wall_slug AS actor_wall_slug,+ p.post_id,+ p.wall_id AS post_wall_id,+ post_wall.wall_slug AS post_wall_slug,+ p.owner_id AS post_owner_id,+ owner_wall.wall_slug AS post_author,+ 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,+ c.comment_id,+ NULL::bigint AS parent_comment_id,+ c.author_id AS comment_author_id,+ actor_wall.wall_slug AS comment_author,+ c.comment_cipher,+ c.created_at AS comment_created_at+ FROM wall_post_comments c+ JOIN wall_posts p ON p.post_id = c.post_id+ JOIN walls actor_wall ON actor_wall.owner_id = c.author_id+ JOIN walls post_wall ON post_wall.wall_id = p.wall_id+ JOIN walls owner_wall ON owner_wall.owner_id = p.owner_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 p.owner_id = $1+ AND c.author_id <> $1+ AND c.parent_comment_id IS NULL+ AND c.is_deleted = FALSE+ AND p.is_deleted = FALSE++ UNION ALL++ SELECT+ 'reply:' || c.comment_id::text AS notification_id,+ 'repliedToComment' AS notification_type,+ c.created_at,+ c.author_id AS actor_id,+ actor_wall.wall_slug AS actor_username,+ actor_wall.wall_id AS actor_wall_id,+ actor_wall.wall_slug AS actor_wall_slug,+ p.post_id,+ p.wall_id AS post_wall_id,+ post_wall.wall_slug AS post_wall_slug,+ p.owner_id AS post_owner_id,+ owner_wall.wall_slug AS post_author,+ 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,+ c.comment_id,+ c.parent_comment_id,+ c.author_id AS comment_author_id,+ actor_wall.wall_slug AS comment_author,+ c.comment_cipher,+ c.created_at AS comment_created_at+ FROM wall_post_comments c+ JOIN wall_post_comments parent ON parent.comment_id = c.parent_comment_id+ JOIN wall_posts p ON p.post_id = c.post_id+ JOIN walls actor_wall ON actor_wall.owner_id = c.author_id+ JOIN walls post_wall ON post_wall.wall_id = p.wall_id+ JOIN walls owner_wall ON owner_wall.owner_id = p.owner_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 parent.author_id = $1+ AND c.author_id <> $1+ AND c.is_deleted = FALSE+ AND parent.is_deleted = FALSE+ AND p.is_deleted = FALSE++ UNION ALL++ SELECT+ 'comment_like:' || cl.comment_id::text || ':' || cl.user_id::text AS notification_id,+ 'likedComment' AS notification_type,+ cl.created_at,+ cl.user_id AS actor_id,+ actor_wall.wall_slug AS actor_username,+ actor_wall.wall_id AS actor_wall_id,+ actor_wall.wall_slug AS actor_wall_slug,+ p.post_id,+ p.wall_id AS post_wall_id,+ post_wall.wall_slug AS post_wall_slug,+ p.owner_id AS post_owner_id,+ owner_wall.wall_slug AS post_author,+ 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,+ c.comment_id,+ c.parent_comment_id,+ c.author_id AS comment_author_id,+ comment_author_wall.wall_slug AS comment_author,+ c.comment_cipher,+ c.created_at AS comment_created_at+ FROM wall_comment_likes cl+ JOIN wall_post_comments c ON c.comment_id = cl.comment_id+ JOIN wall_posts p ON p.post_id = c.post_id+ JOIN walls actor_wall ON actor_wall.owner_id = cl.user_id+ JOIN walls comment_author_wall ON comment_author_wall.owner_id = c.author_id+ JOIN walls post_wall ON post_wall.wall_id = p.wall_id+ JOIN walls owner_wall ON owner_wall.owner_id = p.owner_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.author_id = $1+ AND cl.user_id <> $1+ AND c.is_deleted = FALSE+ AND p.is_deleted = FALSE++ UNION ALL++ SELECT+ 'friend_add:' || fe.event_id::text AS notification_id,+ 'addedYouAsFriend' AS notification_type,+ fe.created_at,+ fe.actor_id,+ actor_wall.wall_slug AS actor_username,+ actor_wall.wall_id AS actor_wall_id,+ actor_wall.wall_slug AS actor_wall_slug,+ NULL::bigint AS post_id,+ NULL::text AS post_wall_id,+ NULL::text AS post_wall_slug,+ NULL::bigint AS post_owner_id,+ NULL::text AS post_author,+ NULL::text AS post_object_key,+ NULL::bigint AS post_object_size,+ NULL::integer AS post_object_position,+ NULL::text AS post_object_variant,+ NULL::text AS post_object_blur_hash_cipher,+ NULL::integer AS post_object_width,+ NULL::integer AS post_object_height,+ NULL::text AS post_object_media_type,+ NULL::bigint AS comment_id,+ NULL::bigint AS parent_comment_id,+ NULL::bigint AS comment_author_id,+ NULL::text AS comment_author,+ NULL::text AS comment_cipher,+ NULL::bigint AS comment_created_at+ FROM wall_friend_events fe+ JOIN walls actor_wall ON actor_wall.wall_id = fe.actor_wall_id+ WHERE fe.target_id = $1+ AND fe.actor_id <> $1+`++func (r *NotificationsRepository) List(ctx context.Context, userID int64, cursor string, limit int) ([]WallNotificationRecord, string, error) {+ limit = optionalInt(limit, 50)+ if limit > 100 {+ limit = 100+ }+ var cursorCreatedAt any+ var cursorID any+ if createdAt, id, ok := parseNotificationCursor(cursor); ok {+ cursorCreatedAt = createdAt+ cursorID = id+ }+ rows, err := r.DB.QueryContext(ctx, `+ WITH notifications AS (`+wallNotificationRows+`)+ SELECT n.notification_id, n.notification_type, n.created_at,+ n.actor_id, n.actor_username, n.actor_wall_id, n.actor_wall_slug,+ n.post_id, n.post_wall_id, n.post_wall_slug, n.post_owner_id, n.post_author,+ n.post_object_key, n.post_object_size, n.post_object_position, n.post_object_variant,+ n.post_object_blur_hash_cipher, n.post_object_width, n.post_object_height, n.post_object_media_type,+ n.comment_id, n.parent_comment_id, n.comment_author_id, n.comment_author, n.comment_cipher, n.comment_created_at+ FROM notifications n+ WHERE ($2::bigint IS NULL OR (n.created_at, n.notification_id) < ($2::bigint, $3::text))+ ORDER BY n.created_at DESC, n.notification_id DESC+ LIMIT $4+ `, userID, cursorCreatedAt, cursorID, limit+1)+ if err != nil {+ return nil, "", stacktrace.Propagate(err, "")+ }+ defer rows.Close()++ out := make([]WallNotificationRecord, 0, limit+1)+ for rows.Next() {+ rec, err := scanNotificationRecord(rows)+ if err != nil {+ return nil, "", err+ }+ out = append(out, *rec)+ }+ if err := rows.Err(); err != nil {+ return nil, "", stacktrace.Propagate(err, "")+ }+ nextCursor := ""+ if len(out) > limit {+ nextCursor = formatNotificationCursor(out[limit-1])+ out = out[:limit]+ }+ return out, nextCursor, nil+}++func scanNotificationRecord(scanner interface{ Scan(dest ...any) error }) (*WallNotificationRecord, error) {+ var rec WallNotificationRecord+ if err := scanner.Scan(+ &rec.ID,+ &rec.Type,+ &rec.CreatedAt,+ &rec.ActorID,+ &rec.ActorUsername,+ &rec.ActorWallID,+ &rec.ActorWallSlug,+ &rec.PostID,+ &rec.PostWallID,+ &rec.PostWallSlug,+ &rec.PostOwnerID,+ &rec.PostAuthor,+ &rec.PostObjectKey,+ &rec.PostObjectSize,+ &rec.PostObjectPosition,+ &rec.PostObjectVariant,+ &rec.PostObjectBlurHashCipher,+ &rec.PostObjectWidth,+ &rec.PostObjectHeight,+ &rec.PostObjectMediaType,+ &rec.CommentID,+ &rec.ParentCommentID,+ &rec.CommentAuthorID,+ &rec.CommentAuthor,+ &rec.CommentCipher,+ &rec.CommentCreatedAt,+ ); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ return &rec, nil+}++func parseNotificationCursor(cursor string) (int64, string, bool) {+ createdAtText, id, ok := strings.Cut(strings.TrimSpace(cursor), ":")+ if !ok || strings.TrimSpace(id) == "" {+ return 0, "", false+ }+ createdAt, err := strconv.ParseInt(createdAtText, 10, 64)+ if err != nil || createdAt <= 0 {+ return 0, "", false+ }+ return createdAt, id, true+}++func formatNotificationCursor(notification WallNotificationRecord) string {+ return strconv.FormatInt(notification.CreatedAt, 10) + ":" + notification.ID+}diff --git a/server/wall/repo/posts.go b/server/wall/repo/posts.goindex d19c7139c4..8e66563e29 100644--- a/server/wall/repo/posts.go+++ b/server/wall/repo/posts.go@@ -41,9 +41,9 @@ func (r *PostsRepository) CreatePost(ctx context.Context, ownerID int64, wallID,}for _, obj := range objects {if _, err := tx.ExecContext(ctx, `- INSERT INTO wall_post_assets (post_id, object_key, bucket_id, size, position, variant, blur_hash_cipher)- VALUES ($1, $2, $3, $4, $5, $6, $7)- `, postID, obj.ObjectKey, obj.BucketID, obj.Size, obj.Position, obj.Variant, obj.BlurHashCipher); err != nil {+ INSERT INTO wall_post_assets (post_id, object_key, bucket_id, size, position, variant, blur_hash_cipher, width, height, media_type)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)+ `, postID, obj.ObjectKey, obj.BucketID, obj.Size, obj.Position, obj.Variant, obj.BlurHashCipher, obj.Width, obj.Height, obj.MediaType); err != nil {return 0, stacktrace.Propagate(err, "")}if err := ConsumeTempObjectTx(ctx, tx, ownerID, obj.ObjectKey, TempObjectPurposePost, nil); err != nil {@@ -135,8 +135,8 @@ func (r *PostsRepository) ListFeed(ctx context.Context, viewerID int64, cursor sAND (p.owner_id = $1 OREXISTS (- SELECT 1 FROM wall_follow_shares fs- WHERE fs.follower_id = $1 AND fs.wall_id = p.wall_id+ SELECT 1 FROM wall_friend_shares fs+ WHERE fs.friend_id = $1 AND fs.wall_id = p.wall_id))`if cursorCreatedAt, cursorPostID, ok := parsePostCursor(cursor); ok {@@ -173,7 +173,7 @@ func (r *PostsRepository) ListAssetsByPostIDs(ctx context.Context, postIDs []intif len(postIDs) == 0 {return map[int64][]WallPostAssetRecord{}, nil}- query, args := inClause("SELECT asset_id, post_id, object_key, bucket_id, size, position, variant, blur_hash_cipher, created_at FROM wall_post_assets WHERE post_id IN (%s) ORDER BY position ASC, asset_id ASC", postIDs, 0)+ query, args := inClause("SELECT asset_id, post_id, object_key, bucket_id, size, position, variant, blur_hash_cipher, width, height, media_type, created_at FROM wall_post_assets WHERE post_id IN (%s) ORDER BY position ASC, asset_id ASC", postIDs, 0)rows, err := r.DB.QueryContext(ctx, query, args...)if err != nil {return nil, stacktrace.Propagate(err, "")@@ -182,7 +182,7 @@ func (r *PostsRepository) ListAssetsByPostIDs(ctx context.Context, postIDs []intresult := make(map[int64][]WallPostAssetRecord, len(postIDs))for rows.Next() {var rec WallPostAssetRecord- if err := rows.Scan(&rec.AssetID, &rec.PostID, &rec.ObjectKey, &rec.BucketID, &rec.Size, &rec.Position, &rec.Variant, &rec.BlurHashCipher, &rec.CreatedAt); err != nil {+ if err := rows.Scan(&rec.AssetID, &rec.PostID, &rec.ObjectKey, &rec.BucketID, &rec.Size, &rec.Position, &rec.Variant, &rec.BlurHashCipher, &rec.Width, &rec.Height, &rec.MediaType, &rec.CreatedAt); err != nil {return nil, stacktrace.Propagate(err, "")}result[rec.PostID] = append(result[rec.PostID], rec)@@ -295,6 +295,8 @@ func (r *PostsRepository) CreateComment(ctx context.Context, postID, authorID infunc (r *PostsRepository) GetComment(ctx context.Context, commentID, viewerID int64) (*WallCommentRecord, error) {return scanCommentRecord(r.DB.QueryRowContext(ctx, `SELECT c.comment_id, c.post_id, c.author_id, author_wall.wall_slug, c.comment_cipher, c.parent_comment_id, c.created_at,+ (SELECT COUNT(*) FROM wall_comment_likes cl WHERE cl.comment_id = c.comment_id) AS likes,+ EXISTS (SELECT 1 FROM wall_comment_likes cl WHERE cl.comment_id = c.comment_id AND cl.user_id = $2) AS viewer_liked,(c.author_id = $2) AS viewer_can_deleteFROM wall_post_comments cJOIN walls author_wall ON author_wall.owner_id = c.author_id@@ -302,7 +304,7 @@ func (r *PostsRepository) GetComment(ctx context.Context, commentID, viewerID in`, commentID, viewerID))}-func (r *PostsRepository) ListTopLevelComments(ctx context.Context, postID, viewerID int64, cursor string, limit int) ([]WallCommentRecord, string, error) {+func (r *PostsRepository) ListComments(ctx context.Context, postID, viewerID int64, cursor string, limit int) ([]WallCommentRecord, string, error) {limit = optionalInt(limit, 20)if limit > 100 {limit = 100@@ -310,10 +312,12 @@ func (r *PostsRepository) ListTopLevelComments(ctx context.Context, postID, viewargs := []any{postID, viewerID}query := `SELECT c.comment_id, c.post_id, c.author_id, author_wall.wall_slug, c.comment_cipher, c.parent_comment_id, c.created_at,- (c.author_id = $2) AS viewer_can_delete- FROM wall_post_comments c- JOIN walls author_wall ON author_wall.owner_id = c.author_id- WHERE c.post_id = $1 AND c.parent_comment_id IS NULL AND c.is_deleted = FALSE`+ (SELECT COUNT(*) FROM wall_comment_likes cl WHERE cl.comment_id = c.comment_id) AS likes,+ EXISTS (SELECT 1 FROM wall_comment_likes cl WHERE cl.comment_id = c.comment_id AND cl.user_id = $2) AS viewer_liked,+ (c.author_id = $2) AS viewer_can_delete+ FROM wall_post_comments c+ JOIN walls author_wall ON author_wall.owner_id = c.author_id+ WHERE c.post_id = $1 AND c.is_deleted = FALSE`if trimmed := strings.TrimSpace(cursor); trimmed != "" {if cursorID, err := strconv.ParseInt(trimmed, 10, 64); err == nil && cursorID > 0 {args = append(args, cursorID)@@ -346,35 +350,26 @@ func (r *PostsRepository) ListTopLevelComments(ctx context.Context, postID, viewreturn out, nextCursor, nil}-func (r *PostsRepository) ListReplies(ctx context.Context, postID, viewerID int64, parentIDs []int64) (map[int64][]WallCommentRecord, error) {- if len(parentIDs) == 0 {- return map[int64][]WallCommentRecord{}, nil- }- query, args := inClause(`- SELECT c.comment_id, c.post_id, c.author_id, author_wall.wall_slug, c.comment_cipher, c.parent_comment_id, c.created_at,- (c.author_id = $1) AS viewer_can_delete- FROM wall_post_comments c- JOIN walls author_wall ON author_wall.owner_id = c.author_id- WHERE c.post_id = $2 AND c.parent_comment_id IN (%s) AND c.is_deleted = FALSE- ORDER BY c.comment_id ASC- `, parentIDs, 2)- args = append([]any{viewerID, postID}, args...)- rows, err := r.DB.QueryContext(ctx, query, args...)- if err != nil {- return nil, stacktrace.Propagate(err, "")- }- defer rows.Close()- result := make(map[int64][]WallCommentRecord)- for rows.Next() {- rec, err := scanCommentRecord(rows)- if err != nil {- return nil, err- }- if rec.ParentCommentID.Valid {- result[rec.ParentCommentID.Int64] = append(result[rec.ParentCommentID.Int64], *rec)- }+func (r *PostsRepository) SetCommentLike(ctx context.Context, postID, commentID, userID int64, like bool) error {+ if like {+ _, err := r.DB.ExecContext(ctx, `+ INSERT INTO wall_comment_likes (comment_id, user_id)+ SELECT c.comment_id, $3+ FROM wall_post_comments c+ WHERE c.post_id = $1 AND c.comment_id = $2 AND c.is_deleted = FALSE+ ON CONFLICT DO NOTHING+ `, postID, commentID, userID)+ return stacktrace.Propagate(err, "")}- return result, stacktrace.Propagate(rows.Err(), "")+ _, err := r.DB.ExecContext(ctx, `+ DELETE FROM wall_comment_likes cl+ USING wall_post_comments c+ WHERE cl.comment_id = c.comment_id+ AND c.post_id = $1+ AND c.comment_id = $2+ AND cl.user_id = $3+ `, postID, commentID, userID)+ return stacktrace.Propagate(err, "")}func (r *PostsRepository) DeleteComment(ctx context.Context, postID, commentID, viewerID int64) error {@@ -422,7 +417,7 @@ func formatPostCursor(post WallPostRecord) string {func scanCommentRecord(scanner interface{ Scan(dest ...any) error }) (*WallCommentRecord, error) {var rec WallCommentRecord- if err := scanner.Scan(&rec.CommentID, &rec.PostID, &rec.AuthorID, &rec.Author, &rec.CommentCipher, &rec.ParentCommentID, &rec.CreatedAt, &rec.ViewerCanDelete); err != nil {+ if err := scanner.Scan(&rec.CommentID, &rec.PostID, &rec.AuthorID, &rec.Author, &rec.CommentCipher, &rec.ParentCommentID, &rec.CreatedAt, &rec.Likes, &rec.ViewerLiked, &rec.ViewerCanDelete); err != nil {return nil, stacktrace.Propagate(err, "")}return &rec, nildiff --git a/server/wall/repo/walls.go b/server/wall/repo/walls.goindex 8ed129b5b4..3ef61a08d8 100644--- a/server/wall/repo/walls.go+++ b/server/wall/repo/walls.go@@ -84,6 +84,16 @@ func (r *WallsRepository) GetWallBySlug(ctx context.Context, wallSlug string) (*`, normalizeSlug(wallSlug)))}+func (r *WallsRepository) GetOwnerPublicKey(ctx context.Context, ownerID int64) (string, error) {+ var publicKey string+ err := r.DB.QueryRowContext(ctx, `+ SELECT public_key+ FROM key_attributes+ WHERE user_id = $1+ `, ownerID).Scan(&publicKey)+ return publicKey, stacktrace.Propagate(err, "")+}+func (r *WallsRepository) UpdateProfile(ctx context.Context, ownerID int64, wallID, encryptedProfile string, avatar *struct {ObjectKey stringBucketID string