Skip to content

armgit / ente

Public Imported from GitHub
0

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

Complete wall social bindings

Anand Baburajan39ce88dc43bb
diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rs
index 59cfbd3826..5b560ab31a 100644
--- a/rust/wall/src/client.rs
+++ b/rust/wall/src/client.rs
@@ -15,14 +15,15 @@ use crate::models::{
use crate::transport::{
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, WallNotificationPage, WallProfileResponse,
+ EntityKeyPayload, EntityKeyResponse, FriendRelationshipResponse, FriendShareResponse,
+ FriendStatusResponse, FriendTargetPayload, LikeCommentRequest, LikeCommentResponse,
+ LikePostRequest, LikePostResponse, ListCommentsResponse, ListPostLikersResponse,
+ PostObjectPayload, PostPage, PostResponse, PresignUploadRequest, PresignUploadResponse,
+ ProfileAvatarPayload, RefreshFriendSharesRequest, RotateWallKeyRequest, ShareUpdatePayload,
+ UpdatePostCaptionRequest, UpdateWallProfileRequest, UpdateWallProfileResponse,
+ UpdateWallSlugRequest, WallFriendResponse, WallKeyResponse, WallKeyVersionResponse,
+ WallLinkCreateRequest, WallLinkLoginRequest, WallLinkLoginResponse, WallLinkStatusResponse,
+ WallLookupResponse, WallNotificationPage, WallProfileResponse,
};
use ente_core::crypto::{sealed, secretbox};
use ente_core::http::{Error as HttpError, HttpClient, HttpConfig};
@@ -463,6 +464,21 @@ impl AccountWallCtx {
})
}
+ pub async fn upload_post_photo_asset(
+ &self,
+ post_key: &[u8],
+ plaintext: &[u8],
+ width: Option<i32>,
+ height: Option<i32>,
+ media_type: Option<String>,
+ ) -> Result<PostObjectPayload> {
+ let mut object = self.upload_post_asset(post_key, plaintext, Some(0)).await?;
+ object.width = width.filter(|value| *value > 0);
+ object.height = height.filter(|value| *value > 0);
+ object.media_type = media_type.filter(|value| !value.trim().is_empty());
+ Ok(object)
+ }
+
pub async fn upload_avatar(
&self,
wall_id: &str,
@@ -609,12 +625,23 @@ impl AccountWallCtx {
.map_err(Into::into)
}
- pub async fn fetch_post_decrypted(&self, post_id: i64) -> Result<DecryptedPost> {
+ pub async fn get_post(&self, post_id: i64) -> Result<PostResponse> {
let path = format!("/wall/posts/{post_id}");
- let post: PostResponse = self.client.get_json(&path, &[]).await?;
+ self.client.get_json(&path, &[]).await.map_err(Into::into)
+ }
+
+ pub async fn fetch_post_decrypted(&self, post_id: i64) -> Result<DecryptedPost> {
+ let post = self.get_post(post_id).await?;
self.decrypt_post_for_wall(&post.wall_id, &post).await
}
+ pub async fn download_post_asset(&self, post_id: i64, object_key: &str) -> Result<Vec<u8>> {
+ let post = self.get_post(post_id).await?;
+ let decrypted = self.decrypt_post_for_wall(&post.wall_id, &post).await?;
+ self.download_decrypted_asset(&post.wall_id, object_key, &decrypted.post_key)
+ .await
+ }
+
pub async fn hydrate_wall_keys(&self) -> Result<HydratedKeys> {
let root_wall_key = self.get_root_wall_key().await?;
let owned_records = self.list_owned_walls().await?;
@@ -725,6 +752,26 @@ impl AccountWallCtx {
.map_err(Into::into)
}
+ pub async fn list_post_likers(
+ &self,
+ post_id: i64,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<ListPostLikersResponse> {
+ 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()));
+ }
+ let path = format!("/wall/posts/{post_id}/likes");
+ self.client
+ .get_json(&path, &query)
+ .await
+ .map_err(Into::into)
+ }
+
pub async fn like_comment(
&self,
post_id: i64,
@@ -850,6 +897,17 @@ impl AccountWallCtx {
.map_err(Into::into)
}
+ pub async fn get_relationship(
+ &self,
+ target_wall_id: &str,
+ ) -> Result<FriendRelationshipResponse> {
+ let query = vec![("targetWallId", target_wall_id.to_owned())];
+ self.client
+ .get_json("/wall/friends/relationship", &query)
+ .await
+ .map_err(Into::into)
+ }
+
pub async fn refresh_friend_shares(&self, wall_id: &str) -> Result<usize> {
let access = self
.resolve_owned_wall_access(wall_id)
@@ -984,6 +1042,7 @@ fn post_response_from_feed_item(item: &FeedItem) -> PostResponse {
post_id: item.post_id,
wall_id: item.wall_id.clone(),
wall_slug: item.wall_slug.clone(),
+ owner_user_id: item.owner_user_id,
author: item.wall_slug.clone(),
encrypted_post_key: item.encrypted_post_key.clone(),
caption_cipher: item.caption_cipher.clone(),
@@ -1112,6 +1171,11 @@ impl WallLinkCtx {
.map_err(Into::into)
}
+ pub async fn get_post(&self, post_id: i64) -> Result<PostResponse> {
+ let path = format!("/wall/posts/{post_id}");
+ self.client.get_json(&path, &[]).await.map_err(Into::into)
+ }
+
pub async fn decrypt_post_key(&self, post: &PostResponse) -> Result<Vec<u8>> {
let wall_key = self
.resolve_wall_key_for_version(Some(post.key_version))
@@ -1139,6 +1203,13 @@ impl WallLinkCtx {
})
}
+ pub async fn download_post_asset(&self, post_id: i64, object_key: &str) -> Result<Vec<u8>> {
+ let post = self.get_post(post_id).await?;
+ let decrypted = self.decrypt_post(&post).await?;
+ self.download_decrypted_asset(object_key, &decrypted.post_key)
+ .await
+ }
+
pub async fn list_comments(
&self,
post_id: i64,
@@ -1170,6 +1241,26 @@ impl WallLinkCtx {
})
}
+ pub async fn list_post_likers(
+ &self,
+ post_id: i64,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<ListPostLikersResponse> {
+ 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()));
+ }
+ let path = format!("/wall/posts/{post_id}/likes");
+ self.client
+ .get_json(&path, &query)
+ .await
+ .map_err(Into::into)
+ }
+
pub async fn list_wall_key_versions(&self) -> Result<Vec<WallKeyVersionResponse>> {
let query = vec![("wallId", self.wall_id.clone())];
self.client
@@ -1590,6 +1681,7 @@ mod tests {
post_id: 42,
wall_id: "wall_owner_gallery".to_owned(),
wall_slug: "owner-gallery".to_owned(),
+ owner_user_id: 7,
author: "owner-gallery".to_owned(),
encrypted_post_key: encode_b64(
&encrypt_secretbox_packed(&previous_wall_key, &post_key)
@@ -1886,6 +1978,105 @@ mod tests {
like.assert_async().await;
}
+ #[tokio::test]
+ async fn list_post_likers_uses_post_likes_endpoint() {
+ let mut server = Server::new_async().await;
+ let ctx = test_account_ctx(&server.url());
+ let likers = server
+ .mock("GET", "/wall/posts/42/likes")
+ .match_header("x-auth-token", "token")
+ .match_query(Matcher::AllOf(vec![
+ Matcher::UrlEncoded("cursor".into(), "3000:7".into()),
+ Matcher::UrlEncoded("limit".into(), "5".into()),
+ ]))
+ .with_status(200)
+ .with_body(
+ json!({
+ "likers": [{
+ "userId": 8,
+ "wallId": "wall_liker",
+ "wallSlug": "liker",
+ "createdAt": "2026-04-16T00:00:00Z"
+ }],
+ "nextCursor": "2000:8"
+ })
+ .to_string(),
+ )
+ .create_async()
+ .await;
+
+ let response = ctx
+ .list_post_likers(42, Some("3000:7".to_owned()), Some(5))
+ .await
+ .expect("likers should load");
+
+ assert_eq!(response.likers[0].wall_id, "wall_liker");
+ assert_eq!(response.next_cursor, "2000:8");
+ likers.assert_async().await;
+ }
+
+ #[tokio::test]
+ async fn get_relationship_uses_relationship_endpoint() {
+ let mut server = Server::new_async().await;
+ let ctx = test_account_ctx(&server.url());
+ let relationship = server
+ .mock("GET", "/wall/friends/relationship")
+ .match_header("x-auth-token", "token")
+ .match_query(Matcher::UrlEncoded(
+ "targetWallId".into(),
+ "wall_friend".into(),
+ ))
+ .with_status(200)
+ .with_body(json!({"relationship": "friend"}).to_string())
+ .create_async()
+ .await;
+
+ let response = ctx
+ .get_relationship("wall_friend")
+ .await
+ .expect("relationship should load");
+
+ assert_eq!(response.relationship, "friend");
+ relationship.assert_async().await;
+ }
+
+ #[tokio::test]
+ async fn wall_link_list_post_likers_uses_session_token() {
+ let mut server = Server::new_async().await;
+ let ctx = 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(),
+ owner_public_key: Vec::new(),
+ wall_key: generate_key(),
+ key_version: 1,
+ };
+ let likers = server
+ .mock("GET", "/wall/posts/42/likes")
+ .match_header("x-auth-token", "link-session-token")
+ .with_status(200)
+ .with_body(json!({"likers": [], "nextCursor": ""}).to_string())
+ .create_async()
+ .await;
+
+ let response = ctx
+ .list_post_likers(42, None, None)
+ .await
+ .expect("link likers should load");
+
+ assert!(response.likers.is_empty());
+ likers.assert_async().await;
+ }
+
#[tokio::test]
async fn refresh_friend_shares_accepts_empty_server_response() {
let mut server = Server::new_async().await;
diff --git a/rust/wall/src/lib.rs b/rust/wall/src/lib.rs
index eac985231e..dd6d5352c5 100644
--- a/rust/wall/src/lib.rs
+++ b/rust/wall/src/lib.rs
@@ -12,10 +12,11 @@ pub use models::{
OpenWallLinkCtxInput, PrivateKeySource,
};
pub use transport::{
- CommentResponse, EntityKeyPayload, FriendShareResponse, FriendStatusResponse,
- LikeCommentResponse, LikePostResponse, PostObjectPayload, PostPage, PostResponse,
- PresignUploadResponse, ProfileAvatarPayload, ProfileAvatarResponse, WallFriendResponse,
- WallKeyResponse, WallKeyVersionResponse, WallLinkLoginResponse, WallLinkStatusResponse,
- WallLookupResponse, WallNotification, WallNotificationActor, WallNotificationComment,
- WallNotificationPage, WallNotificationPost, WallNotificationType, WallProfileResponse,
+ CommentResponse, EntityKeyPayload, FriendRelationshipResponse, FriendShareResponse,
+ FriendStatusResponse, LikeCommentResponse, LikePostResponse, ListPostLikersResponse,
+ PostLikerResponse, PostObjectPayload, PostPage, PostResponse, PresignUploadResponse,
+ ProfileAvatarPayload, ProfileAvatarResponse, WallFriendResponse, WallKeyResponse,
+ WallKeyVersionResponse, WallLinkLoginResponse, WallLinkStatusResponse, WallLookupResponse,
+ WallNotification, WallNotificationActor, WallNotificationComment, WallNotificationPage,
+ WallNotificationPost, WallNotificationType, WallProfileResponse,
};
diff --git a/rust/wall/src/transport.rs b/rust/wall/src/transport.rs
index 8071843831..40f46ca9e3 100644
--- a/rust/wall/src/transport.rs
+++ b/rust/wall/src/transport.rs
@@ -29,7 +29,7 @@ pub struct CreateEntityKeyRequest {
pub header: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusResponse {
pub status: String,
}
@@ -42,7 +42,7 @@ pub struct CreateWallRequest {
pub encrypted_profile: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallKeyResponse {
pub wall_id: String,
@@ -63,7 +63,7 @@ pub struct PresignUploadRequest {
pub wall_id: Option<String>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PresignUploadResponse {
pub url: String,
@@ -73,7 +73,7 @@ pub struct PresignUploadResponse {
pub expires_in: i32,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AssetDownloadResponse {
pub url: String,
@@ -111,7 +111,7 @@ pub struct CreatePostRequest {
pub objects: Vec<PostObjectPayload>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreatePostResponse {
pub post_id: i64,
@@ -123,7 +123,7 @@ pub struct LikePostRequest {
pub like: bool,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LikePostResponse {
pub liked: bool,
}
@@ -134,7 +134,7 @@ pub struct LikeCommentRequest {
pub like: bool,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LikeCommentResponse {
pub liked: bool,
}
@@ -146,12 +146,14 @@ pub struct UpdatePostCaptionRequest {
pub caption_cipher: Option<String>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PostResponse {
pub post_id: i64,
pub wall_id: String,
pub wall_slug: String,
+ #[serde(default)]
+ pub owner_user_id: i64,
pub author: String,
pub encrypted_post_key: String,
#[serde(default)]
@@ -165,7 +167,7 @@ pub struct PostResponse {
pub comments: i64,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PostPage {
pub items: Vec<PostResponse>,
@@ -181,12 +183,14 @@ pub struct CreateCommentRequest {
pub parent_comment_id: Option<i64>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommentResponse {
pub comment_id: i64,
#[serde(default)]
pub author_id: i64,
+ #[serde(default)]
+ pub author_wall_id: String,
pub author: String,
pub comment_cipher: String,
pub created_at: String,
@@ -199,7 +203,7 @@ pub struct CommentResponse {
pub parent_comment_id: Option<i64>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListCommentsResponse {
pub comments: Vec<CommentResponse>,
@@ -207,7 +211,7 @@ pub struct ListCommentsResponse {
pub next_cursor: String,
}
-#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum WallNotificationType {
LikedPost,
@@ -217,7 +221,7 @@ pub enum WallNotificationType {
AddedYouAsFriend,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallNotificationActor {
pub user_id: i64,
@@ -226,7 +230,7 @@ pub struct WallNotificationActor {
pub wall_slug: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallNotificationPost {
pub post_id: i64,
@@ -238,13 +242,15 @@ pub struct WallNotificationPost {
pub objects: Vec<PostObjectPayload>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallNotificationComment {
pub comment_id: i64,
#[serde(default)]
pub author_id: i64,
#[serde(default)]
+ pub author_wall_id: String,
+ #[serde(default)]
pub author: String,
#[serde(default)]
pub comment_cipher: String,
@@ -254,7 +260,7 @@ pub struct WallNotificationComment {
pub parent_comment_id: Option<i64>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallNotification {
pub id: String,
@@ -268,7 +274,7 @@ pub struct WallNotification {
pub comment: Option<WallNotificationComment>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallNotificationPage {
pub items: Vec<WallNotification>,
@@ -305,7 +311,7 @@ pub struct UpdateWallProfileRequest {
pub remove_avatar: bool,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateWallProfileResponse {
pub status: String,
@@ -313,7 +319,7 @@ pub struct UpdateWallProfileResponse {
pub avatar: Option<ProfileAvatarResponse>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallProfileResponse {
pub wall_id: String,
@@ -337,7 +343,7 @@ pub struct RotateWallKeyRequest {
pub encrypted_profile: Option<String>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallKeyVersionResponse {
pub version: i32,
@@ -372,12 +378,18 @@ pub struct AddFriendPayload {
pub requester_key_version: i32,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FriendStatusResponse {
pub status: String,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FriendRelationshipResponse {
+ pub relationship: String,
+}
+
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FriendTargetPayload {
@@ -387,7 +399,7 @@ pub struct FriendTargetPayload {
pub target_wall_id: Option<String>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallFriendResponse {
pub friend_id: i64,
@@ -422,7 +434,7 @@ pub struct RefreshFriendSharesRequest {
pub shares: Vec<ShareUpdatePayload>,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FriendShareResponse {
pub friend: String,
@@ -432,7 +444,24 @@ pub struct FriendShareResponse {
pub key_version: i32,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PostLikerResponse {
+ pub user_id: i64,
+ pub wall_id: String,
+ pub wall_slug: String,
+ pub created_at: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListPostLikersResponse {
+ pub likers: Vec<PostLikerResponse>,
+ #[serde(default)]
+ pub next_cursor: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallLinkStatusResponse {
pub wall_id: String,
@@ -459,7 +488,7 @@ pub struct WallLinkLoginRequest {
pub auth_key: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallLinkLoginResponse {
pub session_token: String,
@@ -472,7 +501,7 @@ pub struct WallLinkLoginResponse {
pub encrypted_wall_key: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdatedCountResponse {
pub updated: usize,
}
@@ -483,7 +512,7 @@ pub struct UpdateWallSlugRequest {
pub wall_slug: String,
}
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WallLookupResponse {
pub wall_id: String,
diff --git a/server/wall/api/friends.go b/server/wall/api/friends.go
index a4fb59bbd5..47a787af69 100644
--- a/server/wall/api/friends.go
+++ b/server/wall/api/friends.go
@@ -35,6 +35,16 @@ func (h *Handlers) ListWallFriends(c *gin.Context) {
respondJSON(c, resp, err)
}
+func (h *Handlers) FriendRelationship(c *gin.Context) {
+ var req models.FriendRelationshipRequest
+ if err := c.ShouldBindQuery(&req); err != nil {
+ respondJSON(c, nil, ente.ErrBadRequest)
+ return
+ }
+ resp, err := h.Module.Friends.Relationship(c, req)
+ respondJSON(c, resp, err)
+}
+
func (h *Handlers) RefreshFriendShares(c *gin.Context) {
var req models.RefreshFriendSharesRequest
if err := c.ShouldBindJSON(&req); err != nil {
diff --git a/server/wall/api/posts.go b/server/wall/api/posts.go
index 14eb3a62fa..dadf1be8a5 100644
--- a/server/wall/api/posts.go
+++ b/server/wall/api/posts.go
@@ -61,6 +61,11 @@ func (h *Handlers) TogglePostLike(c *gin.Context) {
respondJSON(c, resp, err)
}
+func (h *Handlers) ListPostLikers(c *gin.Context) {
+ resp, err := h.Module.Posts.ListLikers(c, c.Param("postID"))
+ respondJSON(c, resp, err)
+}
+
func (h *Handlers) DeletePost(c *gin.Context) {
respondStatus(c, h.Module.Posts.Delete(c, c.Param("postID")))
}
diff --git a/server/wall/api/register.go b/server/wall/api/register.go
index f8396968f1..ff1944d448 100644
--- a/server/wall/api/register.go
+++ b/server/wall/api/register.go
@@ -22,6 +22,7 @@ func Register(privateAPI, publicAPI gin.IRoutes, handlers *Handlers) {
privateAPI.POST("/wall/friends/add", handlers.AddFriend)
privateAPI.POST("/wall/friends/unfriend", handlers.Unfriend)
privateAPI.GET("/wall/friends", handlers.ListWallFriends)
+ privateAPI.GET("/wall/friends/relationship", handlers.FriendRelationship)
privateAPI.POST("/wall/friends/shares/refresh", handlers.RefreshFriendShares)
privateAPI.GET("/wall/friends/shares", handlers.ListFriendShares)
privateAPI.POST("/wall/rotate", handlers.RotateWallKey)
@@ -33,6 +34,7 @@ func Register(privateAPI, publicAPI gin.IRoutes, handlers *Handlers) {
publicAPI.GET("/wall/assets/redirect", handlers.AssetRedirect)
publicAPI.GET("/wall/posts", handlers.ListPosts)
publicAPI.GET("/wall/posts/:postID", handlers.GetPost)
+ publicAPI.GET("/wall/posts/:postID/likes", handlers.ListPostLikers)
publicAPI.GET("/wall/posts/:postID/comments", handlers.ListComments)
publicAPI.GET("/wall/versions", handlers.ListWallKeyVersions)
publicAPI.GET("/wall/public/by-slug/:wallSlug", handlers.LookupWallBySlug)
diff --git a/server/wall/controller/friends.go b/server/wall/controller/friends.go
index 66c10e3b24..5a4cbb4d14 100644
--- a/server/wall/controller/friends.go
+++ b/server/wall/controller/friends.go
@@ -126,6 +126,26 @@ func (c *FriendsController) ListFriends(ctx *gin.Context, req models.ListWallFri
return resp, nil
}
+func (c *FriendsController) Relationship(ctx *gin.Context, req models.FriendRelationshipRequest) (*models.FriendRelationshipResponse, error) {
+ userID, err := c.auth.requireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ targetWallID := strings.TrimSpace(req.TargetWallID)
+ if targetWallID == "" {
+ return nil, ente.NewBadRequestWithMessage("targetWallId is required")
+ }
+ targetWall, err := c.WallsRepo.GetWallByID(ctx.Request.Context(), targetWallID)
+ if err != nil {
+ return nil, err
+ }
+ relationship, err := c.FriendsRepo.GetRelationship(ctx.Request.Context(), userID, targetWall.OwnerID, targetWall.WallID)
+ if err != nil {
+ return nil, err
+ }
+ return &models.FriendRelationshipResponse{Relationship: relationship}, nil
+}
+
func (c *FriendsController) RefreshShares(ctx *gin.Context, req models.RefreshFriendSharesRequest) error {
userID, err := c.auth.requireUser(ctx)
if err != nil {
diff --git a/server/wall/controller/friends_test.go b/server/wall/controller/friends_test.go
new file mode 100644
index 0000000000..baeb5a4919
--- /dev/null
+++ b/server/wall/controller/friends_test.go
@@ -0,0 +1,42 @@
+package controller
+
+import (
+ "context"
+ "testing"
+
+ "github.com/ente-io/museum/wall/models"
+ wallrepo "github.com/ente-io/museum/wall/repo"
+ "github.com/stretchr/testify/require"
+)
+
+func setupFriendsControllerTest(t *testing.T) (*FriendsController, *wallrepo.Module, context.Context) {
+ t.Helper()
+ _, repos, ctx := setupPostsControllerTest(t)
+ return NewModule(repos, nil).Friends, repos, ctx
+}
+
+func TestFriendRelationshipReportsSelfFriendAndEmpty(t *testing.T) {
+ friends, repos, ctx := setupFriendsControllerTest(t)
+ aliceID := insertWallControllerUser(t, repos, "[email protected]", "alice-public")
+ bobID := insertWallControllerUser(t, repos, "[email protected]", "bob-public")
+ devID := insertWallControllerUser(t, repos, "[email protected]", "dev-public")
+ aliceWall, err := repos.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")
+ require.NoError(t, err)
+ bobWall, err := repos.Walls.CreateWall(ctx, bobID, "bob", "bob-wall-key", "bob-profile")
+ require.NoError(t, err)
+ devWall, err := repos.Walls.CreateWall(ctx, devID, "dev", "dev-wall-key", "dev-profile")
+ require.NoError(t, err)
+ require.NoError(t, repos.Friends.AddFriend(ctx, aliceID, aliceWall.WallID, bobWall.WallID, "bob-share-key", bobWall.CurrentVersion, "alice-share-key", aliceWall.CurrentVersion))
+
+ resp, err := friends.Relationship(newWallControllerContext(aliceID), models.FriendRelationshipRequest{TargetWallID: aliceWall.WallID})
+ require.NoError(t, err)
+ require.Equal(t, "self", resp.Relationship)
+
+ resp, err = friends.Relationship(newWallControllerContext(aliceID), models.FriendRelationshipRequest{TargetWallID: bobWall.WallID})
+ require.NoError(t, err)
+ require.Equal(t, "friend", resp.Relationship)
+
+ resp, err = friends.Relationship(newWallControllerContext(aliceID), models.FriendRelationshipRequest{TargetWallID: devWall.WallID})
+ require.NoError(t, err)
+ require.Empty(t, resp.Relationship)
+}
diff --git a/server/wall/controller/helpers.go b/server/wall/controller/helpers.go
index 8eb9089c8a..7a05ec4562 100644
--- a/server/wall/controller/helpers.go
+++ b/server/wall/controller/helpers.go
@@ -92,6 +92,7 @@ func toCommentResponse(comment wallrepo.WallCommentRecord) models.CommentRespons
resp := models.CommentResponse{
CommentID: comment.CommentID,
AuthorID: comment.AuthorID,
+ AuthorWallID: comment.AuthorWallID,
Author: comment.Author,
CommentCipher: comment.CommentCipher,
CreatedAt: formatMicros(comment.CreatedAt),
diff --git a/server/wall/controller/notifications.go b/server/wall/controller/notifications.go
index 083d223c3c..be8f3fc81f 100644
--- a/server/wall/controller/notifications.go
+++ b/server/wall/controller/notifications.go
@@ -83,6 +83,9 @@ func toNotificationResponse(notification repo.WallNotificationRecord) models.Not
if notification.CommentAuthorID.Valid {
comment.AuthorID = notification.CommentAuthorID.Int64
}
+ if notification.CommentAuthorWallID.Valid {
+ comment.AuthorWallID = notification.CommentAuthorWallID.String
+ }
if notification.CommentAuthor.Valid {
comment.Author = notification.CommentAuthor.String
}
diff --git a/server/wall/controller/posts.go b/server/wall/controller/posts.go
index 027f9ec87f..186584dd18 100644
--- a/server/wall/controller/posts.go
+++ b/server/wall/controller/posts.go
@@ -211,6 +211,47 @@ func (c *PostsController) ToggleLike(ctx *gin.Context, postID string, req models
return &models.LikePostResponse{Liked: req.Like}, nil
}
+func (c *PostsController) ListLikers(ctx *gin.Context, postID string) (*models.ListPostLikersResponse, error) {
+ id, err := strconv.ParseInt(strings.TrimSpace(postID), 10, 64)
+ if err != nil || id <= 0 {
+ return nil, ente.NewBadRequestWithMessage("invalid postID")
+ }
+ viewer, err := c.auth.resolveViewer(ctx)
+ if err != nil {
+ return nil, err
+ }
+ viewerID := int64(0)
+ if viewer != nil {
+ viewerID = viewer.UserID
+ }
+ post, err := c.PostsRepo.GetPost(ctx.Request.Context(), id, viewerID)
+ 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(), viewer, wall); err != nil {
+ return nil, err
+ }
+ limit, _ := strconv.Atoi(strings.TrimSpace(ctx.Query("limit")))
+ likers, nextCursor, err := c.PostsRepo.ListPostLikers(ctx.Request.Context(), id, ctx.Query("cursor"), limit)
+ if err != nil {
+ return nil, err
+ }
+ resp := make([]models.PostLikerResponse, 0, len(likers))
+ for _, liker := range likers {
+ resp = append(resp, models.PostLikerResponse{
+ UserID: liker.UserID,
+ WallID: liker.WallID,
+ WallSlug: liker.WallSlug,
+ CreatedAt: formatMicros(liker.CreatedAt),
+ })
+ }
+ return &models.ListPostLikersResponse{Likers: resp, NextCursor: nextCursor}, nil
+}
+
func (c *PostsController) Delete(ctx *gin.Context, postID string) error {
userID, err := c.auth.requireUser(ctx)
if err != nil {
diff --git a/server/wall/models/models.go b/server/wall/models/models.go
index 1d616c2a4c..3c768da8e7 100644
--- a/server/wall/models/models.go
+++ b/server/wall/models/models.go
@@ -35,6 +35,10 @@ type ListWallFriendsRequest struct {
WallID string `form:"wallId"`
}
+type FriendRelationshipRequest struct {
+ TargetWallID string `form:"targetWallId" binding:"required"`
+}
+
type WallKeyResponse struct {
WallID string `json:"wallId"`
WallSlug string `json:"wallSlug"`
@@ -131,6 +135,10 @@ type FriendStatusResponse struct {
Status string `json:"status"`
}
+type FriendRelationshipResponse struct {
+ Relationship string `json:"relationship"`
+}
+
type UpdateWallProfileRequest struct {
WallID string `json:"wallId"`
EncryptedProfile string `json:"encryptedProfile"`
@@ -226,6 +234,18 @@ type LikePostResponse struct {
Liked bool `json:"liked"`
}
+type ListPostLikersResponse struct {
+ Likers []PostLikerResponse `json:"likers"`
+ NextCursor string `json:"nextCursor,omitempty"`
+}
+
+type PostLikerResponse struct {
+ UserID int64 `json:"userId"`
+ WallID string `json:"wallId"`
+ WallSlug string `json:"wallSlug"`
+ CreatedAt string `json:"createdAt"`
+}
+
type LikeCommentRequest struct {
Like bool `json:"like"`
}
@@ -278,6 +298,7 @@ type FeedPage struct {
type CommentResponse struct {
CommentID int64 `json:"commentId"`
AuthorID int64 `json:"authorId"`
+ AuthorWallID string `json:"authorWallId"`
Author string `json:"author"`
CommentCipher string `json:"commentCipher"`
CreatedAt string `json:"createdAt"`
@@ -316,6 +337,7 @@ type NotificationPostResponse struct {
type NotificationCommentResponse struct {
CommentID int64 `json:"commentId"`
AuthorID int64 `json:"authorId,omitempty"`
+ AuthorWallID string `json:"authorWallId,omitempty"`
Author string `json:"author,omitempty"`
CommentCipher string `json:"commentCipher,omitempty"`
CreatedAt string `json:"createdAt,omitempty"`
diff --git a/server/wall/repo/module.go b/server/wall/repo/module.go
index 74c3ab26e8..c6dd453270 100644
--- a/server/wall/repo/module.go
+++ b/server/wall/repo/module.go
@@ -108,6 +108,7 @@ type WallCommentRecord struct {
CommentID int64
PostID int64
AuthorID int64
+ AuthorWallID string
Author string
CommentCipher string
ParentCommentID sql.NullInt64
@@ -117,6 +118,13 @@ type WallCommentRecord struct {
ViewerCanDelete bool
}
+type WallPostLikerRecord struct {
+ UserID int64
+ WallID string
+ WallSlug string
+ CreatedAt int64
+}
+
type WallShareRecord struct {
WallID string
FriendID int64
@@ -197,6 +205,7 @@ type WallNotificationRecord struct {
CommentID sql.NullInt64
ParentCommentID sql.NullInt64
CommentAuthorID sql.NullInt64
+ CommentAuthorWallID sql.NullString
CommentAuthor sql.NullString
CommentCipher sql.NullString
CommentCreatedAt sql.NullInt64
diff --git a/server/wall/repo/module_test.go b/server/wall/repo/module_test.go
index ad6e1cc709..938f225fb0 100644
--- a/server/wall/repo/module_test.go
+++ b/server/wall/repo/module_test.go
@@ -169,6 +169,7 @@ func TestWallModuleLifecycle(t *testing.T) {
require.Len(t, comments, 2)
require.Empty(t, nextCommentsCursor)
require.Equal(t, comment.CommentID, comments[1].CommentID)
+ require.Equal(t, bobWall.WallID, comments[1].AuthorWallID)
require.Equal(t, comment.CommentID, comments[0].ParentCommentID.Int64)
assets, err := module.Posts.ListAssetsByPostIDs(ctx, []int64{postID})
@@ -718,7 +719,9 @@ func TestNotificationsIncludeWallSocialEvents(t *testing.T) {
require.Len(t, page, 3)
require.Equal(t, "addedYouAsFriend", page[0].Type)
require.Equal(t, "likedComment", page[1].Type)
+ require.Equal(t, aliceWall.WallID, page[1].CommentAuthorWallID.String)
require.Equal(t, "repliedToComment", page[2].Type)
+ require.Equal(t, bobWall.WallID, page[2].CommentAuthorWallID.String)
require.NotEmpty(t, nextCursor)
page, nextCursor, err = module.Notifications.List(ctx, aliceID, nextCursor, 3)
@@ -760,6 +763,41 @@ func TestListCommentsPaginates(t *testing.T) {
require.Empty(t, nextCursor)
}
+func TestListPostLikersPaginates(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")
+ devID := insertWallUser(t, module, "[email protected]", "dev-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)
+ devWall, err := module.Walls.CreateWall(ctx, devID, "dev", "dev-wall-key", "dev-profile")
+ require.NoError(t, err)
+ postID, err := module.Posts.CreatePost(ctx, aliceID, aliceWall.WallID, "post-key", nil, aliceWall.CurrentVersion, nil)
+ require.NoError(t, err)
+ require.NoError(t, module.Posts.SetLike(ctx, postID, bobID, true))
+ require.NoError(t, module.Posts.SetLike(ctx, postID, devID, true))
+ setPostLikeCreatedAt(t, module, 3000, postID, bobID)
+ setPostLikeCreatedAt(t, module, 2000, postID, devID)
+
+ page, nextCursor, err := module.Posts.ListPostLikers(ctx, postID, "", 1)
+ require.NoError(t, err)
+ require.Len(t, page, 1)
+ require.Equal(t, bobID, page[0].UserID)
+ require.Equal(t, bobWall.WallID, page[0].WallID)
+ require.Equal(t, "3000:"+strconv.FormatInt(bobID, 10), nextCursor)
+
+ page, nextCursor, err = module.Posts.ListPostLikers(ctx, postID, nextCursor, 1)
+ require.NoError(t, err)
+ require.Len(t, page, 1)
+ require.Equal(t, devID, page[0].UserID)
+ require.Equal(t, devWall.WallID, page[0].WallID)
+ require.Empty(t, nextCursor)
+}
+
func TestDeleteCommentRequiresPostAndAuthorMatch(t *testing.T) {
ctx := context.Background()
module := newWallTestModule(t)
diff --git a/server/wall/repo/notifications.go b/server/wall/repo/notifications.go
index 9a87eb53fe..d0724542d9 100644
--- a/server/wall/repo/notifications.go
+++ b/server/wall/repo/notifications.go
@@ -33,6 +33,7 @@ const wallNotificationRows = `
NULL::bigint AS comment_id,
NULL::bigint AS parent_comment_id,
NULL::bigint AS comment_author_id,
+ NULL::text AS comment_author_wall_id,
NULL::text AS comment_author,
NULL::text AS comment_cipher,
NULL::bigint AS comment_created_at
@@ -78,6 +79,7 @@ const wallNotificationRows = `
c.comment_id,
NULL::bigint AS parent_comment_id,
c.author_id AS comment_author_id,
+ actor_wall.wall_id AS comment_author_wall_id,
actor_wall.wall_slug AS comment_author,
c.comment_cipher,
c.created_at AS comment_created_at
@@ -125,6 +127,7 @@ const wallNotificationRows = `
c.comment_id,
c.parent_comment_id,
c.author_id AS comment_author_id,
+ actor_wall.wall_id AS comment_author_wall_id,
actor_wall.wall_slug AS comment_author,
c.comment_cipher,
c.created_at AS comment_created_at
@@ -173,6 +176,7 @@ const wallNotificationRows = `
c.comment_id,
c.parent_comment_id,
c.author_id AS comment_author_id,
+ comment_author_wall.wall_id AS comment_author_wall_id,
comment_author_wall.wall_slug AS comment_author,
c.comment_cipher,
c.created_at AS comment_created_at
@@ -221,6 +225,7 @@ const wallNotificationRows = `
NULL::bigint AS comment_id,
NULL::bigint AS parent_comment_id,
NULL::bigint AS comment_author_id,
+ NULL::text AS comment_author_wall_id,
NULL::text AS comment_author,
NULL::text AS comment_cipher,
NULL::bigint AS comment_created_at
@@ -248,7 +253,7 @@ func (r *NotificationsRepository) List(ctx context.Context, userID int64, cursor
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
+ n.comment_id, n.parent_comment_id, n.comment_author_id, n.comment_author_wall_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
@@ -304,6 +309,7 @@ func scanNotificationRecord(scanner interface{ Scan(dest ...any) error }) (*Wall
&rec.CommentID,
&rec.ParentCommentID,
&rec.CommentAuthorID,
+ &rec.CommentAuthorWallID,
&rec.CommentAuthor,
&rec.CommentCipher,
&rec.CommentCreatedAt,
diff --git a/server/wall/repo/posts.go b/server/wall/repo/posts.go
index 8e66563e29..606088b8cf 100644
--- a/server/wall/repo/posts.go
+++ b/server/wall/repo/posts.go
@@ -261,6 +261,47 @@ func (r *PostsRepository) SetLike(ctx context.Context, postID, userID int64, lik
return stacktrace.Propagate(err, "")
}
+func (r *PostsRepository) ListPostLikers(ctx context.Context, postID int64, cursor string, limit int) ([]WallPostLikerRecord, string, error) {
+ limit = optionalInt(limit, 50)
+ if limit > 100 {
+ limit = 100
+ }
+ args := []any{postID}
+ query := `
+ SELECT pl.user_id, liker_wall.wall_id, liker_wall.wall_slug, pl.created_at
+ FROM wall_post_likes pl
+ JOIN walls liker_wall ON liker_wall.owner_id = pl.user_id
+ WHERE pl.post_id = $1`
+ if cursorCreatedAt, cursorUserID, ok := parsePostLikerCursor(cursor); ok {
+ args = append(args, cursorCreatedAt, cursorUserID)
+ query += ` AND (pl.created_at, pl.user_id) < ($2, $3)`
+ }
+ args = append(args, limit+1)
+ query += ` ORDER BY pl.created_at DESC, pl.user_id DESC LIMIT $` + strconv.Itoa(len(args))
+ rows, err := r.DB.QueryContext(ctx, query, args...)
+ if err != nil {
+ return nil, "", stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+ out := make([]WallPostLikerRecord, 0, limit+1)
+ for rows.Next() {
+ var rec WallPostLikerRecord
+ if err := rows.Scan(&rec.UserID, &rec.WallID, &rec.WallSlug, &rec.CreatedAt); err != nil {
+ return nil, "", stacktrace.Propagate(err, "")
+ }
+ out = append(out, rec)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, "", stacktrace.Propagate(err, "")
+ }
+ nextCursor := ""
+ if len(out) > limit {
+ nextCursor = formatPostLikerCursor(out[limit-1])
+ out = out[:limit]
+ }
+ return out, nextCursor, nil
+}
+
func (r *PostsRepository) UpdateCaption(ctx context.Context, postID, ownerID int64, captionCipher *string) error {
caption := ""
if captionCipher != nil {
@@ -294,7 +335,7 @@ func (r *PostsRepository) CreateComment(ctx context.Context, postID, authorID in
func (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 c.comment_id, c.post_id, c.author_id, author_wall.wall_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_delete
@@ -311,7 +352,7 @@ func (r *PostsRepository) ListComments(ctx context.Context, postID, viewerID int
}
args := []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,
+ SELECT c.comment_id, c.post_id, c.author_id, author_wall.wall_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_delete
@@ -415,9 +456,29 @@ func formatPostCursor(post WallPostRecord) string {
return strconv.FormatInt(post.CreatedAt, 10) + ":" + strconv.FormatInt(post.PostID, 10)
}
+func parsePostLikerCursor(cursor string) (int64, int64, bool) {
+ createdAtText, userIDText, ok := strings.Cut(strings.TrimSpace(cursor), ":")
+ if !ok {
+ return 0, 0, false
+ }
+ createdAt, err := strconv.ParseInt(createdAtText, 10, 64)
+ if err != nil || createdAt <= 0 {
+ return 0, 0, false
+ }
+ userID, err := strconv.ParseInt(userIDText, 10, 64)
+ if err != nil || userID <= 0 {
+ return 0, 0, false
+ }
+ return createdAt, userID, true
+}
+
+func formatPostLikerCursor(liker WallPostLikerRecord) string {
+ return strconv.FormatInt(liker.CreatedAt, 10) + ":" + strconv.FormatInt(liker.UserID, 10)
+}
+
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.Likes, &rec.ViewerLiked, &rec.ViewerCanDelete); err != nil {
+ if err := scanner.Scan(&rec.CommentID, &rec.PostID, &rec.AuthorID, &rec.AuthorWallID, &rec.Author, &rec.CommentCipher, &rec.ParentCommentID, &rec.CreatedAt, &rec.Likes, &rec.ViewerLiked, &rec.ViewerCanDelete); err != nil {
return nil, stacktrace.Propagate(err, "")
}
return &rec, nil
diff --git a/web/packages/wasm/Cargo.lock b/web/packages/wasm/Cargo.lock
index ccb35e3bc9..be52bc7f8d 100644
--- a/web/packages/wasm/Cargo.lock
+++ b/web/packages/wasm/Cargo.lock
@@ -348,12 +348,25 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "ente-wall"
+version = "0.0.1"
+dependencies = [
+ "base64",
+ "ente-core",
+ "serde",
+ "thiserror",
+ "url",
+ "urlencoding",
+]
+
[[package]]
name = "ente-wasm"
version = "0.0.1"
dependencies = [
"ente-contacts",
"ente-core",
+ "ente-wall",
"js-sys",
"md-5",
"serde",
@@ -1685,6 +1698,12 @@ dependencies = [
"serde",
]
+[[package]]
+name = "urlencoding"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
+
[[package]]
name = "utf8_iter"
version = "1.0.4"
diff --git a/web/packages/wasm/Cargo.toml b/web/packages/wasm/Cargo.toml
index edb71e239b..e379f89123 100644
--- a/web/packages/wasm/Cargo.toml
+++ b/web/packages/wasm/Cargo.toml
@@ -9,6 +9,7 @@ crate-type = ["cdylib"]
[dependencies]
ente-contacts = { path = "../../../rust/contacts" }
ente-core = { path = "../../../rust/core", features = ["srp"] }
+ente-wall = { path = "../../../rust/wall" }
md-5 = "0.10"
js-sys = "0.3"
serde = { version = "1", features = ["derive"] }
diff --git a/web/packages/wasm/src/lib.rs b/web/packages/wasm/src/lib.rs
index 3ba0ce3833..5786b367df 100644
--- a/web/packages/wasm/src/lib.rs
+++ b/web/packages/wasm/src/lib.rs
@@ -5,3 +5,4 @@ mod contacts;
mod crypto;
mod http;
mod urls;
+mod wall;
diff --git a/web/packages/wasm/src/wall.rs b/web/packages/wasm/src/wall.rs
new file mode 100644
index 0000000000..066524d370
--- /dev/null
+++ b/web/packages/wasm/src/wall.rs
@@ -0,0 +1,950 @@
+//! WASM bindings for wall/social flows.
+
+use ente_core::http::Error as HttpError;
+use ente_wall::{
+ AccountWallCtx, AuthKeyAttributes, CommentResponse, CreatedWall, CreatedWallLink,
+ DecryptedPost, DecryptedWallProfile, OpenAccountWallCtxInput, OpenWallLinkCtxInput,
+ PostResponse, PrivateKeySource, ProfileAvatarResponse, WallError as CoreWallError, WallLinkCtx,
+ WallNotification, WallNotificationComment, WallNotificationPost,
+ crypto::{decode_b64, encode_b64},
+};
+use serde::{Deserialize, Serialize};
+use serde_wasm_bindgen as swb;
+use wasm_bindgen::prelude::*;
+
+/// Wall client error.
+#[wasm_bindgen]
+pub struct WasmWallError {
+ code: String,
+ message: String,
+ status: Option<u16>,
+}
+
+#[wasm_bindgen]
+impl WasmWallError {
+ /// Machine-readable error code.
+ #[wasm_bindgen(getter)]
+ pub fn code(&self) -> String {
+ self.code.clone()
+ }
+
+ /// Human-readable error message.
+ #[wasm_bindgen(getter)]
+ pub fn message(&self) -> String {
+ self.message.clone()
+ }
+
+ /// HTTP status code when the error came from an HTTP response.
+ #[wasm_bindgen(getter)]
+ pub fn status(&self) -> Option<u16> {
+ self.status
+ }
+}
+
+impl From<CoreWallError> for WasmWallError {
+ fn from(e: CoreWallError) -> Self {
+ let (code, status) = match &e {
+ CoreWallError::Http(HttpError::Http { status, .. }) => ("http", Some(*status)),
+ CoreWallError::Http(HttpError::InvalidUrl(_)) => ("invalid_url", None),
+ CoreWallError::Http(HttpError::Network(_)) => ("network", None),
+ CoreWallError::Http(HttpError::Parse(_)) => ("parse", None),
+ CoreWallError::Crypto(_) => ("crypto", None),
+ CoreWallError::Auth(_) => ("auth", None),
+ CoreWallError::Base64(_) => ("base64", None),
+ CoreWallError::InvalidInput(_) => ("invalid_input", None),
+ CoreWallError::MissingPrivateKey => ("missing_private_key", None),
+ CoreWallError::MissingEncryptedWallKey => ("missing_encrypted_wall_key", None),
+ CoreWallError::EntityKeyConflict => ("entity_key_conflict", None),
+ };
+ Self {
+ code: code.to_owned(),
+ message: e.to_string(),
+ status,
+ }
+ }
+}
+
+impl From<swb::Error> for WasmWallError {
+ fn from(e: swb::Error) -> Self {
+ Self {
+ code: "serde".to_owned(),
+ message: e.to_string(),
+ status: None,
+ }
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct OpenAccountWallCtxJsInput {
+ base_url: String,
+ auth_token: String,
+ master_key_b64: String,
+ public_key_b64: String,
+ private_key_b64: Option<String>,
+ key_attributes: Option<AuthKeyAttributes>,
+ auth_key_attributes: Option<AuthKeyAttributes>,
+ user_id: Option<i64>,
+ user_agent: Option<String>,
+ client_package: Option<String>,
+ client_version: Option<String>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct OpenWallLinkCtxJsInput {
+ base_url: String,
+ wall_username: String,
+ access_key: String,
+ user_agent: Option<String>,
+ client_package: Option<String>,
+ client_version: Option<String>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct CreatedWallJs {
+ wall_id: String,
+ wall_slug: String,
+ key_version: i32,
+ wall_key_b64: String,
+ encrypted_wall_key: String,
+ encrypted_profile: String,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct CreatedWallLinkJs {
+ access_key: String,
+ wall_username: String,
+ wall_id: String,
+ wall_slug: String,
+ key_version: i32,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct WallProfileJs {
+ wall_id: String,
+ wall_slug: String,
+ version: i32,
+ profile: String,
+ avatar: Option<ProfileAvatarResponse>,
+ updated_at: Option<String>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PostJs {
+ post_id: i64,
+ wall_id: String,
+ wall_slug: String,
+ owner_user_id: i64,
+ author: String,
+ caption: Option<String>,
+ key_version: i32,
+ objects: Vec<ente_wall::PostObjectPayload>,
+ created_at: String,
+ likes: i64,
+ viewer_liked: bool,
+ comments: i64,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PostPageJs {
+ items: Vec<PostJs>,
+ next_cursor: String,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct CommentJs {
+ comment_id: i64,
+ author_id: i64,
+ author_wall_id: String,
+ author: String,
+ comment: String,
+ created_at: String,
+ likes: i64,
+ viewer_liked: bool,
+ viewer_can_delete: bool,
+ parent_comment_id: Option<i64>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct CommentPageJs {
+ comments: Vec<CommentJs>,
+ next_cursor: String,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct NotificationCommentJs {
+ comment_id: i64,
+ author_id: i64,
+ author_wall_id: String,
+ author: String,
+ comment: Option<String>,
+ created_at: String,
+ parent_comment_id: Option<i64>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct NotificationJs {
+ id: String,
+ #[serde(rename = "type")]
+ notification_type: ente_wall::WallNotificationType,
+ created_at: String,
+ actor: ente_wall::WallNotificationActor,
+ post: Option<WallNotificationPost>,
+ comment: Option<NotificationCommentJs>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct NotificationPageJs {
+ items: Vec<NotificationJs>,
+ next_cursor: String,
+}
+
+fn decode_b64_field(value: &str) -> Result<Vec<u8>, WasmWallError> {
+ decode_b64(value)
+ .map_err(CoreWallError::from)
+ .map_err(Into::into)
+}
+
+fn utf8_field(bytes: Vec<u8>, field: &str) -> Result<String, WasmWallError> {
+ String::from_utf8(bytes)
+ .map_err(|err| CoreWallError::InvalidInput(format!("invalid {field} utf8: {err}")).into())
+}
+
+fn optional_utf8_field(
+ bytes: Option<Vec<u8>>,
+ field: &str,
+) -> Result<Option<String>, WasmWallError> {
+ bytes.map(|value| utf8_field(value, field)).transpose()
+}
+
+fn created_wall_to_js(value: CreatedWall) -> CreatedWallJs {
+ CreatedWallJs {
+ wall_id: value.wall_id,
+ wall_slug: value.wall_slug,
+ key_version: value.key_version,
+ wall_key_b64: encode_b64(&value.wall_key),
+ encrypted_wall_key: value.encrypted_wall_key,
+ encrypted_profile: value.encrypted_profile,
+ }
+}
+
+fn created_link_to_js(value: CreatedWallLink) -> CreatedWallLinkJs {
+ CreatedWallLinkJs {
+ access_key: value.access_key,
+ wall_username: value.wall_username,
+ wall_id: value.wall_id,
+ wall_slug: value.wall_slug,
+ key_version: value.key_version,
+ }
+}
+
+fn profile_to_js(value: DecryptedWallProfile) -> Result<WallProfileJs, WasmWallError> {
+ Ok(WallProfileJs {
+ wall_id: value.wall_id,
+ wall_slug: value.wall_slug,
+ version: value.version,
+ profile: utf8_field(value.profile, "profile")?,
+ avatar: value.avatar,
+ updated_at: value.updated_at,
+ })
+}
+
+fn post_to_js(post: PostResponse, decrypted: DecryptedPost) -> Result<PostJs, WasmWallError> {
+ Ok(PostJs {
+ post_id: post.post_id,
+ wall_id: post.wall_id,
+ wall_slug: post.wall_slug,
+ owner_user_id: post.owner_user_id,
+ author: post.author,
+ caption: optional_utf8_field(decrypted.caption_plaintext, "caption")?,
+ key_version: post.key_version,
+ objects: post.objects,
+ created_at: post.created_at,
+ likes: post.likes,
+ viewer_liked: post.viewer_liked,
+ comments: post.comments,
+ })
+}
+
+fn comment_to_js(
+ comment: CommentResponse,
+ decrypted: ente_wall::DecryptedComment,
+) -> Result<CommentJs, WasmWallError> {
+ Ok(CommentJs {
+ comment_id: comment.comment_id,
+ author_id: comment.author_id,
+ author_wall_id: comment.author_wall_id,
+ author: comment.author,
+ comment: utf8_field(decrypted.plaintext, "comment")?,
+ created_at: comment.created_at,
+ likes: comment.likes,
+ viewer_liked: comment.viewer_liked,
+ viewer_can_delete: comment.viewer_can_delete,
+ parent_comment_id: comment.parent_comment_id,
+ })
+}
+
+async fn account_post_page_to_js(
+ ctx: &AccountWallCtx,
+ page: ente_wall::PostPage,
+) -> Result<PostPageJs, WasmWallError> {
+ let mut items = Vec::with_capacity(page.items.len());
+ for post in page.items {
+ let decrypted = ctx.decrypt_post_for_wall(&post.wall_id, &post).await?;
+ items.push(post_to_js(post, decrypted)?);
+ }
+ Ok(PostPageJs {
+ items,
+ next_cursor: page.next_cursor,
+ })
+}
+
+async fn link_post_page_to_js(
+ ctx: &WallLinkCtx,
+ page: ente_wall::PostPage,
+) -> Result<PostPageJs, WasmWallError> {
+ let mut items = Vec::with_capacity(page.items.len());
+ for post in page.items {
+ let decrypted = ctx.decrypt_post(&post).await?;
+ items.push(post_to_js(post, decrypted)?);
+ }
+ Ok(PostPageJs {
+ items,
+ next_cursor: page.next_cursor,
+ })
+}
+
+async fn account_comment_page_to_js(
+ ctx: &AccountWallCtx,
+ post_id: i64,
+ limit: Option<i32>,
+ cursor: Option<i64>,
+) -> Result<CommentPageJs, WasmWallError> {
+ let post = ctx.get_post(post_id).await?;
+ let decrypted_post = ctx.decrypt_post_for_wall(&post.wall_id, &post).await?;
+ let page = ctx.list_comments(post_id, limit, cursor).await?;
+ let mut comments = Vec::with_capacity(page.comments.len());
+ for comment in page.comments {
+ let decrypted = ctx.decrypt_comment(&decrypted_post.post_key, &comment)?;
+ comments.push(comment_to_js(comment, decrypted)?);
+ }
+ Ok(CommentPageJs {
+ comments,
+ next_cursor: page.next_cursor,
+ })
+}
+
+async fn link_comment_page_to_js(
+ ctx: &WallLinkCtx,
+ post_id: i64,
+ limit: Option<i32>,
+ cursor: Option<i64>,
+) -> Result<CommentPageJs, WasmWallError> {
+ let post = ctx.get_post(post_id).await?;
+ let decrypted_post = ctx.decrypt_post(&post).await?;
+ let page = ctx.list_comments(post_id, limit, cursor).await?;
+ let mut comments = Vec::with_capacity(page.comments.len());
+ for comment in page.comments {
+ let decrypted = ctx.decrypt_comment(&decrypted_post.post_key, &comment)?;
+ comments.push(comment_to_js(comment, decrypted)?);
+ }
+ Ok(CommentPageJs {
+ comments,
+ next_cursor: page.next_cursor,
+ })
+}
+
+async fn notification_to_js(
+ ctx: &AccountWallCtx,
+ notification: WallNotification,
+) -> Result<NotificationJs, WasmWallError> {
+ let comment = match notification.comment {
+ Some(comment) => {
+ Some(notification_comment_to_js(ctx, notification.post.as_ref(), comment).await?)
+ }
+ None => None,
+ };
+ Ok(NotificationJs {
+ id: notification.id,
+ notification_type: notification.notification_type,
+ created_at: notification.created_at,
+ actor: notification.actor,
+ post: notification.post,
+ comment,
+ })
+}
+
+async fn notification_comment_to_js(
+ ctx: &AccountWallCtx,
+ post: Option<&WallNotificationPost>,
+ comment: WallNotificationComment,
+) -> Result<NotificationCommentJs, WasmWallError> {
+ let plaintext = if comment.comment_cipher.trim().is_empty() {
+ None
+ } else if let Some(post) = post {
+ let post = ctx.get_post(post.post_id).await?;
+ let decrypted_post = ctx.decrypt_post_for_wall(&post.wall_id, &post).await?;
+ let comment_response = CommentResponse {
+ comment_id: comment.comment_id,
+ author_id: comment.author_id,
+ author_wall_id: comment.author_wall_id.clone(),
+ author: comment.author.clone(),
+ comment_cipher: comment.comment_cipher.clone(),
+ created_at: comment.created_at.clone(),
+ likes: 0,
+ viewer_liked: false,
+ viewer_can_delete: false,
+ parent_comment_id: comment.parent_comment_id,
+ };
+ Some(utf8_field(
+ ctx.decrypt_comment(&decrypted_post.post_key, &comment_response)?
+ .plaintext,
+ "comment",
+ )?)
+ } else {
+ None
+ };
+ Ok(NotificationCommentJs {
+ comment_id: comment.comment_id,
+ author_id: comment.author_id,
+ author_wall_id: comment.author_wall_id,
+ author: comment.author,
+ comment: plaintext,
+ created_at: comment.created_at,
+ parent_comment_id: comment.parent_comment_id,
+ })
+}
+
+/// Open an authenticated wall context for web.
+#[wasm_bindgen]
+pub async fn wall_open_account_ctx(input: JsValue) -> Result<WallAccountCtxHandle, WasmWallError> {
+ let input: OpenAccountWallCtxJsInput = swb::from_value(input)?;
+ let master_key = decode_b64_field(&input.master_key_b64)?;
+ let public_key = decode_b64_field(&input.public_key_b64)?;
+ let private_key_source = if let Some(private_key_b64) = input.private_key_b64.as_deref() {
+ PrivateKeySource::Plain(decode_b64_field(private_key_b64)?)
+ } else if let Some(attrs) = input.key_attributes.or(input.auth_key_attributes) {
+ PrivateKeySource::EncryptedKeyAttributes(attrs)
+ } else {
+ return Err(CoreWallError::MissingPrivateKey.into());
+ };
+ let ctx = AccountWallCtx::open(OpenAccountWallCtxInput {
+ base_url: input.base_url.clone(),
+ auth_token: input.auth_token,
+ master_key,
+ public_key,
+ private_key_source,
+ user_id: input.user_id,
+ user_agent: input.user_agent.clone(),
+ client_package: input.client_package.clone(),
+ client_version: input.client_version.clone(),
+ })?;
+ Ok(WallAccountCtxHandle {
+ inner: ctx,
+ base_url: input.base_url,
+ user_agent: input.user_agent,
+ client_package: input.client_package,
+ client_version: input.client_version,
+ })
+}
+
+/// Open a public wall link context for web.
+#[wasm_bindgen]
+pub async fn wall_open_link_ctx(input: JsValue) -> Result<WallLinkCtxHandle, WasmWallError> {
+ let input: OpenWallLinkCtxJsInput = swb::from_value(input)?;
+ let ctx = WallLinkCtx::open(OpenWallLinkCtxInput {
+ base_url: input.base_url,
+ wall_username: input.wall_username,
+ access_key: input.access_key,
+ user_agent: input.user_agent,
+ client_package: input.client_package,
+ client_version: input.client_version,
+ })
+ .await?;
+ Ok(WallLinkCtxHandle { inner: ctx })
+}
+
+/// Handle to an authenticated wall context.
+#[wasm_bindgen]
+pub struct WallAccountCtxHandle {
+ inner: AccountWallCtx,
+ base_url: String,
+ user_agent: Option<String>,
+ client_package: Option<String>,
+ client_version: Option<String>,
+}
+
+#[wasm_bindgen]
+impl WallAccountCtxHandle {
+ /// Create a wall with an encrypted JSON profile payload.
+ pub async fn create_wall(
+ &self,
+ wall_slug: String,
+ profile: String,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&created_wall_to_js(
+ self.inner
+ .create_wall(&wall_slug, profile.as_bytes())
+ .await?,
+ ))
+ .map_err(Into::into)
+ }
+
+ /// List walls owned by the current account.
+ pub async fn list_owned_walls(&self) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.list_owned_walls().await?).map_err(Into::into)
+ }
+
+ /// Fetch and decrypt a wall profile.
+ pub async fn get_wall_profile(&self, wall_id: String) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&profile_to_js(
+ self.inner
+ .get_wall_profile_decrypted(&wall_id, None)
+ .await?,
+ )?)
+ .map_err(Into::into)
+ }
+
+ /// Update a wall's encrypted JSON profile payload.
+ pub async fn update_wall_profile(
+ &self,
+ wall_id: String,
+ profile: String,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(
+ &self
+ .inner
+ .update_wall_profile(&wall_id, profile.as_bytes(), None, false)
+ .await?,
+ )
+ .map_err(Into::into)
+ }
+
+ /// Update a wall profile and replace its encrypted avatar asset.
+ pub async fn update_wall_profile_with_avatar(
+ &self,
+ wall_id: String,
+ profile: String,
+ avatar_bytes: Vec<u8>,
+ ) -> Result<JsValue, WasmWallError> {
+ let wall_key = self
+ .inner
+ .resolve_owned_wall_key(&wall_id)
+ .await?
+ .ok_or_else(|| {
+ CoreWallError::InvalidInput(format!("wall {wall_id} is not owned by the account"))
+ })?;
+ let avatar = self
+ .inner
+ .upload_avatar(&wall_id, &wall_key, &avatar_bytes)
+ .await?;
+ swb::to_value(
+ &self
+ .inner
+ .update_wall_profile(&wall_id, profile.as_bytes(), Some(avatar), false)
+ .await?,
+ )
+ .map_err(Into::into)
+ }
+
+ /// Update a wall's slug.
+ pub async fn update_wall_slug(
+ &self,
+ wall_id: String,
+ wall_slug: String,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.update_wall_slug(&wall_id, &wall_slug).await?).map_err(Into::into)
+ }
+
+ /// Lookup public wall metadata by slug.
+ pub async fn lookup_wall_by_slug(&self, wall_slug: String) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.lookup_wall_by_slug(&wall_slug).await?).map_err(Into::into)
+ }
+
+ /// Return whether the target wall is self, friend, or neither.
+ pub async fn get_relationship(&self, target_wall_id: String) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.get_relationship(&target_wall_id).await?).map_err(Into::into)
+ }
+
+ /// Create or rotate a shareable wall link.
+ pub async fn create_wall_link(&self, wall_id: String) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&created_link_to_js(
+ self.inner.create_wall_link(&wall_id).await?,
+ ))
+ .map_err(Into::into)
+ }
+
+ /// Fetch wall link status.
+ pub async fn get_wall_link_status(&self, wall_id: String) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.get_wall_link_status(&wall_id).await?).map_err(Into::into)
+ }
+
+ /// Delete a wall link.
+ pub async fn delete_wall_link(&self, wall_id: String) -> Result<(), WasmWallError> {
+ self.inner
+ .delete_wall_link(&wall_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Join a wall link as a friend.
+ pub async fn join_wall_link(
+ &self,
+ wall_username: String,
+ access_key: String,
+ ) -> Result<JsValue, WasmWallError> {
+ let link = WallLinkCtx::open(OpenWallLinkCtxInput {
+ base_url: self.base_url.clone(),
+ wall_username,
+ access_key,
+ user_agent: self.user_agent.clone(),
+ client_package: self.client_package.clone(),
+ client_version: self.client_version.clone(),
+ })
+ .await?;
+ swb::to_value(&self.inner.add_friend_from_link(&link).await?).map_err(Into::into)
+ }
+
+ /// List the current account feed with captions decrypted.
+ pub async fn list_feed(
+ &self,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<JsValue, WasmWallError> {
+ let page = self.inner.list_feed(cursor, limit).await?;
+ swb::to_value(
+ &account_post_page_to_js(
+ &self.inner,
+ ente_wall::PostPage {
+ items: page
+ .items
+ .into_iter()
+ .map(|item| PostResponse {
+ post_id: item.post_id,
+ wall_id: item.wall_id,
+ wall_slug: item.wall_slug.clone(),
+ owner_user_id: item.owner_user_id,
+ author: item.wall_slug,
+ encrypted_post_key: item.encrypted_post_key,
+ caption_cipher: item.caption_cipher,
+ key_version: item.key_version,
+ objects: item.objects,
+ created_at: item.created_at,
+ likes: item.likes,
+ viewer_liked: item.viewer_liked,
+ comments: item.comments,
+ })
+ .collect(),
+ next_cursor: page.next_cursor,
+ },
+ )
+ .await?,
+ )
+ .map_err(Into::into)
+ }
+
+ /// List posts on a wall with captions decrypted.
+ pub async fn list_posts(
+ &self,
+ wall_id: String,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(
+ &account_post_page_to_js(
+ &self.inner,
+ self.inner.list_posts(&wall_id, cursor, limit).await?,
+ )
+ .await?,
+ )
+ .map_err(Into::into)
+ }
+
+ /// Create a single-photo post with optional caption.
+ pub async fn create_photo_post(
+ &self,
+ wall_id: String,
+ photo_bytes: Vec<u8>,
+ caption: Option<String>,
+ width: Option<i32>,
+ height: Option<i32>,
+ media_type: Option<String>,
+ ) -> Result<JsValue, WasmWallError> {
+ let post_key = self.inner.generate_post_key();
+ let object = self
+ .inner
+ .upload_post_photo_asset(&post_key, &photo_bytes, width, height, media_type)
+ .await?;
+ let (post_id, _) = self
+ .inner
+ .create_post(
+ &wall_id,
+ &[object],
+ caption.as_ref().map(|value| value.as_bytes()),
+ Some(&post_key),
+ )
+ .await?;
+ let post = self.inner.get_post(post_id).await?;
+ let decrypted = self
+ .inner
+ .decrypt_post_for_wall(&post.wall_id, &post)
+ .await?;
+ swb::to_value(&post_to_js(post, decrypted)?).map_err(Into::into)
+ }
+
+ /// Download and decrypt one object from a wall post.
+ pub async fn download_post_asset(
+ &self,
+ post_id: i64,
+ object_key: String,
+ ) -> Result<Vec<u8>, WasmWallError> {
+ self.inner
+ .download_post_asset(post_id, &object_key)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Download and decrypt a wall avatar using an owned or friend wall key.
+ pub async fn download_wall_avatar(
+ &self,
+ wall_id: String,
+ object_key: String,
+ ) -> Result<Vec<u8>, WasmWallError> {
+ let wall_key = self
+ .inner
+ .resolve_wall_key(&wall_id)
+ .await?
+ .ok_or_else(|| {
+ CoreWallError::InvalidInput(format!("no wall key available for {wall_id}"))
+ })?;
+ self.inner
+ .download_decrypted_asset(&wall_id, &object_key, &wall_key)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Like or unlike a post.
+ pub async fn like_post(&self, post_id: i64, like: bool) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.like_post(post_id, like).await?).map_err(Into::into)
+ }
+
+ /// List people who liked a post.
+ pub async fn list_post_likers(
+ &self,
+ post_id: i64,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.list_post_likers(post_id, cursor, limit).await?)
+ .map_err(Into::into)
+ }
+
+ /// List comments with plaintext decrypted.
+ pub async fn list_comments(
+ &self,
+ post_id: i64,
+ limit: Option<i32>,
+ cursor: Option<i64>,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&account_comment_page_to_js(&self.inner, post_id, limit, cursor).await?)
+ .map_err(Into::into)
+ }
+
+ /// Create a comment or reply.
+ pub async fn create_comment(
+ &self,
+ post_id: i64,
+ comment: String,
+ parent_comment_id: Option<i64>,
+ ) -> Result<JsValue, WasmWallError> {
+ let post = self.inner.get_post(post_id).await?;
+ let decrypted_post = self
+ .inner
+ .decrypt_post_for_wall(&post.wall_id, &post)
+ .await?;
+ let response = self
+ .inner
+ .create_comment(
+ post_id,
+ &decrypted_post.post_key,
+ comment.as_bytes(),
+ parent_comment_id,
+ )
+ .await?;
+ let decrypted = self
+ .inner
+ .decrypt_comment(&decrypted_post.post_key, &response)?;
+ swb::to_value(&comment_to_js(response, decrypted)?).map_err(Into::into)
+ }
+
+ /// Like or unlike a comment.
+ pub async fn like_comment(
+ &self,
+ post_id: i64,
+ comment_id: i64,
+ like: bool,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.like_comment(post_id, comment_id, like).await?)
+ .map_err(Into::into)
+ }
+
+ /// Delete a comment.
+ pub async fn delete_comment(&self, post_id: i64, comment_id: i64) -> Result<(), WasmWallError> {
+ self.inner
+ .delete_comment(post_id, comment_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Update a post caption.
+ pub async fn update_post_caption(
+ &self,
+ post_id: i64,
+ caption: Option<String>,
+ ) -> Result<(), WasmWallError> {
+ let post = self.inner.get_post(post_id).await?;
+ let decrypted_post = self
+ .inner
+ .decrypt_post_for_wall(&post.wall_id, &post)
+ .await?;
+ self.inner
+ .update_post_caption(
+ post_id,
+ &decrypted_post.post_key,
+ caption.as_ref().map(|value| value.as_bytes()),
+ )
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Delete a post.
+ pub async fn delete_post(&self, post_id: i64) -> Result<(), WasmWallError> {
+ self.inner.delete_post(post_id).await.map_err(Into::into)
+ }
+
+ /// List friends for a wall.
+ pub async fn list_wall_friends(&self, wall_id: String) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.list_wall_friends(&wall_id).await?).map_err(Into::into)
+ }
+
+ /// Remove a friend by their wall ID.
+ pub async fn remove_friend_by_wall(&self, wall_id: String) -> Result<(), WasmWallError> {
+ self.inner
+ .unfriend_by_wall(&wall_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// List friend shares available to the current account.
+ pub async fn list_friend_shares(&self) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.list_friend_shares().await?).map_err(Into::into)
+ }
+
+ /// Refresh friend shares for a rotated wall key.
+ pub async fn refresh_friend_shares(&self, wall_id: String) -> Result<usize, WasmWallError> {
+ self.inner
+ .refresh_friend_shares(&wall_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// List notifications with comment plaintext decrypted where present.
+ pub async fn list_notifications(
+ &self,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<JsValue, WasmWallError> {
+ let page = self.inner.list_notifications(cursor, limit).await?;
+ let mut items = Vec::with_capacity(page.items.len());
+ for item in page.items {
+ items.push(notification_to_js(&self.inner, item).await?);
+ }
+ swb::to_value(&NotificationPageJs {
+ items,
+ next_cursor: page.next_cursor,
+ })
+ .map_err(Into::into)
+ }
+}
+
+/// Handle to a public wall link context.
+#[wasm_bindgen]
+pub struct WallLinkCtxHandle {
+ inner: WallLinkCtx,
+}
+
+#[wasm_bindgen]
+impl WallLinkCtxHandle {
+ /// Fetch and decrypt the public wall profile.
+ pub async fn get_wall_profile(&self) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&profile_to_js(
+ self.inner.get_wall_profile_decrypted(None).await?,
+ )?)
+ .map_err(Into::into)
+ }
+
+ /// List public wall posts with captions decrypted.
+ pub async fn list_posts(
+ &self,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(
+ &link_post_page_to_js(&self.inner, self.inner.list_posts(cursor, limit).await?).await?,
+ )
+ .map_err(Into::into)
+ }
+
+ /// Download and decrypt one object from a public wall post.
+ pub async fn download_post_asset(
+ &self,
+ post_id: i64,
+ object_key: String,
+ ) -> Result<Vec<u8>, WasmWallError> {
+ self.inner
+ .download_post_asset(post_id, &object_key)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Download and decrypt the public wall avatar.
+ pub async fn download_wall_avatar(&self, object_key: String) -> Result<Vec<u8>, WasmWallError> {
+ self.inner
+ .download_decrypted_asset(&object_key, self.inner.wall_key())
+ .await
+ .map_err(Into::into)
+ }
+
+ /// List comments with plaintext decrypted.
+ pub async fn list_comments(
+ &self,
+ post_id: i64,
+ limit: Option<i32>,
+ cursor: Option<i64>,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&link_comment_page_to_js(&self.inner, post_id, limit, cursor).await?)
+ .map_err(Into::into)
+ }
+
+ /// List people who liked a post.
+ pub async fn list_post_likers(
+ &self,
+ post_id: i64,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<JsValue, WasmWallError> {
+ swb::to_value(&self.inner.list_post_likers(post_id, cursor, limit).await?)
+ .map_err(Into::into)
+ }
+}