Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add private post replies and messages

Anand Baburajan08d6358dcb93
diff --git a/rust/wall/Cargo.toml b/rust/wall/Cargo.toml
index a2650d5255..d33557c6f5 100644
--- a/rust/wall/Cargo.toml
+++ b/rust/wall/Cargo.toml
@@ -7,6 +7,7 @@ edition = "2024"
base64 = "0.22"
ente-core = { path = "../core" }
serde = { version = "1", features = ["derive"] }
+serde_json = "1"
thiserror = "2"
url = "2"
urlencoding = "2"
diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rs
index a4ef86889b..2a74689144 100644
--- a/rust/wall/src/client.rs
+++ b/rust/wall/src/client.rs
@@ -8,27 +8,30 @@ use crate::crypto::{
};
use crate::error::{Result, WallError};
use crate::models::{
- CreatedWall, CreatedWallLink, DecryptedFriendShare, DecryptedPost, DecryptedWallProfile,
- FeedItem, FeedPage, HydratedKeys, OpenAccountWallCtxInput, OpenWallLinkCtxInput,
- PrivateKeySource,
+ CreatedWall, CreatedWallLink, DecryptedFriendShare, DecryptedMessage, DecryptedPost,
+ DecryptedWallProfile, FeedItem, FeedPage, HydratedKeys, MessagePayload, MessageQuote,
+ OpenAccountWallCtxInput, OpenWallLinkCtxInput, PrivateKeySource,
};
use crate::transport::{
- AddFriendPayload, AssetDownloadResponse, CreateEntityKeyRequest, CreatePostRequest,
- CreatePostResponse, CreateWallRequest, EntityKeyPayload, EntityKeyResponse,
+ AddFriendPayload, AssetDownloadResponse, CreateEntityKeyRequest, CreateMessageRequest,
+ CreatePostRequest, CreatePostResponse, CreateWallRequest, EntityKeyPayload, EntityKeyResponse,
FriendRelationshipResponse, FriendShareResponse, FriendStatusResponse, FriendTargetPayload,
- LikePostRequest, LikePostResponse, ListPostLikersResponse, PostObjectPayload, PostPage,
- PostResponse, PresignUploadRequest, PresignUploadResponse, ProfileAvatarPayload,
- RefreshFriendSharesRequest, RotateWallKeyRequest, ShareUpdatePayload, UpdatePostCaptionRequest,
- UpdateWallProfileRequest, UpdateWallProfileResponse, UpdateWallSlugRequest, WallActorResponse,
- WallFriendResponse, WallKeyResponse, WallKeyVersionResponse, WallLinkCreateRequest,
- WallLinkLoginRequest, WallLinkLoginResponse, WallLinkStatusResponse, WallLookupResponse,
- WallNotificationPage, WallProfileResponse,
+ LikePostRequest, LikePostResponse, ListPostLikersResponse, MessageConversationPage,
+ MessagePage, MessageResponse, PostObjectPayload, PostPage, PostResponse, PresignUploadRequest,
+ PresignUploadResponse, ProfileAvatarPayload, RefreshFriendSharesRequest, RotateWallKeyRequest,
+ ShareUpdatePayload, UpdatePostCaptionRequest, UpdateWallProfileRequest,
+ UpdateWallProfileResponse, UpdateWallSlugRequest, WallActorResponse, WallFriendResponse,
+ WallKeyResponse, WallKeyVersionResponse, WallLinkCreateRequest, WallLinkLoginRequest,
+ WallLinkLoginResponse, WallLinkStatusResponse, WallLookupResponse, WallNotificationPage,
+ WallProfileResponse,
};
use ente_core::crypto::{sealed, secretbox};
use ente_core::http::{Error as HttpError, HttpClient, HttpConfig};
const ROOT_WALL_KEY_TYPE: &str = "wall";
const UPLOAD_PURPOSE_AVATAR: &str = "avatar";
+const MESSAGE_KIND_REGULAR: &str = "regular";
+const MESSAGE_KIND_POST_REPLY: &str = "post_reply";
#[derive(Debug, Clone)]
struct ResolvedWallAccess {
@@ -808,6 +811,143 @@ impl AccountWallCtx {
.map_err(Into::into)
}
+ pub async fn list_message_conversations(
+ &self,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<MessageConversationPage> {
+ 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/messages", &query)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn list_message_thread(
+ &self,
+ wall_id: &str,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<MessagePage> {
+ 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/messages/{wall_id}");
+ self.client
+ .get_json(&path, &query)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn send_message(&self, wall_id: &str, text: &str) -> Result<MessageResponse> {
+ let friend = self.friend_actor_for_wall(wall_id).await?;
+ let payload = MessagePayload {
+ version: 1,
+ kind: MESSAGE_KIND_REGULAR.to_owned(),
+ text: text.to_owned(),
+ quote: None,
+ };
+ let request = self.message_request_for_payload(&friend.public_key, &payload)?;
+ let path = format!("/wall/messages/{wall_id}");
+ self.client
+ .post_json(&path, &request)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn reply_to_post(&self, post_id: i64, text: &str) -> Result<MessageResponse> {
+ let post = self.get_post(post_id).await?;
+ if Some(post.owner_user_id) == self.user_id {
+ return Err(WallError::InvalidInput(
+ "cannot reply to your own post".into(),
+ ));
+ }
+ if post.author.public_key.trim().is_empty() {
+ return Err(WallError::InvalidInput(
+ "post author public key is missing".into(),
+ ));
+ }
+ let decrypted = self.decrypt_post_for_wall(&post.wall_id, &post).await?;
+ let caption = optional_utf8(decrypted.caption_plaintext, "caption")?;
+ let object = post.objects.first();
+ let payload = MessagePayload {
+ version: 1,
+ kind: MESSAGE_KIND_POST_REPLY.to_owned(),
+ text: text.to_owned(),
+ quote: Some(MessageQuote {
+ post_id,
+ wall_id: post.wall_id.clone(),
+ caption,
+ object_key: object.map(|value| value.object_key.clone()),
+ width: object.and_then(|value| value.width),
+ height: object.and_then(|value| value.height),
+ media_type: object.and_then(|value| value.media_type.clone()),
+ }),
+ };
+ let request = self.message_request_for_payload(&post.author.public_key, &payload)?;
+ let path = format!("/wall/posts/{post_id}/reply");
+ self.client
+ .post_json(&path, &request)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub fn decrypt_message(&self, message: &MessageResponse) -> Result<DecryptedMessage> {
+ if message.is_deleted {
+ return Err(WallError::InvalidInput("message is deleted".into()));
+ }
+ let packed_key = decode_b64(&message.encrypted_message_key)?;
+ let (sealed_key, _) = unpack_payload(&packed_key)?;
+ let message_key = sealed::open(&sealed_key, &self.public_key, &self.private_key)?;
+ let packed_message = decode_b64(&message.message_cipher)?;
+ let plaintext = decrypt_secretbox_packed(&message_key, &packed_message)?;
+ let payload: MessagePayload = serde_json::from_slice(&plaintext)
+ .map_err(|err| WallError::InvalidInput(format!("invalid message payload: {err}")))?;
+ Ok(DecryptedMessage {
+ message_key,
+ payload,
+ })
+ }
+
+ async fn friend_actor_for_wall(&self, wall_id: &str) -> Result<WallActorResponse> {
+ let (owned_wall, _) = self.default_owned_wall_access().await?;
+ let friends = self.list_wall_friends(&owned_wall.wall_id).await?;
+ friends
+ .into_iter()
+ .map(|value| value.friend)
+ .find(|friend| friend.wall_id == wall_id)
+ .ok_or_else(|| WallError::InvalidInput(format!("wall {wall_id} is not a friend")))
+ }
+
+ fn message_request_for_payload(
+ &self,
+ recipient_public_key: &str,
+ payload: &MessagePayload,
+ ) -> Result<CreateMessageRequest> {
+ let recipient_public_key = decode_b64(recipient_public_key)?;
+ let message_key = generate_key();
+ let plaintext = serde_json::to_vec(payload)
+ .map_err(|err| WallError::InvalidInput(format!("invalid message payload: {err}")))?;
+ let sender_key = sealed::seal(&message_key, &self.public_key)?;
+ let recipient_key = sealed::seal(&message_key, &recipient_public_key)?;
+ Ok(CreateMessageRequest {
+ message_id: None,
+ message_cipher: encode_b64(&encrypt_secretbox_packed(&message_key, &plaintext)?),
+ sender_encrypted_message_key: encode_b64(&pack_payload(&sender_key, &[])),
+ recipient_encrypted_message_key: encode_b64(&pack_payload(&recipient_key, &[])),
+ })
+ }
+
pub async fn add_friend_from_link(&self, link: &WallLinkCtx) -> Result<FriendStatusResponse> {
if link.owner_public_key().is_empty() {
return Err(WallError::InvalidInput(
@@ -1020,6 +1160,15 @@ fn post_response_from_feed_item(item: &FeedItem) -> PostResponse {
}
}
+fn optional_utf8(bytes: Option<Vec<u8>>, field: &str) -> Result<Option<String>> {
+ bytes
+ .map(|value| {
+ String::from_utf8(value)
+ .map_err(|err| WallError::InvalidInput(format!("invalid {field} utf8: {err}")))
+ })
+ .transpose()
+}
+
impl WallLinkCtx {
pub async fn open(input: OpenWallLinkCtxInput) -> Result<Self> {
let access_key_material = wall_link_access_key_material(&input.access_key)?;
@@ -2666,6 +2815,28 @@ mod tests {
}
}
},
+ {
+ "id": "post_reply:wmsg_1",
+ "type": "repliedToPost",
+ "createdAt": "2026-04-16T12: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": {
+ "userId": 7,
+ "wallId": "wall_owner_gallery",
+ "wallSlug": "owner-gallery"
+ }
+ }
+ },
{
"id": "friend_remove:12",
"type": "removedYouAsFriend",
@@ -2687,13 +2858,17 @@ mod tests {
.await
.expect("notifications should load");
- assert_eq!(page.items.len(), 2);
+ assert_eq!(page.items.len(), 3);
assert_eq!(
page.items[0].notification_type,
crate::transport::WallNotificationType::LikedPost
);
assert_eq!(
page.items[1].notification_type,
+ crate::transport::WallNotificationType::RepliedToPost
+ );
+ assert_eq!(
+ page.items[2].notification_type,
crate::transport::WallNotificationType::RemovedYouAsFriend
);
assert_eq!(page.items[0].actor.wall_slug, "mira");
diff --git a/rust/wall/src/lib.rs b/rust/wall/src/lib.rs
index 4809583aa6..a625c41232 100644
--- a/rust/wall/src/lib.rs
+++ b/rust/wall/src/lib.rs
@@ -7,15 +7,16 @@ pub mod transport;
pub use client::{AccountWallCtx, WallLinkCtx};
pub use error::{Result, WallError};
pub use models::{
- AuthKeyAttributes, CreatedWall, CreatedWallLink, DecryptedFriendShare, DecryptedPost,
- DecryptedWallProfile, FeedItem, FeedPage, HydratedKeys, OpenAccountWallCtxInput,
- OpenWallLinkCtxInput, PrivateKeySource,
+ AuthKeyAttributes, CreatedWall, CreatedWallLink, DecryptedFriendShare, DecryptedMessage,
+ DecryptedPost, DecryptedWallProfile, FeedItem, FeedPage, HydratedKeys, MessagePayload,
+ MessageQuote, OpenAccountWallCtxInput, OpenWallLinkCtxInput, PrivateKeySource,
};
pub use transport::{
EntityKeyPayload, FriendRelationshipResponse, FriendShareResponse, FriendStatusResponse,
- LikePostResponse, ListPostLikersResponse, PostLikerResponse, PostObjectPayload, PostPage,
- PostResponse, PresignUploadResponse, ProfileAvatarPayload, ProfileAvatarResponse,
- WallActorResponse, WallFriendResponse, WallKeyResponse, WallKeyVersionResponse,
- WallLinkLoginResponse, WallLinkStatusResponse, WallLookupResponse, WallNotification,
- WallNotificationPage, WallNotificationPost, WallNotificationType, WallProfileResponse,
+ LikePostResponse, ListPostLikersResponse, MessageConversationPage, MessageConversationResponse,
+ MessagePage, MessageResponse, PostLikerResponse, PostObjectPayload, PostPage, PostResponse,
+ PresignUploadResponse, ProfileAvatarPayload, ProfileAvatarResponse, WallActorResponse,
+ WallFriendResponse, WallKeyResponse, WallKeyVersionResponse, WallLinkLoginResponse,
+ WallLinkStatusResponse, WallLookupResponse, WallNotification, WallNotificationPage,
+ WallNotificationPost, WallNotificationType, WallProfileResponse,
};
diff --git a/rust/wall/src/models.rs b/rust/wall/src/models.rs
index 62452d2eb9..f701202322 100644
--- a/rust/wall/src/models.rs
+++ b/rust/wall/src/models.rs
@@ -80,6 +80,39 @@ pub struct DecryptedPost {
pub caption_plaintext: Option<Vec<u8>>,
}
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct MessageQuote {
+ pub post_id: i64,
+ pub wall_id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub caption: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub object_key: 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, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct MessagePayload {
+ pub version: i32,
+ pub kind: String,
+ pub text: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub quote: Option<MessageQuote>,
+}
+
+#[derive(Debug, Clone)]
+pub struct DecryptedMessage {
+ pub message_key: Vec<u8>,
+ pub payload: MessagePayload,
+}
+
#[derive(Debug, Clone)]
pub struct DecryptedFriendShare {
pub friend: String,
diff --git a/rust/wall/src/transport.rs b/rust/wall/src/transport.rs
index ce2f09cbf2..0a169c672a 100644
--- a/rust/wall/src/transport.rs
+++ b/rust/wall/src/transport.rs
@@ -128,6 +128,58 @@ pub struct LikePostResponse {
pub liked: bool,
}
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateMessageRequest {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub message_id: Option<String>,
+ pub message_cipher: String,
+ pub sender_encrypted_message_key: String,
+ pub recipient_encrypted_message_key: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MessageResponse {
+ pub message_id: String,
+ pub kind: String,
+ pub sender: WallActorResponse,
+ pub recipient: WallActorResponse,
+ #[serde(default)]
+ pub message_cipher: String,
+ #[serde(default)]
+ pub encrypted_message_key: String,
+ #[serde(default)]
+ pub reply_post_id: Option<i64>,
+ #[serde(default)]
+ pub is_deleted: bool,
+ pub created_at: String,
+ pub updated_at: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MessagePage {
+ pub items: Vec<MessageResponse>,
+ #[serde(default)]
+ pub next_cursor: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MessageConversationResponse {
+ pub friend: WallActorResponse,
+ pub last_message: MessageResponse,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MessageConversationPage {
+ pub items: Vec<MessageConversationResponse>,
+ #[serde(default)]
+ pub next_cursor: String,
+}
+
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdatePostCaptionRequest {
@@ -167,6 +219,7 @@ pub struct PostPage {
#[serde(rename_all = "camelCase")]
pub enum WallNotificationType {
LikedPost,
+ RepliedToPost,
AddedYouAsFriend,
RemovedYouAsFriend,
}
diff --git a/server/migrations/121_wall.down.sql b/server/migrations/121_wall.down.sql
index 5e66733d7a..6b99c178e0 100644
--- a/server/migrations/121_wall.down.sql
+++ b/server/migrations/121_wall.down.sql
@@ -8,6 +8,11 @@ DROP TABLE IF EXISTS wall_friend_events;
DROP TRIGGER IF EXISTS update_wall_friend_shares_updated_at ON wall_friend_shares;
DROP TABLE IF EXISTS wall_friend_shares;
+DROP TRIGGER IF EXISTS update_wall_messages_updated_at ON wall_messages;
+DROP TRIGGER IF EXISTS wall_messages_null_cipher_on_delete ON wall_messages;
+DROP TABLE IF EXISTS wall_messages;
+DROP FUNCTION IF EXISTS tg_wall_messages_null_cipher_on_delete();
+
DROP TABLE IF EXISTS wall_post_likes;
DROP TABLE IF EXISTS wall_temp_objects;
DROP TABLE IF EXISTS wall_post_assets;
diff --git a/server/migrations/121_wall.up.sql b/server/migrations/121_wall.up.sql
index 348079d32a..936331e190 100644
--- a/server/migrations/121_wall.up.sql
+++ b/server/migrations/121_wall.up.sql
@@ -148,6 +148,78 @@ CREATE INDEX IF NOT EXISTS idx_wall_friend_events_target_created
CREATE INDEX IF NOT EXISTS idx_wall_friend_events_target_type_created
ON wall_friend_events (target_id, event_type, created_at DESC);
+CREATE OR REPLACE FUNCTION tg_wall_messages_null_cipher_on_delete() RETURNS trigger AS $$
+BEGIN
+ IF NEW.is_deleted THEN
+ NEW.message_cipher := NULL;
+ NEW.sender_encrypted_message_key := NULL;
+ NEW.recipient_encrypted_message_key := NULL;
+ END IF;
+ RETURN NEW;
+END; $$ LANGUAGE plpgsql;
+
+CREATE TABLE IF NOT EXISTS wall_messages (
+ message_id TEXT PRIMARY KEY,
+ sender_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,
+ sender_wall_id TEXT NOT NULL REFERENCES walls (wall_id) ON DELETE CASCADE,
+ recipient_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,
+ recipient_wall_id TEXT NOT NULL REFERENCES walls (wall_id) ON DELETE CASCADE,
+ thread_key TEXT GENERATED ALWAYS AS (
+ CASE
+ WHEN sender_wall_id < recipient_wall_id
+ THEN sender_wall_id || ':' || recipient_wall_id
+ ELSE recipient_wall_id || ':' || sender_wall_id
+ END
+ ) STORED,
+ kind TEXT NOT NULL,
+ message_cipher TEXT,
+ sender_encrypted_message_key TEXT,
+ recipient_encrypted_message_key TEXT,
+ reply_post_id BIGINT REFERENCES wall_posts (post_id) ON DELETE SET NULL,
+ is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ CONSTRAINT chk_wall_messages_distinct_users CHECK (sender_id <> recipient_id),
+ CONSTRAINT chk_wall_messages_kind CHECK (kind IN ('regular', 'post_reply')),
+ CONSTRAINT chk_wall_messages_regular_shape CHECK (kind <> 'regular' OR reply_post_id IS NULL),
+ CONSTRAINT chk_wall_messages_cipher_on_delete CHECK (
+ (
+ is_deleted = FALSE
+ AND message_cipher IS NOT NULL
+ AND sender_encrypted_message_key IS NOT NULL
+ AND recipient_encrypted_message_key IS NOT NULL
+ ) OR (
+ is_deleted = TRUE
+ AND message_cipher IS NULL
+ AND sender_encrypted_message_key IS NULL
+ AND recipient_encrypted_message_key IS NULL
+ )
+ )
+);
+
+CREATE INDEX IF NOT EXISTS idx_wall_messages_sender_updated
+ ON wall_messages (sender_id, updated_at DESC, message_id DESC);
+
+CREATE INDEX IF NOT EXISTS idx_wall_messages_recipient_updated
+ ON wall_messages (recipient_id, updated_at DESC, message_id DESC);
+
+CREATE INDEX IF NOT EXISTS idx_wall_messages_thread_created
+ ON wall_messages (thread_key, created_at DESC, message_id DESC);
+
+CREATE INDEX IF NOT EXISTS idx_wall_messages_reply_post
+ ON wall_messages (reply_post_id)
+ WHERE reply_post_id IS NOT NULL;
+
+CREATE TRIGGER wall_messages_null_cipher_on_delete
+ BEFORE INSERT OR UPDATE ON wall_messages
+ FOR EACH ROW
+EXECUTE PROCEDURE tg_wall_messages_null_cipher_on_delete();
+
+CREATE TRIGGER update_wall_messages_updated_at
+ BEFORE UPDATE ON wall_messages
+ FOR EACH ROW
+EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
+
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/messages.go b/server/wall/api/messages.go
new file mode 100644
index 0000000000..6eeafe4133
--- /dev/null
+++ b/server/wall/api/messages.go
@@ -0,0 +1,47 @@
+package api
+
+import (
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/wall/models"
+ "github.com/gin-gonic/gin"
+)
+
+func (h *Handlers) CreateMessage(c *gin.Context) {
+ var req models.CreateMessageRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ respondJSON(c, nil, ente.ErrBadRequest)
+ return
+ }
+ resp, err := h.Module.Messages.Create(c, c.Param("wallID"), req)
+ respondJSON(c, resp, err)
+}
+
+func (h *Handlers) ReplyToPost(c *gin.Context) {
+ var req models.CreateMessageRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ respondJSON(c, nil, ente.ErrBadRequest)
+ return
+ }
+ resp, err := h.Module.Messages.ReplyToPost(c, c.Param("postID"), req)
+ respondJSON(c, resp, err)
+}
+
+func (h *Handlers) ListMessages(c *gin.Context) {
+ var req models.ListMessagesRequest
+ if err := c.ShouldBindQuery(&req); err != nil {
+ respondJSON(c, nil, ente.ErrBadRequest)
+ return
+ }
+ resp, err := h.Module.Messages.List(c, req)
+ respondJSON(c, resp, err)
+}
+
+func (h *Handlers) ListMessageThread(c *gin.Context) {
+ var req models.ListMessageThreadRequest
+ if err := c.ShouldBindQuery(&req); err != nil {
+ respondJSON(c, nil, ente.ErrBadRequest)
+ return
+ }
+ resp, err := h.Module.Messages.ListThread(c, c.Param("wallID"), req)
+ respondJSON(c, resp, err)
+}
diff --git a/server/wall/api/register.go b/server/wall/api/register.go
index dc1dc419e0..0ddd2be18a 100644
--- a/server/wall/api/register.go
+++ b/server/wall/api/register.go
@@ -14,7 +14,11 @@ func Register(privateAPI, publicAPI gin.IRoutes, handlers *Handlers) {
privateAPI.POST("/wall/posts/:postID/caption", handlers.UpdatePostCaption)
privateAPI.PATCH("/wall/posts/:postID/caption", handlers.UpdatePostCaption)
privateAPI.POST("/wall/posts/:postID/like", handlers.TogglePostLike)
+ privateAPI.POST("/wall/posts/:postID/reply", handlers.ReplyToPost)
privateAPI.DELETE("/wall/posts/:postID", handlers.DeletePost)
+ privateAPI.GET("/wall/messages", handlers.ListMessages)
+ privateAPI.GET("/wall/messages/:wallID", handlers.ListMessageThread)
+ privateAPI.POST("/wall/messages/:wallID", handlers.CreateMessage)
privateAPI.GET("/wall/notifications", handlers.ListNotifications)
privateAPI.POST("/wall/friends/add", handlers.AddFriend)
privateAPI.POST("/wall/friends/unfriend", handlers.Unfriend)
diff --git a/server/wall/controller/messages.go b/server/wall/controller/messages.go
new file mode 100644
index 0000000000..ee25956b6c
--- /dev/null
+++ b/server/wall/controller/messages.go
@@ -0,0 +1,202 @@
+package controller
+
+import (
+ "database/sql"
+ "errors"
+ "strconv"
+ "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"
+)
+
+const (
+ wallMessageKindRegular = "regular"
+ wallMessageKindPostReply = "post_reply"
+)
+
+type MessagesController struct {
+ MessagesRepo *repo.MessagesRepository
+ PostsRepo *repo.PostsRepository
+ WallsRepo *repo.WallsRepository
+ FriendsRepo *repo.FriendsRepository
+ auth authDeps
+}
+
+func (c *MessagesController) Create(ctx *gin.Context, targetWallID string, req models.CreateMessageRequest) (*models.MessageResponse, error) {
+ userID, err := c.auth.requireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if err := validateCreateMessageRequest(req); err != nil {
+ return nil, err
+ }
+ senderWall, recipientWall, err := c.requireFriendMessageTarget(ctx, userID, targetWallID)
+ if err != nil {
+ return nil, err
+ }
+ message, err := c.MessagesRepo.CreateMessage(ctx.Request.Context(), repo.CreateWallMessageRecord{
+ MessageID: req.MessageID,
+ Kind: wallMessageKindRegular,
+ SenderID: userID,
+ SenderWallID: senderWall.WallID,
+ RecipientID: recipientWall.OwnerID,
+ RecipientWallID: recipientWall.WallID,
+ MessageCipher: req.MessageCipher,
+ SenderEncryptedMessageKey: req.SenderEncryptedMessageKey,
+ RecipientEncryptedMessageKey: req.RecipientEncryptedMessageKey,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return toMessageResponse(*message), nil
+}
+
+func (c *MessagesController) ReplyToPost(ctx *gin.Context, postID string, req models.CreateMessageRequest) (*models.MessageResponse, error) {
+ userID, err := c.auth.requireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if err := validateCreateMessageRequest(req); err != nil {
+ return nil, err
+ }
+ id, err := strconv.ParseInt(strings.TrimSpace(postID), 10, 64)
+ if err != nil || id <= 0 {
+ return nil, ente.NewBadRequestWithMessage("invalid postID")
+ }
+ post, err := c.PostsRepo.GetPost(ctx.Request.Context(), id, 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
+ }
+ if wall.OwnerID == userID {
+ return nil, ente.NewBadRequestWithMessage("cannot reply to your own post")
+ }
+ senderWall, recipientWall, err := c.requireFriendMessageTarget(ctx, userID, wall.WallID)
+ if err != nil {
+ return nil, err
+ }
+ message, err := c.MessagesRepo.CreateMessage(ctx.Request.Context(), repo.CreateWallMessageRecord{
+ MessageID: req.MessageID,
+ Kind: wallMessageKindPostReply,
+ SenderID: userID,
+ SenderWallID: senderWall.WallID,
+ RecipientID: recipientWall.OwnerID,
+ RecipientWallID: recipientWall.WallID,
+ MessageCipher: req.MessageCipher,
+ SenderEncryptedMessageKey: req.SenderEncryptedMessageKey,
+ RecipientEncryptedMessageKey: req.RecipientEncryptedMessageKey,
+ ReplyPostID: sql.NullInt64{Int64: id, Valid: true},
+ })
+ if err != nil {
+ return nil, err
+ }
+ return toMessageResponse(*message), nil
+}
+
+func (c *MessagesController) List(ctx *gin.Context, req models.ListMessagesRequest) (*models.MessageConversationPage, error) {
+ userID, err := c.auth.requireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ conversations, nextCursor, err := c.MessagesRepo.ListConversations(ctx.Request.Context(), userID, req.Cursor, req.Limit)
+ if err != nil {
+ return nil, err
+ }
+ items := make([]models.MessageConversationResponse, 0, len(conversations))
+ for _, conversation := range conversations {
+ items = append(items, models.MessageConversationResponse{
+ Friend: toActorResponse(conversation.Friend, true),
+ LastMessage: *toMessageResponse(conversation.LastMessage),
+ })
+ }
+ return &models.MessageConversationPage{Items: items, NextCursor: nextCursor}, nil
+}
+
+func (c *MessagesController) ListThread(ctx *gin.Context, targetWallID string, req models.ListMessageThreadRequest) (*models.MessagePage, error) {
+ userID, err := c.auth.requireUser(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if strings.TrimSpace(targetWallID) == "" {
+ return nil, ente.NewBadRequestWithMessage("wallId is required")
+ }
+ if _, err := c.WallsRepo.GetWallByID(ctx.Request.Context(), strings.TrimSpace(targetWallID)); err != nil {
+ return nil, err
+ }
+ messages, nextCursor, err := c.MessagesRepo.ListThread(ctx.Request.Context(), userID, strings.TrimSpace(targetWallID), req.Cursor, req.Limit)
+ if err != nil {
+ return nil, err
+ }
+ items := make([]models.MessageResponse, 0, len(messages))
+ for _, message := range messages {
+ items = append(items, *toMessageResponse(message))
+ }
+ return &models.MessagePage{Items: items, NextCursor: nextCursor}, nil
+}
+
+func (c *MessagesController) requireFriendMessageTarget(ctx *gin.Context, userID int64, targetWallID string) (*repo.WallRecord, *repo.WallRecord, error) {
+ targetWallID = strings.TrimSpace(targetWallID)
+ if targetWallID == "" {
+ return nil, nil, ente.NewBadRequestWithMessage("wallId is required")
+ }
+ ownedWalls, err := c.WallsRepo.ListWallsByOwner(ctx.Request.Context(), userID)
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(ownedWalls) == 0 {
+ return nil, nil, ente.NewBadRequestWithMessage("sender wall is missing")
+ }
+ senderWall := ownedWalls[0]
+ recipientWall, err := c.WallsRepo.GetWallByID(ctx.Request.Context(), targetWallID)
+ if err != nil {
+ return nil, nil, err
+ }
+ if recipientWall.OwnerID == userID {
+ return nil, nil, ente.NewBadRequestWithMessage("cannot message your own wall")
+ }
+ if _, err := c.FriendsRepo.GetShareForFriendAndWall(ctx.Request.Context(), userID, recipientWall.WallID); err != nil {
+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {
+ return nil, nil, ente.ErrPermissionDenied
+ }
+ return nil, nil, err
+ }
+ return &senderWall, recipientWall, nil
+}
+
+func validateCreateMessageRequest(req models.CreateMessageRequest) error {
+ if strings.TrimSpace(req.MessageCipher) == "" ||
+ strings.TrimSpace(req.SenderEncryptedMessageKey) == "" ||
+ strings.TrimSpace(req.RecipientEncryptedMessageKey) == "" {
+ return ente.NewBadRequestWithMessage("messageCipher and encrypted message keys are required")
+ }
+ return nil
+}
+
+func toMessageResponse(message repo.WallMessageRecord) *models.MessageResponse {
+ resp := &models.MessageResponse{
+ MessageID: message.MessageID,
+ Kind: message.Kind,
+ Sender: toActorResponse(message.Sender, true),
+ Recipient: toActorResponse(message.Recipient, true),
+ MessageCipher: message.MessageCipher,
+ EncryptedMessageKey: message.EncryptedMessageKey,
+ IsDeleted: message.IsDeleted,
+ CreatedAt: formatMicros(message.CreatedAt),
+ UpdatedAt: formatMicros(message.UpdatedAt),
+ }
+ if message.ReplyPostID.Valid {
+ replyPostID := message.ReplyPostID.Int64
+ resp.ReplyPostID = &replyPostID
+ }
+ return resp
+}
diff --git a/server/wall/controller/module.go b/server/wall/controller/module.go
index a52047f72a..89e37f4c5b 100644
--- a/server/wall/controller/module.go
+++ b/server/wall/controller/module.go
@@ -9,6 +9,7 @@ type Module struct {
Walls *WallsController
Posts *PostsController
Friends *FriendsController
+ Messages *MessagesController
Notifications *NotificationsController
Links *LinksController
Assets *AssetsController
@@ -27,6 +28,7 @@ func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository) *M
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},
+ Messages: &MessagesController{MessagesRepo: repos.Messages, PostsRepo: repos.Posts, WallsRepo: repos.Walls, FriendsRepo: repos.Friends, 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},
diff --git a/server/wall/models/models.go b/server/wall/models/models.go
index 5020b9da3c..a04248f85f 100644
--- a/server/wall/models/models.go
+++ b/server/wall/models/models.go
@@ -31,6 +31,16 @@ type ListNotificationsRequest struct {
Limit int `form:"limit"`
}
+type ListMessagesRequest struct {
+ Cursor string `form:"cursor"`
+ Limit int `form:"limit"`
+}
+
+type ListMessageThreadRequest struct {
+ Cursor string `form:"cursor"`
+ Limit int `form:"limit"`
+}
+
type ListWallFriendsRequest struct {
WallID string `form:"wallId"`
}
@@ -258,6 +268,41 @@ type UpdatePostCaptionRequest struct {
CaptionCipher *string `json:"captionCipher,omitempty"`
}
+type CreateMessageRequest struct {
+ MessageID string `json:"messageId,omitempty"`
+ MessageCipher string `json:"messageCipher"`
+ SenderEncryptedMessageKey string `json:"senderEncryptedMessageKey"`
+ RecipientEncryptedMessageKey string `json:"recipientEncryptedMessageKey"`
+}
+
+type MessageResponse struct {
+ MessageID string `json:"messageId"`
+ Kind string `json:"kind"`
+ Sender WallActorResponse `json:"sender"`
+ Recipient WallActorResponse `json:"recipient"`
+ MessageCipher string `json:"messageCipher,omitempty"`
+ EncryptedMessageKey string `json:"encryptedMessageKey,omitempty"`
+ ReplyPostID *int64 `json:"replyPostId,omitempty"`
+ IsDeleted bool `json:"isDeleted"`
+ CreatedAt string `json:"createdAt"`
+ UpdatedAt string `json:"updatedAt"`
+}
+
+type MessagePage struct {
+ Items []MessageResponse `json:"items"`
+ NextCursor string `json:"nextCursor,omitempty"`
+}
+
+type MessageConversationResponse struct {
+ Friend WallActorResponse `json:"friend"`
+ LastMessage MessageResponse `json:"lastMessage"`
+}
+
+type MessageConversationPage struct {
+ Items []MessageConversationResponse `json:"items"`
+ NextCursor string `json:"nextCursor,omitempty"`
+}
+
type PostObjectPayload struct {
ObjectKey string `json:"objectKey"`
Size int64 `json:"size,omitempty"`
diff --git a/server/wall/repo/messages.go b/server/wall/repo/messages.go
new file mode 100644
index 0000000000..50866b9da4
--- /dev/null
+++ b/server/wall/repo/messages.go
@@ -0,0 +1,248 @@
+package repo
+
+import (
+ "context"
+ "strconv"
+ "strings"
+
+ "github.com/ente-io/museum/ente/base"
+ "github.com/ente-io/stacktrace"
+)
+
+const wallMessageSelectColumns = `
+ m.message_id,
+ m.kind,
+ m.sender_id,
+ m.sender_wall_id,
+ m.recipient_id,
+ m.recipient_wall_id,
+ COALESCE(m.message_cipher, ''),
+ CASE
+ WHEN m.sender_id = %s THEN COALESCE(m.sender_encrypted_message_key, '')
+ ELSE COALESCE(m.recipient_encrypted_message_key, '')
+ END AS encrypted_message_key,
+ m.reply_post_id,
+ m.is_deleted,
+ m.created_at,
+ m.updated_at,
+ sender_wall.owner_id,
+ sender_wall.wall_id,
+ sender_wall.wall_slug,
+ sender_ka.public_key,
+ sender_wall.current_version,
+ sender_wall.encrypted_profile,
+ sender_wall.avatar_object_key,
+ sender_wall.avatar_size,
+ sender_wall.updated_at,
+ (SELECT COUNT(*) FROM wall_friend_shares fs WHERE fs.wall_id = sender_wall.wall_id) AS sender_friends,
+ (SELECT COUNT(*) FROM wall_posts sp WHERE sp.wall_id = sender_wall.wall_id AND sp.is_deleted = FALSE) AS sender_posts,
+ recipient_wall.owner_id,
+ recipient_wall.wall_id,
+ recipient_wall.wall_slug,
+ recipient_ka.public_key,
+ recipient_wall.current_version,
+ recipient_wall.encrypted_profile,
+ recipient_wall.avatar_object_key,
+ recipient_wall.avatar_size,
+ recipient_wall.updated_at,
+ (SELECT COUNT(*) FROM wall_friend_shares fs WHERE fs.wall_id = recipient_wall.wall_id) AS recipient_friends,
+ (SELECT COUNT(*) FROM wall_posts rp WHERE rp.wall_id = recipient_wall.wall_id AND rp.is_deleted = FALSE) AS recipient_posts
+`
+
+const wallMessageJoins = `
+ JOIN walls sender_wall ON sender_wall.wall_id = m.sender_wall_id
+ JOIN key_attributes sender_ka ON sender_ka.user_id = sender_wall.owner_id
+ JOIN walls recipient_wall ON recipient_wall.wall_id = m.recipient_wall_id
+ JOIN key_attributes recipient_ka ON recipient_ka.user_id = recipient_wall.owner_id
+`
+
+func (r *MessagesRepository) CreateMessage(ctx context.Context, input CreateWallMessageRecord) (*WallMessageRecord, error) {
+ messageID := strings.TrimSpace(input.MessageID)
+ if messageID == "" {
+ messageID = base.MustNewID("wmsg")
+ }
+ var replyPostID any
+ if input.ReplyPostID.Valid {
+ replyPostID = input.ReplyPostID.Int64
+ }
+ if _, err := r.DB.ExecContext(ctx, `
+ INSERT INTO wall_messages (
+ message_id,
+ sender_id,
+ sender_wall_id,
+ recipient_id,
+ recipient_wall_id,
+ kind,
+ message_cipher,
+ sender_encrypted_message_key,
+ recipient_encrypted_message_key,
+ reply_post_id
+ )
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
+ `, messageID, input.SenderID, input.SenderWallID, input.RecipientID, input.RecipientWallID, input.Kind, input.MessageCipher, input.SenderEncryptedMessageKey, input.RecipientEncryptedMessageKey, replyPostID); err != nil {
+ return nil, wrapUnique(err, "message already exists")
+ }
+ return r.GetMessage(ctx, messageID, input.SenderID)
+}
+
+func (r *MessagesRepository) GetMessage(ctx context.Context, messageID string, viewerID int64) (*WallMessageRecord, error) {
+ query := `
+ SELECT ` + sprintfWallMessageColumns("$2") + `
+ FROM wall_messages m
+ ` + wallMessageJoins + `
+ WHERE m.message_id = $1
+ AND (m.sender_id = $2 OR m.recipient_id = $2)
+ `
+ return scanMessageRecord(r.DB.QueryRowContext(ctx, query, messageID, viewerID))
+}
+
+func (r *MessagesRepository) ListThread(ctx context.Context, viewerID int64, otherWallID string, cursor string, limit int) ([]WallMessageRecord, string, error) {
+ limit = optionalInt(limit, 50)
+ if limit > 100 {
+ limit = 100
+ }
+ args := []any{viewerID, otherWallID}
+ query := `
+ SELECT ` + sprintfWallMessageColumns("$1") + `
+ FROM wall_messages m
+ ` + wallMessageJoins + `
+ WHERE (
+ (m.sender_id = $1 AND m.recipient_wall_id = $2)
+ OR
+ (m.recipient_id = $1 AND m.sender_wall_id = $2)
+ )
+ AND m.is_deleted = FALSE`
+ if cursorCreatedAt, cursorMessageID, ok := parseMessageCursor(cursor); ok {
+ args = append(args, cursorCreatedAt, cursorMessageID)
+ query += ` AND (m.created_at, m.message_id) < ($3, $4)`
+ }
+ args = append(args, limit+1)
+ query += ` ORDER BY m.created_at DESC, m.message_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([]WallMessageRecord, 0, limit+1)
+ for rows.Next() {
+ rec, err := scanMessageRecord(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 = formatMessageCursor(out[limit-1])
+ out = out[:limit]
+ }
+ return out, nextCursor, nil
+}
+
+func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int64, cursor string, limit int) ([]WallMessageConversationRecord, string, error) {
+ limit = optionalInt(limit, 50)
+ if limit > 100 {
+ limit = 100
+ }
+ var cursorCreatedAt any
+ var cursorID any
+ if createdAt, id, ok := parseMessageCursor(cursor); ok {
+ cursorCreatedAt = createdAt
+ cursorID = id
+ }
+ rows, err := r.DB.QueryContext(ctx, `
+ WITH ranked AS (
+ SELECT
+ m.*,
+ ROW_NUMBER() OVER (
+ PARTITION BY CASE WHEN m.sender_id = $1 THEN m.recipient_wall_id ELSE m.sender_wall_id END
+ ORDER BY m.created_at DESC, m.message_id DESC
+ ) AS rn
+ FROM wall_messages m
+ WHERE (m.sender_id = $1 OR m.recipient_id = $1)
+ AND m.is_deleted = FALSE
+ )
+ SELECT `+sprintfWallMessageColumns("$1")+`
+ FROM ranked m
+ `+wallMessageJoins+`
+ WHERE m.rn = 1
+ AND ($2::bigint IS NULL OR (m.created_at, m.message_id) < ($2::bigint, $3::text))
+ ORDER BY m.created_at DESC, m.message_id DESC
+ LIMIT $4
+ `, viewerID, cursorCreatedAt, cursorID, limit+1)
+ if err != nil {
+ return nil, "", stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+ out := make([]WallMessageConversationRecord, 0, limit+1)
+ for rows.Next() {
+ message, err := scanMessageRecord(rows)
+ if err != nil {
+ return nil, "", err
+ }
+ friend := message.Sender
+ if message.SenderID == viewerID {
+ friend = message.Recipient
+ }
+ out = append(out, WallMessageConversationRecord{
+ Friend: friend,
+ LastMessage: *message,
+ })
+ }
+ if err := rows.Err(); err != nil {
+ return nil, "", stacktrace.Propagate(err, "")
+ }
+ nextCursor := ""
+ if len(out) > limit {
+ nextCursor = formatMessageCursor(out[limit-1].LastMessage)
+ out = out[:limit]
+ }
+ return out, nextCursor, nil
+}
+
+func sprintfWallMessageColumns(viewerPlaceholder string) string {
+ return strings.TrimSpace(strings.ReplaceAll(wallMessageSelectColumns, "%s", viewerPlaceholder))
+}
+
+func scanMessageRecord(scanner interface{ Scan(dest ...any) error }) (*WallMessageRecord, error) {
+ var rec WallMessageRecord
+ dest := []any{
+ &rec.MessageID,
+ &rec.Kind,
+ &rec.SenderID,
+ &rec.SenderWallID,
+ &rec.RecipientID,
+ &rec.RecipientWallID,
+ &rec.MessageCipher,
+ &rec.EncryptedMessageKey,
+ &rec.ReplyPostID,
+ &rec.IsDeleted,
+ &rec.CreatedAt,
+ &rec.UpdatedAt,
+ }
+ dest = append(dest, wallActorScanDest(&rec.Sender)...)
+ dest = append(dest, wallActorScanDest(&rec.Recipient)...)
+ if err := scanner.Scan(dest...); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return &rec, nil
+}
+
+func parseMessageCursor(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 formatMessageCursor(message WallMessageRecord) string {
+ return strconv.FormatInt(message.CreatedAt, 10) + ":" + message.MessageID
+}
diff --git a/server/wall/repo/module.go b/server/wall/repo/module.go
index 18c68c6e5a..a643cf5dcf 100644
--- a/server/wall/repo/module.go
+++ b/server/wall/repo/module.go
@@ -10,6 +10,7 @@ type Module struct {
Walls *WallsRepository
Posts *PostsRepository
Friends *FriendsRepository
+ Messages *MessagesRepository
Notifications *NotificationsRepository
Links *LinksRepository
Assets *AssetsRepository
@@ -27,6 +28,10 @@ type FriendsRepository struct {
DB *sql.DB
}
+type MessagesRepository struct {
+ DB *sql.DB
+}
+
type NotificationsRepository struct {
DB *sql.DB
}
@@ -108,6 +113,41 @@ type WallPostLikerRecord struct {
CreatedAt int64
}
+type WallMessageRecord struct {
+ MessageID string
+ Kind string
+ SenderID int64
+ SenderWallID string
+ RecipientID int64
+ RecipientWallID string
+ MessageCipher string
+ EncryptedMessageKey string
+ ReplyPostID sql.NullInt64
+ IsDeleted bool
+ CreatedAt int64
+ UpdatedAt int64
+ Sender WallActorRecord
+ Recipient WallActorRecord
+}
+
+type WallMessageConversationRecord struct {
+ Friend WallActorRecord
+ LastMessage WallMessageRecord
+}
+
+type CreateWallMessageRecord struct {
+ MessageID string
+ Kind string
+ SenderID int64
+ SenderWallID string
+ RecipientID int64
+ RecipientWallID string
+ MessageCipher string
+ SenderEncryptedMessageKey string
+ RecipientEncryptedMessageKey string
+ ReplyPostID sql.NullInt64
+}
+
type WallActorRecord struct {
UserID int64
WallID string
@@ -195,6 +235,7 @@ func NewModule(db *sql.DB, s3Config *s3config.S3Config) *Module {
Walls: &WallsRepository{DB: db},
Posts: &PostsRepository{DB: db},
Friends: &FriendsRepository{DB: db},
+ Messages: &MessagesRepository{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.go
index 411d3ea89a..adb82606a7 100644
--- a/server/wall/repo/module_test.go
+++ b/server/wall/repo/module_test.go
@@ -66,6 +66,63 @@ func TestUpdateSlugRejectsReservedSlug(t *testing.T) {
require.Equal(t, "rename-user", unchanged.WallSlug)
}
+func TestWallMessagesThreadAndConversations(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-messages", "alice-wall-key", "alice-profile")
+ require.NoError(t, err)
+ bobWall, err := module.Walls.CreateWall(ctx, bobID, "bob-messages", "bob-wall-key", "bob-profile")
+ require.NoError(t, err)
+
+ err = module.Friends.AddFriend(ctx, bobID, bobWall.WallID, aliceWall.WallID, "alice-share-key", aliceWall.CurrentVersion, "bob-share-key", bobWall.CurrentVersion)
+ require.NoError(t, err)
+
+ message, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{
+ Kind: "regular",
+ SenderID: bobID,
+ SenderWallID: bobWall.WallID,
+ RecipientID: aliceID,
+ RecipientWallID: aliceWall.WallID,
+ MessageCipher: "cipher",
+ SenderEncryptedMessageKey: "sender-key",
+ RecipientEncryptedMessageKey: "recipient-key",
+ })
+ require.NoError(t, err)
+ require.Equal(t, "regular", message.Kind)
+ require.Equal(t, "sender-key", message.EncryptedMessageKey)
+
+ aliceThread, nextCursor, err := module.Messages.ListThread(ctx, aliceID, bobWall.WallID, "", 10)
+ require.NoError(t, err)
+ require.Empty(t, nextCursor)
+ require.Len(t, aliceThread, 1)
+ require.Equal(t, "recipient-key", aliceThread[0].EncryptedMessageKey)
+ require.Equal(t, bobWall.WallID, aliceThread[0].Sender.WallID)
+
+ conversations, nextCursor, err := module.Messages.ListConversations(ctx, aliceID, "", 10)
+ require.NoError(t, err)
+ require.Empty(t, nextCursor)
+ require.Len(t, conversations, 1)
+ require.Equal(t, bobWall.WallID, conversations[0].Friend.WallID)
+ require.Equal(t, message.MessageID, conversations[0].LastMessage.MessageID)
+
+ _, err = module.Messages.CreateMessage(ctx, CreateWallMessageRecord{
+ Kind: "regular",
+ SenderID: bobID,
+ SenderWallID: bobWall.WallID,
+ RecipientID: aliceID,
+ RecipientWallID: aliceWall.WallID,
+ MessageCipher: "cipher",
+ SenderEncryptedMessageKey: "sender-key",
+ RecipientEncryptedMessageKey: "recipient-key",
+ ReplyPostID: sql.NullInt64{Int64: 1, Valid: true},
+ })
+ require.Error(t, err)
+}
+
func TestWallModuleLifecycle(t *testing.T) {
ctx := context.Background()
module := newWallTestModule(t)
@@ -825,11 +882,28 @@ func TestNotificationsIncludeWallSocialEvents(t *testing.T) {
require.NoError(t, err)
setFriendEventCreatedAt(t, module, 3000, "friend_add", bobID, aliceID)
- page, nextCursor, err := module.Notifications.List(ctx, aliceID, "", 3)
+ reply, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{
+ Kind: "post_reply",
+ SenderID: bobID,
+ SenderWallID: bobWall.WallID,
+ RecipientID: aliceID,
+ RecipientWallID: aliceWall.WallID,
+ MessageCipher: "reply-cipher",
+ SenderEncryptedMessageKey: "sender-reply-key",
+ RecipientEncryptedMessageKey: "recipient-reply-key",
+ ReplyPostID: sql.NullInt64{Int64: postID, Valid: true},
+ })
require.NoError(t, err)
- require.Len(t, page, 2)
- require.Equal(t, "addedYouAsFriend", page[0].Type)
- require.Equal(t, "likedPost", page[1].Type)
+ setMessageCreatedAt(t, module, 3500, reply.MessageID)
+
+ page, nextCursor, err := module.Notifications.List(ctx, aliceID, "", 5)
+ require.NoError(t, err)
+ require.Len(t, page, 3)
+ require.Equal(t, "repliedToPost", page[0].Type)
+ require.Equal(t, bobID, page[0].Actor.UserID)
+ require.Equal(t, postID, page[0].PostID.Int64)
+ require.Equal(t, "addedYouAsFriend", page[1].Type)
+ require.Equal(t, "likedPost", page[2].Type)
require.Empty(t, nextCursor)
err = module.Friends.DeleteFriendship(ctx, aliceID, bobWall.WallID)
@@ -925,3 +999,9 @@ func setFriendEventCreatedAt(t *testing.T, module *Module, createdAt int64, even
_, err := module.Friends.DB.Exec(`UPDATE wall_friend_events SET created_at = $1 WHERE event_type = $2 AND actor_id = $3 AND target_id = $4`, createdAt, eventType, actorID, targetID)
require.NoError(t, err)
}
+
+func setMessageCreatedAt(t *testing.T, module *Module, createdAt int64, messageID string) {
+ t.Helper()
+ _, err := module.Messages.DB.Exec(`UPDATE wall_messages SET created_at = $1 WHERE message_id = $2`, createdAt, messageID)
+ require.NoError(t, err)
+}
diff --git a/server/wall/repo/notifications.go b/server/wall/repo/notifications.go
index 152cd6dacd..e9cefc6baa 100644
--- a/server/wall/repo/notifications.go
+++ b/server/wall/repo/notifications.go
@@ -40,7 +40,7 @@ const wallNotificationRows = `
JOIN walls actor_wall ON actor_wall.owner_id = pl.user_id
JOIN key_attributes actor_ka ON actor_ka.user_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
+ JOIN walls owner_wall ON owner_wall.wall_id = p.wall_id
JOIN key_attributes owner_ka ON owner_ka.user_id = p.owner_id
LEFT JOIN LATERAL (
SELECT object_key, size, position, variant, blur_hash_cipher, width, height, media_type
@@ -88,6 +88,56 @@ const wallNotificationRows = `
JOIN key_attributes actor_ka ON actor_ka.user_id = actor_wall.owner_id
WHERE fe.target_id = $1
AND fe.actor_id <> $1
+
+ UNION ALL
+
+ SELECT
+ 'post_reply:' || m.message_id AS notification_id,
+ 'repliedToPost' AS notification_type,
+ m.created_at,
+ actor_wall.owner_id, actor_wall.wall_id, actor_wall.wall_slug, actor_ka.public_key,
+ actor_wall.current_version, actor_wall.encrypted_profile, actor_wall.avatar_object_key,
+ actor_wall.avatar_size, actor_wall.updated_at,
+ (SELECT COUNT(*) FROM wall_friend_shares fs WHERE fs.wall_id = actor_wall.wall_id) AS actor_friends,
+ (SELECT COUNT(*) FROM wall_posts ap WHERE ap.wall_id = actor_wall.wall_id AND ap.is_deleted = FALSE) AS actor_posts,
+ 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.owner_id, owner_wall.wall_id, owner_wall.wall_slug, owner_ka.public_key,
+ owner_wall.current_version, owner_wall.encrypted_profile, owner_wall.avatar_object_key,
+ owner_wall.avatar_size, owner_wall.updated_at,
+ (SELECT COUNT(*) FROM wall_friend_shares fs WHERE fs.wall_id = owner_wall.wall_id) AS post_author_friends,
+ (SELECT COUNT(*) FROM wall_posts op WHERE op.wall_id = owner_wall.wall_id AND op.is_deleted = FALSE) AS post_author_posts,
+ asset.object_key AS post_object_key,
+ asset.size AS post_object_size,
+ asset.position AS post_object_position,
+ asset.variant AS post_object_variant,
+ asset.blur_hash_cipher AS post_object_blur_hash_cipher,
+ asset.width AS post_object_width,
+ asset.height AS post_object_height,
+ asset.media_type AS post_object_media_type
+ FROM wall_messages m
+ JOIN wall_posts p ON p.post_id = m.reply_post_id
+ JOIN walls actor_wall ON actor_wall.wall_id = m.sender_wall_id AND actor_wall.owner_id = m.sender_id
+ JOIN key_attributes actor_ka ON actor_ka.user_id = m.sender_id
+ JOIN walls post_wall ON post_wall.wall_id = p.wall_id
+ JOIN walls owner_wall ON owner_wall.wall_id = p.wall_id
+ JOIN key_attributes owner_ka ON owner_ka.user_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 m.recipient_id = $1
+ AND m.sender_id <> $1
+ AND m.kind = 'post_reply'
+ AND m.is_deleted = FALSE
+ AND m.reply_post_id IS NOT NULL
+ AND p.owner_id = $1
+ AND p.is_deleted = FALSE
`
func (r *NotificationsRepository) List(ctx context.Context, userID int64, cursor string, limit int) ([]WallNotificationRecord, string, error) {
diff --git a/web/apps/social/src/components/SocialFileViewer.tsx b/web/apps/social/src/components/SocialFileViewer.tsx
index cc476ed3b1..4e24780ed9 100644
--- a/web/apps/social/src/components/SocialFileViewer.tsx
+++ b/web/apps/social/src/components/SocialFileViewer.tsx
@@ -4,6 +4,7 @@ import {
FavouriteIcon,
Loading03Icon,
MoreHorizontalIcon,
+ Navigation03Icon,
Tick02Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -37,6 +38,9 @@ const dangerColor = "#F63A3A";
const viewerHeaderHeight = 56;
const viewerBottomPadding = 72;
const captionInputMinHeight = 40;
+const replyInputMinHeight = 48;
+const replyInputPadding = 14;
+const replyInputPaddingLeft = 18;
const captionInputMaxHeight = 112;
const defaultPhotoWidth = 900;
const defaultPhotoHeight = 680;
@@ -99,8 +103,10 @@ interface SocialFileViewerProps {
onOpenFriend?: (friendID: string) => void;
onOpenProfile?: () => void;
onPublishDraftPost?: (caption: string) => Promise<void>;
+ onReplyToPost?: (postId: number, text: string) => Promise<void>;
onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
photo: SocialViewerPhoto;
+ focusReplyOnOpen?: boolean;
postActionMode?: SocialViewerPostActionMode;
}
@@ -215,12 +221,15 @@ const HeartFilledIcon: React.FC = () => (
</svg>
);
-const resizeCaptionInput = (input: HTMLTextAreaElement | null) => {
+const resizeCaptionInput = (
+ input: HTMLTextAreaElement | null,
+ minHeight = captionInputMinHeight,
+) => {
if (!input) return;
- input.style.height = `${captionInputMinHeight}px`;
+ input.style.height = `${minHeight}px`;
const nextHeight = Math.min(input.scrollHeight, captionInputMaxHeight);
- input.style.height = `${Math.max(captionInputMinHeight, nextHeight)}px`;
+ input.style.height = `${Math.max(minHeight, nextHeight)}px`;
input.style.overflowY =
input.scrollHeight > captionInputMaxHeight ? "auto" : "hidden";
};
@@ -229,6 +238,7 @@ const wait = (durationMs: number) =>
new Promise((resolve) => window.setTimeout(resolve, durationMs));
export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
+ focusReplyOnOpen = false,
initialScreen = "photo",
onClose,
onDeletePost,
@@ -236,6 +246,7 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
onOpenFriend,
onOpenProfile,
onPublishDraftPost,
+ onReplyToPost,
onSetPostLiked,
photo,
postActionMode = "like-with-count",
@@ -257,6 +268,11 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
photo.viewerLiked ?? false,
);
const [caption, setCaption] = React.useState(photo.caption ?? "");
+ const [replyText, setReplyText] = React.useState("");
+ const [isReplyFocused, setIsReplyFocused] =
+ React.useState(focusReplyOnOpen);
+ const [replyActionPhase, setReplyActionPhase] =
+ React.useState<SocialActionPhase | null>(null);
const [serverLikeCount, setServerLikeCount] = React.useState(
photo.likeCount ?? 0,
);
@@ -269,6 +285,7 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
const initials = initialsFor(photo.name);
const viewerRootRef = React.useRef<HTMLDivElement | null>(null);
const captionInputRef = React.useRef<HTMLTextAreaElement | null>(null);
+ const replyInputRef = React.useRef<HTMLTextAreaElement | null>(null);
const likeHoldTimeoutRef = React.useRef<number | null>(null);
const likeHoldStartPointRef = React.useRef<{ x: number; y: number } | null>(
null,
@@ -289,6 +306,18 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
const isActionsOpen = Boolean(actionsAnchor);
const isDeleteActionRunning = deleteActionPhase != null;
const isDraftPostActionRunning = draftPostActionPhase != null;
+ const isReplyActionRunning = replyActionPhase != null;
+ const canReplyToPost = Boolean(
+ !isDraftPost && photo.postId && onReplyToPost,
+ );
+ const isReplyMode =
+ canReplyToPost &&
+ (isReplyFocused || replyText.trim().length > 0 || isReplyActionRunning);
+ const canSendReply =
+ canReplyToPost &&
+ Boolean(photo.postId) &&
+ replyText.trim().length > 0 &&
+ !isReplyActionRunning;
const clearLikeHoldTimeout = () => {
if (likeHoldTimeoutRef.current != null) {
@@ -461,6 +490,37 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
})();
};
+ const sendReply = () => {
+ const text = replyText.trim();
+ if (!canSendReply || !photo.postId || !onReplyToPost) return;
+
+ setReplyActionPhase("busy");
+ void (async () => {
+ try {
+ await Promise.all([
+ onReplyToPost(photo.postId!, text),
+ wait(socialActionBusyDurationMs),
+ ]);
+ setReplyText("");
+ setReplyActionPhase("done");
+ } catch (error) {
+ console.error("Failed to send post reply", error);
+ setReplyActionPhase(null);
+ }
+ })();
+ };
+
+ const handleReplyKeyDown = (event: React.KeyboardEvent) => {
+ if (event.key != "Enter" || event.shiftKey) return;
+
+ event.preventDefault();
+ sendReply();
+ };
+
+ const handleReplyActionPointerDown = (event: React.PointerEvent) => {
+ event.preventDefault();
+ };
+
const openFriendProfile = (friendID: string) => {
onOpenFriend?.(friendID);
};
@@ -479,6 +539,17 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
resizeCaptionInput(captionInputRef.current);
}, [caption]);
+ React.useLayoutEffect(() => {
+ resizeCaptionInput(replyInputRef.current, replyInputMinHeight);
+ }, [replyText]);
+
+ React.useLayoutEffect(() => {
+ if (!focusReplyOnOpen || !canReplyToPost) return;
+
+ setIsReplyFocused(true);
+ replyInputRef.current?.focus();
+ }, [canReplyToPost, focusReplyOnOpen, photo.postId]);
+
React.useEffect(() => {
const suppressDelayedContextMenu = (event: MouseEvent) => {
if (!suppressNextLikeContextMenuRef.current) return;
@@ -525,9 +596,23 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
return () => window.clearTimeout(timeoutID);
}, [draftPostActionPhase]);
+ React.useEffect(() => {
+ if (replyActionPhase != "done") return;
+
+ const timeoutID = window.setTimeout(() => {
+ setReplyActionPhase(null);
+ setIsReplyFocused(false);
+ }, socialActionDoneDurationMs);
+
+ return () => window.clearTimeout(timeoutID);
+ }, [replyActionPhase]);
+
React.useEffect(() => {
setIsPhotoLiked(photo.viewerLiked ?? false);
setCaption(photo.caption ?? "");
+ setReplyText("");
+ setIsReplyFocused(focusReplyOnOpen && canReplyToPost);
+ setReplyActionPhase(null);
setServerLikeCount(photo.likeCount ?? 0);
setPhotoLikers([]);
setScreen(resolvedInitialScreen);
@@ -537,6 +622,8 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
photo.likeCount,
photo.postId,
photo.viewerLiked,
+ canReplyToPost,
+ focusReplyOnOpen,
resolvedInitialScreen,
]);
@@ -1167,46 +1254,188 @@ export const SocialFileViewer: React.FC<SocialFileViewerProps> = ({
<Box
data-social-viewer-bottom="true"
sx={{
+ alignItems: "flex-end",
bottom: "16px",
display: "flex",
- gap: "10px",
+ gap: "8px",
+ left: canReplyToPost ? { xs: "16px", sm: 0 } : "auto",
+ maxWidth: canReplyToPost ? { sm: 390 } : undefined,
+ mx: canReplyToPost ? { sm: "auto" } : undefined,
position: "fixed",
right: "16px",
+ width: canReplyToPost
+ ? { sm: "calc(100% - 32px)" }
+ : undefined,
zIndex: 2,
}}
>
+ {canReplyToPost && (
+ <Box
+ ref={replyInputRef}
+ component="textarea"
+ aria-label="Reply to post"
+ disabled={isReplyActionRunning}
+ onBlur={() => setIsReplyFocused(false)}
+ onChange={(event) => {
+ setReplyText(event.target.value);
+ resizeCaptionInput(
+ event.currentTarget,
+ replyInputMinHeight,
+ );
+ }}
+ onFocus={() => setIsReplyFocused(true)}
+ onKeyDown={handleReplyKeyDown}
+ placeholder="Reply"
+ rows={1}
+ value={replyText}
+ sx={{
+ bgcolor: controlBackground,
+ border: 0,
+ borderRadius: "24px",
+ boxSizing: "border-box",
+ color: textBase,
+ flex: "1 1 auto",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ lineHeight: "20px",
+ maxHeight: captionInputMaxHeight,
+ minHeight: replyInputMinHeight,
+ minWidth: 0,
+ outline: 0,
+ overflow: "hidden",
+ pb: `${replyInputPadding}px`,
+ pl: `${replyInputPaddingLeft}px`,
+ pr: `${replyInputPadding}px`,
+ pt: `${replyInputPadding}px`,
+ resize: "none",
+ "&::placeholder": { color: textSecondary },
+ "&:disabled": { opacity: 0.74 },
+ "&:focus": { bgcolor: controlBackgroundActive },
+ }}
+ />
+ )}
<Box sx={{ height: 48, position: "relative", width: 48 }}>
<Box
component="button"
type="button"
aria-label={
- isPhotoLiked ? "Unlike photo" : "Like photo"
+ isReplyMode
+ ? replyActionPhase == "busy"
+ ? "Sending reply"
+ : replyActionPhase == "done"
+ ? "Reply sent"
+ : "Send reply"
+ : isPhotoLiked
+ ? "Unlike photo"
+ : "Like photo"
+ }
+ aria-pressed={
+ isReplyMode ? undefined : isPhotoLiked
+ }
+ aria-disabled={
+ isReplyMode && !canSendReply ? true : undefined
+ }
+ onClick={
+ isReplyMode ? sendReply : handlePhotoLikeClick
+ }
+ onContextMenuCapture={
+ isReplyMode
+ ? undefined
+ : handlePhotoLikeContextMenu
+ }
+ onPointerCancel={
+ isReplyMode ? undefined : clearLikeHoldTimeout
+ }
+ onPointerDown={
+ isReplyMode
+ ? handleReplyActionPointerDown
+ : startPhotoLikeHold
+ }
+ onPointerLeave={
+ isReplyMode ? undefined : clearLikeHoldTimeout
+ }
+ onPointerMove={
+ isReplyMode
+ ? undefined
+ : cancelPhotoLikeHoldOnMove
+ }
+ onPointerUp={
+ isReplyMode ? undefined : clearLikeHoldTimeout
}
- aria-pressed={isPhotoLiked}
- onClick={handlePhotoLikeClick}
- onContextMenuCapture={handlePhotoLikeContextMenu}
- onPointerCancel={clearLikeHoldTimeout}
- onPointerDown={startPhotoLikeHold}
- onPointerLeave={clearLikeHoldTimeout}
- onPointerMove={cancelPhotoLikeHoldOnMove}
- onPointerUp={clearLikeHoldTimeout}
sx={{
...viewerActionButtonSx,
+ bgcolor:
+ isReplyMode && canSendReply
+ ? "#FFFFFF"
+ : controlBackground,
+ color:
+ isReplyMode && canSendReply
+ ? "#111111"
+ : controlIcon,
+ opacity:
+ isReplyMode && !canSendReply
+ ? replyActionPhase == "done"
+ ? 1
+ : 0.52
+ : 1,
+ cursor:
+ isReplyMode && !canSendReply
+ ? "default"
+ : "pointer",
touchAction: "manipulation",
userSelect: "none",
WebkitTouchCallout: "none",
WebkitUserSelect: "none",
}}
>
- <HugeiconsIcon
- fill={isPhotoLiked ? green : "none"}
- icon={FavouriteIcon}
- primaryColor={isPhotoLiked ? green : undefined}
- size={26}
- strokeWidth={1.8}
- />
+ {isReplyMode ? (
+ replyActionPhase == "busy" ? (
+ <Box
+ component="span"
+ sx={{
+ animation: `${postButtonSpin} 2.4s linear infinite`,
+ display: "flex",
+ lineHeight: 0,
+ }}
+ >
+ <HugeiconsIcon
+ icon={Loading03Icon}
+ size={22}
+ strokeWidth={1.8}
+ />
+ </Box>
+ ) : replyActionPhase == "done" ? (
+ <HugeiconsIcon
+ icon={Tick02Icon}
+ primaryColor={green}
+ size={22}
+ strokeWidth={1.8}
+ />
+ ) : (
+ <HugeiconsIcon
+ icon={Navigation03Icon}
+ size={24}
+ strokeWidth={1.8}
+ style={{
+ transform: "translate(-1px, 1px)",
+ }}
+ />
+ )
+ ) : (
+ <HugeiconsIcon
+ fill={isPhotoLiked ? green : "none"}
+ icon={FavouriteIcon}
+ primaryColor={
+ isPhotoLiked ? green : undefined
+ }
+ size={26}
+ strokeWidth={1.8}
+ />
+ )}
</Box>
- {showPhotoLikeCount && (
+ {!isReplyMode && showPhotoLikeCount && (
<Box
component="button"
type="button"
diff --git a/web/apps/social/src/pages/app/index.tsx b/web/apps/social/src/pages/app/index.tsx
index 5ec95b1387..e5752197f3 100644
--- a/web/apps/social/src/pages/app/index.tsx
+++ b/web/apps/social/src/pages/app/index.tsx
@@ -10,6 +10,7 @@ import {
loadCurrentFeedPage,
loadCurrentPostLikers,
loadCurrentWallFriends,
+ replyToCurrentPost,
setCurrentPostLiked,
type SocialWallPost,
} from "services/socialWall";
@@ -117,6 +118,7 @@ const Page: React.FC = () => {
}
onOpenProfile={() => void router.push(socialRoutes.profile)}
onLoadPostLikers={loadCurrentPostLikers}
+ onReplyToPost={replyToCurrentPost}
onSetPostLiked={setCurrentPostLiked}
onShareProfileLink={async () => {
if (!profile?.wallId) throw new Error("Missing wall.");
diff --git a/web/apps/social/src/pages/app/messages.tsx b/web/apps/social/src/pages/app/messages.tsx
new file mode 100644
index 0000000000..8fd510dfc1
--- /dev/null
+++ b/web/apps/social/src/pages/app/messages.tsx
@@ -0,0 +1,107 @@
+import { SocialPageMeta } from "components/SocialPageMeta";
+import { SocialRouteFallback } from "components/SocialRouteFallback";
+import { useRouter } from "next/router";
+import React from "react";
+import { MessagesScreen, messagesBackground } from "screens/MessagesScreen";
+import {
+ loadCurrentMessageConversations,
+ loadCurrentMessageThread,
+ sendCurrentMessage,
+ type SocialWallMessage,
+ type SocialWallMessageConversation,
+} from "services/socialWall";
+import { useSocialAppState } from "state/socialAppState";
+import { socialRoutes } from "utils/socialRoutes";
+
+const Page: React.FC = () => {
+ const router = useRouter();
+ const { profile, profileLoadStatus } = useSocialAppState();
+ const [conversations, setConversations] = React.useState<
+ SocialWallMessageConversation[]
+ >([]);
+ const [isConversationsLoading, setIsConversationsLoading] =
+ React.useState(true);
+ const [isThreadLoading, setIsThreadLoading] = React.useState(false);
+ const [messages, setMessages] = React.useState<SocialWallMessage[]>([]);
+ const [selectedFriend, setSelectedFriend] = React.useState<
+ SocialWallMessageConversation["friend"] | undefined
+ >();
+
+ const refreshConversations = React.useCallback(() => {
+ setIsConversationsLoading(true);
+ void loadCurrentMessageConversations()
+ .then((page) => setConversations(page.items))
+ .catch((error: unknown) =>
+ console.error("Failed to load message conversations", error),
+ )
+ .finally(() => setIsConversationsLoading(false));
+ }, []);
+
+ React.useEffect(() => {
+ if (profileLoadStatus == "ready" && !profile) {
+ void router.replace(socialRoutes.onboarding);
+ }
+ }, [profile, profileLoadStatus, router]);
+
+ React.useEffect(() => {
+ if (!profile) return;
+ refreshConversations();
+ }, [profile, refreshConversations]);
+
+ React.useEffect(() => {
+ if (!selectedFriend) {
+ setMessages([]);
+ return;
+ }
+
+ let cancelled = false;
+ setIsThreadLoading(true);
+ void loadCurrentMessageThread(
+ selectedFriend.wallId ?? selectedFriend.id,
+ )
+ .then((page) => {
+ if (!cancelled) setMessages(page.items);
+ })
+ .catch((error: unknown) =>
+ console.error("Failed to load message thread", error),
+ )
+ .finally(() => {
+ if (!cancelled) setIsThreadLoading(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [selectedFriend]);
+
+ if (profileLoadStatus == "loading" || !profile) {
+ return <SocialRouteFallback background={messagesBackground} />;
+ }
+
+ return (
+ <>
+ <SocialPageMeta themeColor={messagesBackground} />
+ <MessagesScreen
+ conversations={conversations}
+ isConversationsLoading={isConversationsLoading}
+ isThreadLoading={isThreadLoading}
+ messages={messages}
+ onBack={() => void router.push(socialRoutes.notifications)}
+ onCloseThread={() => setSelectedFriend(undefined)}
+ onOpenThread={setSelectedFriend}
+ onSendMessage={async (wallId, text) => {
+ const message = await sendCurrentMessage(wallId, text);
+ setMessages((currentMessages) => [
+ ...currentMessages,
+ message,
+ ]);
+ refreshConversations();
+ }}
+ profile={profile}
+ selectedFriend={selectedFriend}
+ />
+ </>
+ );
+};
+
+export default Page;
diff --git a/web/apps/social/src/pages/app/notifications.tsx b/web/apps/social/src/pages/app/notifications.tsx
index 6a857acc26..aa5c061a58 100644
--- a/web/apps/social/src/pages/app/notifications.tsx
+++ b/web/apps/social/src/pages/app/notifications.tsx
@@ -72,6 +72,7 @@ const Page: React.FC = () => {
socialRoutes.friend(friendID, "notifications"),
)
}
+ onOpenMessages={() => void router.push(socialRoutes.messages)}
onLoadPostLikers={loadCurrentPostLikers}
onSetPostLiked={setCurrentPostLiked}
profile={profile}
diff --git a/web/apps/social/src/screens/HomeScreen.tsx b/web/apps/social/src/screens/HomeScreen.tsx
index 461b9f4ae2..b6c5c71303 100644
--- a/web/apps/social/src/screens/HomeScreen.tsx
+++ b/web/apps/social/src/screens/HomeScreen.tsx
@@ -48,8 +48,29 @@ const headerIconSize = 23;
const headerSideWidth = headerActionSize * 2 + headerActionGap;
const feedLikeActionInset = 4;
const feedLikeActionSize = 40;
+const feedActionIconSize = 23;
+const feedReplyIconSize = 20;
const emptyFeedItemGap = "22px";
+const FeedReplyIcon: React.FC = () => (
+ <svg
+ width={feedReplyIconSize}
+ height={feedReplyIconSize}
+ viewBox="0 0 12 9"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M4.5241 0.242677C4.62341 0.34442 4.67919 0.482337 4.67919 0.626134C4.67919 0.76993 4.62341 0.907847 4.5241 1.00959L1.89369 3.70102H7.68483C8.3587 3.70102 9.35854 3.9036 10.2042 4.52653C11.0775 5.17045 11.7507 6.23762 11.7507 7.86116C11.7507 8.00507 11.6948 8.14309 11.5953 8.24485C11.4959 8.34661 11.361 8.40378 11.2203 8.40378C11.0797 8.40378 10.9448 8.34661 10.8453 8.24485C10.7459 8.14309 10.69 8.00507 10.69 7.86116C10.69 6.59069 10.1844 5.84982 9.58481 5.40776C8.95761 4.94544 8.18899 4.78627 7.68483 4.78627H1.89369L4.5241 7.4777C4.5762 7.52738 4.61799 7.58728 4.64698 7.65384C4.67597 7.72041 4.69155 7.79226 4.69281 7.86512C4.69406 7.93798 4.68096 8.01035 4.65429 8.07791C4.62762 8.14548 4.58792 8.20686 4.53756 8.25839C4.4872 8.30991 4.42722 8.35053 4.36118 8.37782C4.29515 8.40512 4.22442 8.41852 4.15321 8.41723C4.082 8.41595 4.01178 8.4 3.94673 8.37034C3.88167 8.34068 3.82313 8.29792 3.77457 8.24461L0.23908 4.6271C0.139767 4.52536 0.0839844 4.38744 0.0839844 4.24364C0.0839844 4.09985 0.139767 3.96193 0.23908 3.86019L3.77457 0.242677C3.87401 0.141061 4.0088 0.0839844 4.14934 0.0839844C4.28987 0.0839844 4.42466 0.141061 4.5241 0.242677Z"
+ fill="currentColor"
+ stroke="currentColor"
+ strokeWidth="0.166667"
+ />
+ </svg>
+);
+
interface HomeScreenProps {
addedFriendToastName?: string;
feedItems: SocialWallPost[];
@@ -64,6 +85,7 @@ interface HomeScreenProps {
onOpenNotifications?: () => void;
onOpenProfile?: () => void;
onLoadPostLikers?: (postId: number) => Promise<SocialLiker[]>;
+ onReplyToPost?: (postId: number, text: string) => Promise<void>;
onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
onShareProfileLink?: () => Promise<string>;
profile: SetupProfile;
@@ -76,6 +98,7 @@ interface FeedPhotoDimensions {
interface SelectedHomeViewer {
draftImage?: PreparedSocialPostImage;
+ focusReplyOnOpen?: boolean;
initialScreen: SocialViewerInitialScreen;
localObjectUrl?: string;
photo: SocialViewerPhoto;
@@ -85,6 +108,7 @@ interface SelectedHomeViewer {
interface FeedItemProps {
aspectRatio: number;
avatarUrl?: string | null;
+ caption?: string;
friendID: string;
imageUrl: string;
likeCount: number;
@@ -93,6 +117,7 @@ interface FeedItemProps {
onOpenPhoto?: (
photo: SocialViewerPhoto,
initialScreen?: SocialViewerInitialScreen,
+ focusReplyOnOpen?: boolean,
) => void;
onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
postId: number;
@@ -118,6 +143,7 @@ const dimensionsFromAspectRatio = (
const FeedItem: React.FC<FeedItemProps> = ({
aspectRatio,
avatarUrl,
+ caption,
friendID,
imageUrl,
likeCount,
@@ -131,11 +157,9 @@ const FeedItem: React.FC<FeedItemProps> = ({
}) => {
const [isLiked, setIsLiked] = useState(viewerLiked);
const [localLikeCount, setLocalLikeCount] = useState(likeCount);
- const [isLikeButtonPopping, setIsLikeButtonPopping] = useState(false);
const firstName = firstNameFrom(name);
const dateLabel = formatSocialDate(timestampMs);
const openFriend = () => onOpenFriend?.(friendID);
- const likePopTimeoutRef = React.useRef<number | null>(null);
const [loadedPhotoDimensions, setLoadedPhotoDimensions] =
useState<FeedPhotoDimensions | null>(null);
const photoDimensions =
@@ -157,11 +181,15 @@ const FeedItem: React.FC<FeedItemProps> = ({
return { height: naturalHeight, width: naturalWidth };
});
};
- const openPhoto = (initialScreen?: SocialViewerInitialScreen) =>
+ const openPhoto = (
+ initialScreen?: SocialViewerInitialScreen,
+ focusReplyOnOpen = false,
+ ) =>
onOpenPhoto?.(
{
alt: `${name} post`,
avatarUrl,
+ caption,
friendID,
height: photoDimensions.height,
imageUrl,
@@ -173,12 +201,9 @@ const FeedItem: React.FC<FeedItemProps> = ({
width: photoDimensions.width,
},
initialScreen,
+ focusReplyOnOpen,
);
const handleLikeClick = () => {
- if (likePopTimeoutRef.current != null)
- window.clearTimeout(likePopTimeoutRef.current);
-
- setIsLikeButtonPopping(true);
const nextLiked = !isLiked;
setIsLiked(nextLiked);
setLocalLikeCount((count) => Math.max(0, count + (nextLiked ? 1 : -1)));
@@ -189,10 +214,6 @@ const FeedItem: React.FC<FeedItemProps> = ({
Math.max(0, count + (nextLiked ? -1 : 1)),
);
});
- likePopTimeoutRef.current = window.setTimeout(() => {
- likePopTimeoutRef.current = null;
- setIsLikeButtonPopping(false);
- }, 120);
};
React.useEffect(() => {
@@ -203,14 +224,6 @@ const FeedItem: React.FC<FeedItemProps> = ({
setLocalLikeCount(likeCount);
}, [likeCount]);
- React.useEffect(
- () => () => {
- if (likePopTimeoutRef.current != null)
- window.clearTimeout(likePopTimeoutRef.current);
- },
- [],
- );
-
return (
<Box
component="article"
@@ -387,6 +400,38 @@ const FeedItem: React.FC<FeedItemProps> = ({
}}
/>
</Box>
+ <Box
+ component="button"
+ type="button"
+ aria-label={`Reply to ${firstName}'s post`}
+ onClick={() => openPhoto("photo", true)}
+ sx={{
+ alignItems: "center",
+ appearance: "none",
+ bgcolor: "transparent",
+ border: 0,
+ borderRadius: "50%",
+ bottom: feedLikeActionInset,
+ color: "#FFFFFF",
+ cursor: "pointer",
+ display: "inline-flex",
+ height: feedLikeActionSize,
+ justifyContent: "center",
+ p: 0,
+ position: "absolute",
+ right: feedLikeActionInset + feedLikeActionSize - 4,
+ transition: "color 120ms ease, transform 120ms ease",
+ width: feedLikeActionSize,
+ zIndex: 1,
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ "&:hover": { bgcolor: "transparent" },
+ }}
+ >
+ <FeedReplyIcon />
+ </Box>
<Box
component="button"
type="button"
@@ -408,10 +453,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
p: 0,
position: "absolute",
right: feedLikeActionInset,
- transform: isLikeButtonPopping
- ? "scale(0.96)"
- : "scale(1)",
- transition: "color 120ms ease, transform 120ms ease",
+ transition: "color 120ms ease",
width: feedLikeActionSize,
zIndex: 1,
"&:focus-visible": {
@@ -425,7 +467,7 @@ const FeedItem: React.FC<FeedItemProps> = ({
fill={isLiked ? green : "none"}
icon={FavouriteIcon}
primaryColor={isLiked ? green : "#FFFFFF"}
- size={23}
+ size={feedActionIconSize}
strokeWidth={1.8}
/>
</Box>
@@ -544,6 +586,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
onOpenFriend,
onOpenNotifications,
onOpenProfile,
+ onReplyToPost,
onSetPostLiked,
onShareProfileLink,
profile,
@@ -572,8 +615,10 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
const openFeedPhoto = (
photo: SocialViewerPhoto,
initialScreen: SocialViewerInitialScreen = "photo",
+ focusReplyOnOpen = false,
) => {
setSelectedViewer({
+ focusReplyOnOpen,
initialScreen,
photo,
postActionMode: "like-only",
@@ -882,6 +927,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
: 1
}
avatarUrl={item.avatarUrl ?? ""}
+ caption={item.caption}
friendID={item.friendID}
imageUrl={item.imageUrl}
likeCount={item.likeCount}
@@ -985,6 +1031,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
{selectedViewer && (
<SocialFileViewer
initialScreen={selectedViewer.initialScreen}
+ focusReplyOnOpen={selectedViewer.focusReplyOnOpen}
photo={selectedViewer.photo}
postActionMode={
selectedViewer.postActionMode ?? "like-with-count"
@@ -1007,6 +1054,11 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({
: undefined
}
onLoadPostLikers={onLoadPostLikers}
+ onReplyToPost={
+ selectedViewer.photo.friendID != profile.wallId
+ ? onReplyToPost
+ : undefined
+ }
onPublishDraftPost={
selectedViewer.draftImage && onCreatePost
? async (caption) => {
diff --git a/web/apps/social/src/screens/MessagesScreen.tsx b/web/apps/social/src/screens/MessagesScreen.tsx
new file mode 100644
index 0000000000..426e4ed73e
--- /dev/null
+++ b/web/apps/social/src/screens/MessagesScreen.tsx
@@ -0,0 +1,905 @@
+import {
+ ArrowLeft02Icon,
+ Loading03Icon,
+ Navigation03Icon,
+ Tick02Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { Box } from "@mui/material";
+import { keyframes } from "@mui/material/styles";
+import { SocialLoadingSpinner } from "components/SocialRouteFallback";
+import { formatTimeAgo } from "ente-base/date";
+import React from "react";
+import type { SetupProfile } from "screens/SetupProfileScreen";
+import type {
+ SocialWallMessage,
+ SocialWallMessageConversation,
+} from "services/socialWall";
+import { firstNameFrom, initialsFor } from "utils/socialDisplay";
+
+export const messagesBackground = "#FFFFFF";
+
+const green = "#08C225";
+const paleGreen = "#E7F6E9";
+const textBase = "#000000";
+const textSecondary = "#777777";
+const threadBackground = "#202020";
+const threadSurface = "#2C2C2C";
+const threadSurfaceHover = "#343434";
+const outgoingBubble = "#3FA43D";
+const incomingBubble = "#2C2C2C";
+const threadText = "#F4F4F4";
+const threadMuted = "rgba(244, 244, 244, 0.54)";
+const threadTimestamp = "rgba(255, 255, 255, 0.55)";
+const composerHeight = 48;
+const composerMaxHeight = 112;
+const composerPadding = 14;
+const composerPaddingLeft = 18;
+const messageGroupTimeThresholdMs = 10 * 60 * 1000;
+
+const sendSpin = keyframes`
+ from {
+ transform: rotate(0deg);
+ }
+
+ to {
+ transform: rotate(360deg);
+ }
+`;
+
+interface MessagesScreenProps {
+ conversations: SocialWallMessageConversation[];
+ isConversationsLoading?: boolean;
+ isThreadLoading?: boolean;
+ messages: SocialWallMessage[];
+ onBack?: () => void;
+ onCloseThread: () => void;
+ onOpenThread: (friend: SocialWallMessageConversation["friend"]) => void;
+ onSendMessage: (wallId: string, text: string) => Promise<void>;
+ profile: SetupProfile;
+ selectedFriend?: SocialWallMessageConversation["friend"];
+}
+
+const microsForTimestamp = (timestampMs: number) => timestampMs * 1000;
+
+const resizeComposer = (input: HTMLTextAreaElement | null) => {
+ if (!input) return;
+
+ input.style.height = `${composerHeight}px`;
+ const nextHeight = Math.min(input.scrollHeight, composerMaxHeight);
+ input.style.height = `${Math.max(composerHeight, nextHeight)}px`;
+ input.style.overflowY =
+ input.scrollHeight > composerMaxHeight ? "auto" : "hidden";
+};
+
+const Avatar: React.FC<{
+ avatarUrl?: string | null;
+ name: string;
+ size: number;
+}> = ({ avatarUrl, name, size }) => (
+ <Box
+ sx={{
+ alignItems: "center",
+ bgcolor: avatarUrl ? "transparent" : paleGreen,
+ borderRadius: "50%",
+ color: green,
+ display: "flex",
+ flexShrink: 0,
+ height: size,
+ justifyContent: "center",
+ overflow: "hidden",
+ width: size,
+ }}
+ >
+ {avatarUrl ? (
+ <Box
+ component="img"
+ alt=""
+ src={avatarUrl}
+ sx={{
+ display: "block",
+ height: "100%",
+ objectFit: "cover",
+ objectPosition: "center",
+ width: "100%",
+ }}
+ />
+ ) : (
+ <Box
+ sx={{
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: Math.max(10, Math.round(size * 0.34)),
+ fontWeight: 800,
+ lineHeight: 1,
+ }}
+ >
+ {initialsFor(name)}
+ </Box>
+ )}
+ </Box>
+);
+
+const messagePreview = (message: SocialWallMessage) => {
+ if (message.kind == "post_reply") {
+ return message.text ? `Reply: ${message.text}` : "Replied to a post";
+ }
+ return message.text;
+};
+
+const sameMessageSender = (
+ first: SocialWallMessage | undefined,
+ second: SocialWallMessage | undefined,
+) => Boolean(first && second && first.sender.wallId == second.sender.wallId);
+
+const QuotePreview: React.FC<{
+ isOwn: boolean;
+ message: SocialWallMessage;
+}> = ({ isOwn, message }) => {
+ if (message.kind != "post_reply") return null;
+ const quote = message.quote;
+ const isUnavailable = !quote || quote.isUnavailable || !quote.imageUrl;
+
+ return (
+ <Box
+ sx={{
+ alignItems: "stretch",
+ display: "flex",
+ gap: "10px",
+ mb: "8px",
+ maxWidth: "100%",
+ minWidth: 0,
+ }}
+ >
+ <Box
+ aria-hidden
+ sx={{
+ alignSelf: "stretch",
+ bgcolor: isOwn ? "rgba(255, 255, 255, 0.55)" : "#8C8C8C",
+ borderRadius: "999px",
+ flexShrink: 0,
+ width: 3,
+ }}
+ />
+ <Box
+ sx={{
+ alignItems: "center",
+ display: "grid",
+ gap: "10px",
+ gridTemplateColumns: "minmax(0, 1fr) 44px",
+ minWidth: 0,
+ width: "100%",
+ }}
+ >
+ <Box sx={{ minWidth: 0 }}>
+ <Box
+ sx={{
+ color: "rgba(244, 244, 244, 0.92)",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 12,
+ fontWeight: 750,
+ lineHeight: "18px",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ }}
+ >
+ Post
+ </Box>
+ <Box
+ sx={{
+ color: "rgba(244, 244, 244, 0.82)",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 12,
+ fontWeight: 500,
+ lineHeight: "17px",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {isUnavailable
+ ? "(deleted)"
+ : quote?.caption || "Photo"}
+ </Box>
+ </Box>
+ {isUnavailable ? (
+ <Box
+ sx={{
+ bgcolor: "rgba(255, 255, 255, 0.08)",
+ borderRadius: "6px",
+ height: 44,
+ width: 44,
+ }}
+ />
+ ) : (
+ <Box
+ component="img"
+ alt=""
+ src={quote.imageUrl}
+ sx={{
+ borderRadius: "6px",
+ display: "block",
+ height: 44,
+ objectFit: "cover",
+ objectPosition: "center",
+ width: 44,
+ }}
+ />
+ )}
+ </Box>
+ </Box>
+ );
+};
+
+const MessageBubble: React.FC<{
+ isLastInSequence: boolean;
+ message: SocialWallMessage;
+ ownWallID?: string;
+ showTimestamp: boolean;
+}> = ({
+ isLastInSequence,
+ message,
+ ownWallID,
+ showTimestamp,
+}) => {
+ const isOwn = message.sender.wallId == ownWallID;
+ const timestampLabel = formatTimeAgo(
+ microsForTimestamp(message.createdAtMs),
+ );
+ const timestampDateTime = new Date(
+ Math.floor(microsForTimestamp(message.createdAtMs) / 1000),
+ ).toISOString();
+ const bubbleBorderRadius = isOwn
+ ? isLastInSequence
+ ? "20px 6px 20px 20px"
+ : "20px 6px 6px 20px"
+ : isLastInSequence
+ ? "6px 20px 20px 20px"
+ : "6px 20px 20px 6px";
+
+ return (
+ <Box
+ component="li"
+ sx={{
+ alignItems: isOwn ? "flex-end" : "flex-start",
+ display: "flex",
+ flexDirection: "column",
+ listStyle: "none",
+ mb: isLastInSequence ? "24px" : "6px",
+ maxWidth: "100%",
+ minWidth: 0,
+ position: "relative",
+ width: "100%",
+ zIndex: "auto",
+ }}
+ >
+ <Box
+ className={isOwn ? "green-bg" : undefined}
+ sx={{
+ bgcolor: isOwn ? outgoingBubble : incomingBubble,
+ borderRadius: bubbleBorderRadius,
+ color: threadText,
+ display: "block",
+ maxWidth: "min(calc(100vw - 72px), 360px)",
+ minWidth: 0,
+ ml: 0,
+ overflow: "visible",
+ position: "relative",
+ px: "16px",
+ py: message.kind == "post_reply" ? "16px" : "14px",
+ textAlign: "left",
+ width: "fit-content",
+ "&:hover": {
+ bgcolor: isOwn ? outgoingBubble : threadSurfaceHover,
+ },
+ }}
+ >
+ <QuotePreview isOwn={isOwn} message={message} />
+ <Box
+ sx={{
+ color: "rgba(244, 244, 244, 0.94)",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 600,
+ lineHeight: "21px",
+ overflowWrap: "anywhere",
+ whiteSpace: "pre-wrap",
+ }}
+ >
+ {message.text}
+ </Box>
+ </Box>
+ {showTimestamp && (
+ <Box
+ component="time"
+ dateTime={timestampDateTime}
+ sx={{
+ color: threadTimestamp,
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 12,
+ fontWeight: 600,
+ lineHeight: "16px",
+ ml: isOwn ? 0 : "2px",
+ mt: "6px",
+ mr: isOwn ? "2px" : 0,
+ }}
+ >
+ {timestampLabel}
+ </Box>
+ )}
+ </Box>
+ );
+};
+
+export const MessagesScreen: React.FC<MessagesScreenProps> = ({
+ conversations,
+ isConversationsLoading = false,
+ isThreadLoading = false,
+ messages,
+ onBack,
+ onCloseThread,
+ onOpenThread,
+ onSendMessage,
+ profile,
+ selectedFriend,
+}) => {
+ const [messageText, setMessageText] = React.useState("");
+ const [sendPhase, setSendPhase] = React.useState<
+ "done" | "idle" | "sending"
+ >("idle");
+ const composerRef = React.useRef<HTMLTextAreaElement | null>(null);
+ const threadScrollRef = React.useRef<HTMLDivElement | null>(null);
+ const isThreadOpen = Boolean(selectedFriend);
+ const canSend = messageText.trim().length > 0 && sendPhase == "idle";
+ const selectedName = selectedFriend
+ ? selectedFriend.fullName.trim() || selectedFriend.username
+ : "";
+ const isSendStatus = sendPhase != "idle";
+ const isSendButtonActive = canSend || isSendStatus;
+
+ const sendMessage = () => {
+ const text = messageText.trim();
+ if (!selectedFriend || !canSend) return;
+ setSendPhase("sending");
+ void onSendMessage(selectedFriend.wallId ?? selectedFriend.id, text)
+ .then(() => {
+ setMessageText("");
+ setSendPhase("done");
+ window.setTimeout(() => setSendPhase("idle"), 900);
+ })
+ .catch((error: unknown) => {
+ console.error("Failed to send message", error);
+ setSendPhase("idle");
+ });
+ };
+
+ const handleComposerKeyDown = (event: React.KeyboardEvent) => {
+ if (event.key != "Enter" || event.shiftKey) return;
+
+ event.preventDefault();
+ sendMessage();
+ };
+
+ React.useLayoutEffect(() => {
+ resizeComposer(composerRef.current);
+ }, [messageText]);
+
+ React.useLayoutEffect(() => {
+ if (!selectedFriend || isThreadLoading) return;
+
+ const scroller = threadScrollRef.current;
+ if (!scroller) return;
+
+ scroller.scrollTop = scroller.scrollHeight;
+ }, [isThreadLoading, messages.length, selectedFriend]);
+
+ return (
+ <Box
+ component="main"
+ sx={{
+ bgcolor: isThreadOpen ? threadBackground : messagesBackground,
+ color: isThreadOpen ? threadText : textBase,
+ display: "grid",
+ minHeight: "100svh",
+ overflowX: "hidden",
+ placeItems: { xs: "stretch", sm: "start center" },
+ }}
+ >
+ <Box
+ sx={{
+ bgcolor: "inherit",
+ boxSizing: "border-box",
+ minHeight: "100svh",
+ mx: "auto",
+ position: "relative",
+ width: "100%",
+ "@media (min-width: 600px)": { maxWidth: 390 },
+ }}
+ >
+ <Box
+ component="header"
+ sx={{
+ alignItems: "center",
+ display: "grid",
+ gridTemplateColumns: "24px 1fr 24px",
+ height: 56,
+ px: 2,
+ width: "100%",
+ }}
+ >
+ <Box
+ component="button"
+ type="button"
+ aria-label={isThreadOpen ? "Back to messages" : "Back"}
+ onClick={isThreadOpen ? onCloseThread : onBack}
+ sx={{
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ color: "inherit",
+ cursor:
+ isThreadOpen || onBack ? "pointer" : "default",
+ display: "flex",
+ height: 24,
+ justifyContent: "flex-start",
+ ml: "-2px",
+ p: 0,
+ width: 24,
+ "&:focus-visible": {
+ borderRadius: "50%",
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ }}
+ >
+ <HugeiconsIcon
+ icon={ArrowLeft02Icon}
+ size={24}
+ strokeWidth={1.8}
+ />
+ </Box>
+ <Box
+ component="h1"
+ sx={{
+ color: "inherit",
+ fontFamily: '"Inter Variable", Inter, sans-serif',
+ fontSize: 18,
+ fontWeight: 700,
+ justifySelf: "center",
+ lineHeight: "24px",
+ m: 0,
+ minWidth: 0,
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {isThreadOpen
+ ? firstNameFrom(selectedName)
+ : "Messages"}
+ </Box>
+ <Box aria-hidden />
+ </Box>
+
+ {isThreadOpen && selectedFriend ? (
+ <>
+ <Box
+ ref={threadScrollRef}
+ sx={{
+ boxSizing: "border-box",
+ height: "calc(100svh - 56px - 72px - env(safe-area-inset-bottom))",
+ overflowY: "auto",
+ px: "14px",
+ py: "12px",
+ }}
+ >
+ {isThreadLoading ? (
+ <Box
+ sx={{
+ alignItems: "center",
+ display: "flex",
+ height: "100%",
+ justifyContent: "center",
+ }}
+ >
+ <SocialLoadingSpinner ariaLabel="Loading messages" />
+ </Box>
+ ) : (
+ <Box
+ component="ol"
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ listStyle: "none",
+ m: 0,
+ p: 0,
+ }}
+ >
+ {messages.map((message, index) => {
+ const nextMessage =
+ messages[index + 1];
+ const isSameSequenceAsNext =
+ sameMessageSender(
+ message,
+ nextMessage,
+ ) &&
+ nextMessage!.createdAtMs -
+ message.createdAtMs <=
+ messageGroupTimeThresholdMs;
+ const isLastInSequence =
+ !isSameSequenceAsNext;
+
+ return (
+ <MessageBubble
+ key={message.id}
+ isLastInSequence={
+ isLastInSequence
+ }
+ message={message}
+ ownWallID={profile.wallId}
+ showTimestamp={
+ isLastInSequence
+ }
+ />
+ );
+ })}
+ </Box>
+ )}
+ </Box>
+ <Box
+ sx={{
+ alignItems: "flex-end",
+ bgcolor: threadBackground,
+ bottom: 0,
+ boxSizing: "border-box",
+ display: "flex",
+ gap: "8px",
+ left: 0,
+ maxWidth: { sm: 390 },
+ mx: { sm: "auto" },
+ p: "10px 14px calc(10px + env(safe-area-inset-bottom))",
+ position: "fixed",
+ right: 0,
+ width: "100%",
+ }}
+ >
+ <Box
+ ref={composerRef}
+ component="textarea"
+ aria-label={`Message ${selectedName}`}
+ onChange={(event) => {
+ setMessageText(event.target.value);
+ resizeComposer(event.currentTarget);
+ }}
+ onKeyDown={handleComposerKeyDown}
+ placeholder="Message"
+ rows={1}
+ value={messageText}
+ sx={{
+ bgcolor: threadSurface,
+ border: 0,
+ borderRadius: "24px",
+ boxSizing: "border-box",
+ color: threadText,
+ flex: "1 1 auto",
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 600,
+ lineHeight: "20px",
+ maxHeight: composerMaxHeight,
+ minHeight: composerHeight,
+ minWidth: 0,
+ outline: 0,
+ overflow: "hidden",
+ pb: `${composerPadding}px`,
+ pl: `${composerPaddingLeft}px`,
+ pr: `${composerPadding}px`,
+ pt: `${composerPadding}px`,
+ resize: "none",
+ "&::placeholder": { color: threadMuted },
+ "&:focus": { bgcolor: threadSurfaceHover },
+ }}
+ />
+ <Box
+ component="button"
+ type="button"
+ aria-label={
+ sendPhase == "sending"
+ ? "Sending"
+ : sendPhase == "done"
+ ? "Sent"
+ : "Send message"
+ }
+ disabled={!canSend}
+ onClick={sendMessage}
+ sx={{
+ alignItems: "center",
+ bgcolor: isSendStatus
+ ? threadSurfaceHover
+ : canSend
+ ? "#FFFFFF"
+ : threadSurfaceHover,
+ border: 0,
+ borderRadius: "50%",
+ color:
+ sendPhase == "sending"
+ ? "#D8D8D8"
+ : sendPhase == "done"
+ ? green
+ : canSend
+ ? "#3A3A3A"
+ : "#D8D8D8",
+ cursor: canSend ? "pointer" : "default",
+ display: "flex",
+ flexShrink: 0,
+ height: composerHeight,
+ justifyContent: "center",
+ opacity:
+ sendPhase == "sending"
+ ? 0.72
+ : isSendButtonActive
+ ? 1
+ : 0.42,
+ p: 0,
+ transition:
+ "background-color 180ms ease, color 180ms ease, opacity 180ms ease, transform 120ms ease",
+ width: composerHeight,
+ "&:active": {
+ transform: canSend
+ ? "scale(0.96)"
+ : "none",
+ },
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ "&:hover": {
+ bgcolor: isSendStatus
+ ? threadSurfaceHover
+ : canSend
+ ? "#F2F2F2"
+ : "rgba(255, 255, 255, 0.14)",
+ },
+ }}
+ >
+ {sendPhase == "sending" ? (
+ <Box
+ component="span"
+ sx={{
+ animation: `${sendSpin} 1s linear infinite`,
+ display: "flex",
+ transform: "none",
+ }}
+ >
+ <HugeiconsIcon
+ icon={Loading03Icon}
+ size={22}
+ strokeWidth={1.8}
+ />
+ </Box>
+ ) : sendPhase == "done" ? (
+ <Box
+ component="span"
+ sx={{
+ display: "flex",
+ transform: "translate(-1px, 1px)",
+ }}
+ >
+ <HugeiconsIcon
+ icon={Tick02Icon}
+ primaryColor={green}
+ size={22}
+ strokeWidth={1.8}
+ />
+ </Box>
+ ) : (
+ <Box
+ component="span"
+ sx={{
+ display: "flex",
+ transform: "translate(-1px, 1px)",
+ }}
+ >
+ <HugeiconsIcon
+ icon={Navigation03Icon}
+ size={24}
+ strokeWidth={1.8}
+ />
+ </Box>
+ )}
+ </Box>
+ </Box>
+ </>
+ ) : (
+ <>
+ {isConversationsLoading ? (
+ <Box
+ sx={{
+ alignItems: "center",
+ boxSizing: "border-box",
+ display: "flex",
+ inset: 0,
+ justifyContent: "center",
+ pointerEvents: "none",
+ position: "absolute",
+ }}
+ >
+ <SocialLoadingSpinner ariaLabel="Loading messages" />
+ </Box>
+ ) : conversations.length == 0 ? (
+ <Box
+ sx={{
+ alignItems: "center",
+ boxSizing: "border-box",
+ display: "flex",
+ flexDirection: "column",
+ inset: 0,
+ justifyContent: "center",
+ pointerEvents: "none",
+ position: "absolute",
+ px: 3,
+ textAlign: "center",
+ }}
+ >
+ <Box
+ component="h2"
+ sx={{
+ color: textBase,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 16,
+ fontWeight: 700,
+ letterSpacing: 0,
+ lineHeight: "22px",
+ m: 0,
+ }}
+ >
+ No messages yet
+ </Box>
+ <Box
+ component="p"
+ sx={{
+ color: textSecondary,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 500,
+ lineHeight: "20px",
+ m: 0,
+ mt: "8px",
+ maxWidth: 260,
+ }}
+ >
+ Replies to posts and messages from friends
+ will appear here.
+ </Box>
+ </Box>
+ ) : (
+ <Box
+ component="ul"
+ sx={{
+ boxSizing: "border-box",
+ listStyle: "none",
+ m: 0,
+ p: "12px 16px 28px",
+ }}
+ >
+ {conversations.map((conversation) => {
+ const name =
+ conversation.friend.fullName.trim() ||
+ conversation.friend.username;
+ const timestampLabel = formatTimeAgo(
+ microsForTimestamp(
+ conversation.lastMessage
+ .createdAtMs,
+ ),
+ );
+ return (
+ <Box
+ component="li"
+ key={conversation.friend.id}
+ sx={{ listStyle: "none" }}
+ >
+ <Box
+ component="button"
+ type="button"
+ onClick={() =>
+ onOpenThread(
+ conversation.friend,
+ )
+ }
+ sx={{
+ alignItems: "center",
+ appearance: "none",
+ bgcolor: "transparent",
+ border: 0,
+ borderRadius: "8px",
+ color: textBase,
+ cursor: "pointer",
+ display: "grid",
+ gap: "10px",
+ gridTemplateColumns:
+ "44px minmax(0, 1fr) auto",
+ minHeight: 64,
+ p: "8px 0",
+ textAlign: "left",
+ width: "100%",
+ "&:focus-visible": {
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ }}
+ >
+ <Avatar
+ avatarUrl={
+ conversation.friend
+ .avatarUrl
+ }
+ name={name}
+ size={44}
+ />
+ <Box sx={{ minWidth: 0 }}>
+ <Box
+ sx={{
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 14,
+ fontWeight: 700,
+ lineHeight: "20px",
+ overflow: "hidden",
+ textOverflow:
+ "ellipsis",
+ whiteSpace:
+ "nowrap",
+ }}
+ >
+ {firstNameFrom(name)}
+ </Box>
+ <Box
+ sx={{
+ color: textSecondary,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 13,
+ fontWeight: 500,
+ lineHeight: "18px",
+ overflow: "hidden",
+ textOverflow:
+ "ellipsis",
+ whiteSpace:
+ "nowrap",
+ }}
+ >
+ {messagePreview(
+ conversation.lastMessage,
+ )}
+ </Box>
+ </Box>
+ <Box
+ sx={{
+ color: textSecondary,
+ fontFamily:
+ '"Inter Variable", Inter, sans-serif',
+ fontSize: 12,
+ fontWeight: 600,
+ lineHeight: "16px",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {timestampLabel}
+ </Box>
+ </Box>
+ </Box>
+ );
+ })}
+ </Box>
+ )}
+ </>
+ )}
+ </Box>
+ </Box>
+ );
+};
diff --git a/web/apps/social/src/screens/NotificationsScreen.tsx b/web/apps/social/src/screens/NotificationsScreen.tsx
index 1321a14563..69d06cf61c 100644
--- a/web/apps/social/src/screens/NotificationsScreen.tsx
+++ b/web/apps/social/src/screens/NotificationsScreen.tsx
@@ -1,5 +1,6 @@
import {
ArrowLeft02Icon,
+ Message01Icon,
UserAdd01Icon,
UserRemove01Icon,
} from "@hugeicons/core-free-icons";
@@ -32,7 +33,11 @@ const timelineLineTop = iconCircleTopOffset + iconCircleSize;
const timelineListInset = "12px";
const thumbnailRightInset = "16px";
-type NotificationType = "liked-post" | "added-friend" | "removed-friend";
+type NotificationType =
+ | "liked-post"
+ | "replied-post"
+ | "added-friend"
+ | "removed-friend";
interface SocialNotification {
actor: Pick<FriendProfile, "avatarUrl" | "fullName" | "id" | "username">;
@@ -50,6 +55,7 @@ interface NotificationsScreenProps {
profile: SetupProfile;
notifications: SocialNotification[];
onLoadPostLikers?: (postId: number) => Promise<SocialLiker[]>;
+ onOpenMessages?: () => void;
onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;
}
@@ -80,6 +86,25 @@ const LikedPhotoIcon: React.FC = () => (
</svg>
);
+const RepliedPostNotificationIcon: React.FC = () => (
+ <svg
+ width="15"
+ height="12"
+ viewBox="0 0 12 9"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M4.5241 0.242677C4.62341 0.34442 4.67919 0.482337 4.67919 0.626134C4.67919 0.76993 4.62341 0.907847 4.5241 1.00959L1.89369 3.70102H7.68483C8.3587 3.70102 9.35854 3.9036 10.2042 4.52653C11.0775 5.17045 11.7507 6.23762 11.7507 7.86116C11.7507 8.00507 11.6948 8.14309 11.5953 8.24485C11.4959 8.34661 11.361 8.40378 11.2203 8.40378C11.0797 8.40378 10.9448 8.34661 10.8453 8.24485C10.7459 8.14309 10.69 8.00507 10.69 7.86116C10.69 6.59069 10.1844 5.84982 9.58481 5.40776C8.95761 4.94544 8.18899 4.78627 7.68483 4.78627H1.89369L4.5241 7.4777C4.5762 7.52738 4.61799 7.58728 4.64698 7.65384C4.67597 7.72041 4.69155 7.79226 4.69281 7.86512C4.69406 7.93798 4.68096 8.01035 4.65429 8.07791C4.62762 8.14548 4.58792 8.20686 4.53756 8.25839C4.4872 8.30991 4.42722 8.35053 4.36118 8.37782C4.29515 8.40512 4.22442 8.41852 4.15321 8.41723C4.082 8.41595 4.01178 8.4 3.94673 8.37034C3.88167 8.34068 3.82313 8.29792 3.77457 8.24461L0.23908 4.6271C0.139767 4.52536 0.0839844 4.38744 0.0839844 4.24364C0.0839844 4.09985 0.139767 3.96193 0.23908 3.86019L3.77457 0.242677C3.87401 0.141061 4.0088 0.0839844 4.14934 0.0839844C4.28987 0.0839844 4.42466 0.141061 4.5241 0.242677Z"
+ fill="currentColor"
+ stroke="currentColor"
+ strokeWidth="0.166667"
+ />
+ </svg>
+);
+
const UserAddNotificationIcon: React.FC = () => (
<HugeiconsIcon icon={UserAdd01Icon} size={17} strokeWidth={1.8} />
);
@@ -94,6 +119,11 @@ const actionForNotification = (
switch (type) {
case "liked-post":
return { icon: <LikedPhotoIcon />, label: "liked your post" };
+ case "replied-post":
+ return {
+ icon: <RepliedPostNotificationIcon />,
+ label: "replied to your post",
+ };
case "added-friend":
return {
icon: <UserAddNotificationIcon />,
@@ -360,6 +390,7 @@ export const NotificationsScreen: React.FC<NotificationsScreenProps> = ({
notifications,
onBack,
onLoadPostLikers,
+ onOpenMessages,
onOpenFriend,
onSetPostLiked,
profile,
@@ -461,6 +492,35 @@ export const NotificationsScreen: React.FC<NotificationsScreenProps> = ({
>
Notifications
</Box>
+ <Box
+ component="button"
+ type="button"
+ aria-label="Open messages"
+ onClick={onOpenMessages}
+ sx={{
+ alignItems: "center",
+ bgcolor: "transparent",
+ border: 0,
+ color: textBase,
+ cursor: onOpenMessages ? "pointer" : "default",
+ display: "flex",
+ height: 24,
+ justifyContent: "flex-end",
+ p: 0,
+ width: 24,
+ "&:focus-visible": {
+ borderRadius: "50%",
+ outline: `2px solid ${green}`,
+ outlineOffset: 2,
+ },
+ }}
+ >
+ <HugeiconsIcon
+ icon={Message01Icon}
+ size={24}
+ strokeWidth={1.8}
+ />
+ </Box>
</Box>
{hasNotifications ? (
@@ -548,7 +608,8 @@ export const NotificationsScreen: React.FC<NotificationsScreenProps> = ({
maxWidth: 240,
}}
>
- Likes, replies, and new friends will appear here.
+ Likes and replies to posts, and new friends will
+ appear here.
</Box>
</Box>
)}
diff --git a/web/apps/social/src/services/socialWall.ts b/web/apps/social/src/services/socialWall.ts
index bf37776e1e..97f2664218 100644
--- a/web/apps/social/src/services/socialWall.ts
+++ b/web/apps/social/src/services/socialWall.ts
@@ -34,6 +34,7 @@ interface WallActor {
friends?: number;
posts?: number;
profile?: string;
+ publicKey?: string;
userId?: number;
wallId: string;
wallSlug: string;
@@ -80,7 +81,11 @@ interface WallNotification {
wallId: string;
wallSlug: string;
};
- type: "likedPost" | "addedYouAsFriend" | "removedYouAsFriend";
+ type:
+ | "likedPost"
+ | "repliedToPost"
+ | "addedYouAsFriend"
+ | "removedYouAsFriend";
}
interface WallNotificationPage {
@@ -93,6 +98,47 @@ interface WallPostLikerPage {
nextCursor?: string;
}
+type WallMessageKind = "post_reply" | "regular";
+
+interface WallMessageQuote {
+ caption?: string;
+ height?: number;
+ mediaType?: string;
+ objectKey?: string;
+ postId: number;
+ wallId: string;
+ width?: number;
+}
+
+interface WallMessage {
+ createdAt: string;
+ id?: string;
+ isDeleted?: boolean;
+ kind: WallMessageKind;
+ messageId: string;
+ quote?: WallMessageQuote;
+ recipient: WallActor;
+ replyPostId?: number;
+ sender: WallActor;
+ text: string;
+ updatedAt: string;
+}
+
+interface WallMessagePage {
+ items?: WallMessage[];
+ nextCursor?: string;
+}
+
+interface WallMessageConversation {
+ friend: WallActor;
+ lastMessage: WallMessage;
+}
+
+interface WallMessageConversationPage {
+ items?: WallMessageConversation[];
+ nextCursor?: string;
+}
+
export interface SocialWallPost {
avatarUrl?: string | null;
caption?: string;
@@ -118,7 +164,7 @@ export interface SocialWallNotification {
id: string;
post?: SocialWallPost;
timestampMs: number;
- type: "added-friend" | "liked-post" | "removed-friend";
+ type: "added-friend" | "liked-post" | "removed-friend" | "replied-post";
}
export interface SocialWallNotificationPage {
@@ -141,6 +187,48 @@ export interface SocialLiker {
name: string;
}
+export type SocialWallMessageKind = WallMessageKind;
+
+export interface SocialWallMessageQuote {
+ caption?: string;
+ height?: number;
+ imageUrl?: string;
+ isUnavailable?: boolean;
+ mediaType?: string;
+ objectKey?: string;
+ postId: number;
+ wallId: string;
+ width?: number;
+}
+
+export interface SocialWallMessage {
+ createdAtMs: number;
+ id: string;
+ isDeleted: boolean;
+ kind: SocialWallMessageKind;
+ quote?: SocialWallMessageQuote;
+ recipient: FriendProfile;
+ replyPostId?: number;
+ sender: FriendProfile;
+ text: string;
+ updatedAtMs: number;
+}
+
+export interface SocialWallMessagePage {
+ items: SocialWallMessage[];
+ nextCursor?: string;
+}
+
+export interface SocialWallMessageConversation {
+ friend: FriendProfile;
+ lastMessage: SocialWallMessage;
+}
+
+export interface SocialWallMessageConversationPage {
+ items: SocialWallMessageConversation[];
+ nextCursor?: string;
+}
+
const parseWallProfilePayload = (profile: string): WallProfilePayload => {
if (!profile.trim()) return {};
try {
@@ -313,6 +401,71 @@ const postPageFromLinkPage = async (
return { items, nextCursor: page.nextCursor || undefined };
};
+const messageQuoteFromWallQuote = async (
+ ctx: WallAccountCtxHandle,
+ quote: WallMessageQuote | undefined,
+ includeImage: boolean,
+): Promise<SocialWallMessageQuote | undefined> => {
+ if (!quote) return undefined;
+
+ const socialQuote: SocialWallMessageQuote = {
+ caption: quote.caption,
+ height: quote.height,
+ mediaType: quote.mediaType,
+ objectKey: quote.objectKey,
+ postId: quote.postId,
+ wallId: quote.wallId,
+ width: quote.width,
+ };
+ if (!includeImage || !quote.objectKey) return socialQuote;
+
+ try {
+ socialQuote.imageUrl = blobURLForBytes(
+ await ctx.download_post_asset(
+ BigInt(quote.postId),
+ quote.objectKey,
+ ),
+ quote.mediaType,
+ );
+ } catch (error) {
+ console.warn("Failed to load quoted post image", error);
+ socialQuote.isUnavailable = true;
+ }
+ return socialQuote;
+};
+
+const messageFromWallMessage = async (
+ ctx: WallAccountCtxHandle,
+ message: WallMessage,
+ includeQuoteImage: boolean,
+): Promise<SocialWallMessage> => {
+ const sender = actorProfile(message.sender);
+ const recipient = actorProfile(message.recipient);
+ const [senderAvatarUrl, recipientAvatarUrl, quote] = await Promise.all([
+ accountAvatarURL(ctx, message.sender.wallId, message.sender.avatar),
+ accountAvatarURL(
+ ctx,
+ message.recipient.wallId,
+ message.recipient.avatar,
+ ),
+ messageQuoteFromWallQuote(ctx, message.quote, includeQuoteImage),
+ ]);
+ sender.avatarUrl = senderAvatarUrl;
+ recipient.avatarUrl = recipientAvatarUrl;
+ return {
+ createdAtMs: timestampMsFromWallDate(message.createdAt),
+ id: message.messageId || message.id || `${message.createdAt}`,
+ isDeleted: Boolean(message.isDeleted),
+ kind: message.kind,
+ quote,
+ recipient,
+ replyPostId: message.replyPostId,
+ sender,
+ text: message.text,
+ updatedAtMs: timestampMsFromWallDate(message.updatedAt),
+ };
+};
+
export const createCurrentProfileLink = async (
wallId: string,
): Promise<SocialWallLink> => {
@@ -486,6 +639,83 @@ export const loadCurrentPostLikers = async (postId: number) => {
}
};
+export const replyToCurrentPost = async (postId: number, text: string) => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ await ctx.reply_to_post(BigInt(postId), text.trim());
+ } finally {
+ ctx.free();
+ }
+};
+
+export const sendCurrentMessage = async (wallId: string, text: string) => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ return await messageFromWallMessage(
+ ctx,
+ (await ctx.send_message(wallId, text.trim())) as WallMessage,
+ true,
+ );
+ } finally {
+ ctx.free();
+ }
+};
+
+export const loadCurrentMessageConversations =
+ async (): Promise<SocialWallMessageConversationPage> => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ const page = (await ctx.list_message_conversations(
+ null,
+ 50,
+ )) as WallMessageConversationPage;
+ const items = await Promise.all(
+ (page.items ?? []).map(async (conversation) => {
+ const friend = actorProfile(conversation.friend);
+ friend.avatarUrl = await accountAvatarURL(
+ ctx,
+ conversation.friend.wallId,
+ conversation.friend.avatar,
+ );
+ return {
+ friend,
+ lastMessage: await messageFromWallMessage(
+ ctx,
+ conversation.lastMessage,
+ false,
+ ),
+ };
+ }),
+ );
+ return { items, nextCursor: page.nextCursor || undefined };
+ } finally {
+ ctx.free();
+ }
+ };
+
+export const loadCurrentMessageThread = async (
+ wallId: string,
+): Promise<SocialWallMessagePage> => {
+ const ctx = await ensureCurrentWallContext();
+ try {
+ const page = (await ctx.list_message_thread(
+ wallId,
+ null,
+ 100,
+ )) as WallMessagePage;
+ const items = (
+ await Promise.all(
+ (page.items ?? []).map((message) =>
+ messageFromWallMessage(ctx, message, true),
+ ),
+ )
+ ).reverse();
+ return { items, nextCursor: page.nextCursor || undefined };
+ } finally {
+ ctx.free();
+ }
+};
+
export const deleteCurrentPost = async (postId: number) => {
const ctx = await ensureCurrentWallContext();
try {
@@ -527,12 +757,15 @@ export const loadCurrentNotificationsPage =
wallSlug: notification.post.wallSlug,
})
: undefined;
- const notificationType: SocialWallNotification["type"] =
- notification.type == "addedYouAsFriend"
- ? "added-friend"
- : notification.type == "removedYouAsFriend"
- ? "removed-friend"
- : "liked-post";
+ let notificationType: SocialWallNotification["type"] =
+ "liked-post";
+ if (notification.type == "addedYouAsFriend") {
+ notificationType = "added-friend";
+ } else if (notification.type == "removedYouAsFriend") {
+ notificationType = "removed-friend";
+ } else if (notification.type == "repliedToPost") {
+ notificationType = "replied-post";
+ }
return {
actor,
id: notification.id,
diff --git a/web/apps/social/src/utils/socialRoutes.ts b/web/apps/social/src/utils/socialRoutes.ts
index 185030e53e..f57dcf37b3 100644
--- a/web/apps/social/src/utils/socialRoutes.ts
+++ b/web/apps/social/src/utils/socialRoutes.ts
@@ -19,6 +19,7 @@ export const socialRoutes = {
home: "/app",
invite: "/invite",
login: "/login",
+ messages: "/app/messages",
notifications: "/app/notifications",
onboarding: "/",
passkeysFinish: "/passkeys/finish",
diff --git a/web/packages/wasm/Cargo.lock b/web/packages/wasm/Cargo.lock
index be52bc7f8d..2e88e88f99 100644
--- a/web/packages/wasm/Cargo.lock
+++ b/web/packages/wasm/Cargo.lock
@@ -355,6 +355,7 @@ dependencies = [
"base64",
"ente-core",
"serde",
+ "serde_json",
"thiserror",
"url",
"urlencoding",
diff --git a/web/packages/wasm/src/wall.rs b/web/packages/wasm/src/wall.rs
index 8606bca042..dcc572a94d 100644
--- a/web/packages/wasm/src/wall.rs
+++ b/web/packages/wasm/src/wall.rs
@@ -2,10 +2,10 @@
use ente_core::http::Error as HttpError;
use ente_wall::{
- AccountWallCtx, AuthKeyAttributes, CreatedWall, CreatedWallLink, DecryptedPost,
- DecryptedWallProfile, OpenAccountWallCtxInput, OpenWallLinkCtxInput, PostResponse,
- PrivateKeySource, ProfileAvatarResponse, WallActorResponse, WallError as CoreWallError,
- WallLinkCtx, WallNotification, WallNotificationPost,
+ AccountWallCtx, AuthKeyAttributes, CreatedWall, CreatedWallLink, DecryptedMessage,
+ DecryptedPost, DecryptedWallProfile, MessageResponse, OpenAccountWallCtxInput,
+ OpenWallLinkCtxInput, PostResponse, PrivateKeySource, ProfileAvatarResponse, WallActorResponse,
+ WallError as CoreWallError, WallLinkCtx, WallNotification, WallNotificationPost,
crypto::{decode_b64, encode_b64},
};
use serde::{Deserialize, Serialize};
@@ -214,6 +214,54 @@ struct PostLikerPageJs {
next_cursor: String,
}
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct MessageQuoteJs {
+ post_id: i64,
+ wall_id: String,
+ caption: Option<String>,
+ object_key: Option<String>,
+ width: Option<i32>,
+ height: Option<i32>,
+ media_type: Option<String>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct MessageJs {
+ message_id: String,
+ kind: String,
+ sender: ActorJs,
+ recipient: ActorJs,
+ text: String,
+ quote: Option<MessageQuoteJs>,
+ reply_post_id: Option<i64>,
+ is_deleted: bool,
+ created_at: String,
+ updated_at: String,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct MessagePageJs {
+ items: Vec<MessageJs>,
+ next_cursor: String,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct MessageConversationJs {
+ friend: ActorJs,
+ last_message: MessageJs,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct MessageConversationPageJs {
+ items: Vec<MessageConversationJs>,
+ next_cursor: String,
+}
+
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct FriendJs {
@@ -409,6 +457,36 @@ async fn notification_post_to_js(
})
}
+async fn account_message_to_js(
+ ctx: &AccountWallCtx,
+ message: MessageResponse,
+ decrypted: DecryptedMessage,
+) -> Result<MessageJs, WasmWallError> {
+ let sender = account_actor_to_js(ctx, message.sender).await?;
+ let recipient = account_actor_to_js(ctx, message.recipient).await?;
+ let quote = decrypted.payload.quote.map(|quote| MessageQuoteJs {
+ post_id: quote.post_id,
+ wall_id: quote.wall_id,
+ caption: quote.caption,
+ object_key: quote.object_key,
+ width: quote.width,
+ height: quote.height,
+ media_type: quote.media_type,
+ });
+ Ok(MessageJs {
+ message_id: message.message_id,
+ kind: message.kind,
+ sender,
+ recipient,
+ text: decrypted.payload.text,
+ quote,
+ reply_post_id: message.reply_post_id,
+ is_deleted: message.is_deleted,
+ created_at: message.created_at,
+ updated_at: message.updated_at,
+ })
+}
+
/// Open an authenticated wall context for web.
#[wasm_bindgen]
pub async fn wall_open_account_ctx(input: JsValue) -> Result<WallAccountCtxHandle, WasmWallError> {
@@ -743,6 +821,81 @@ impl WallAccountCtxHandle {
.map_err(Into::into)
}
+ /// Send a regular 1:1 message to a friend wall.
+ pub async fn send_message(
+ &self,
+ wall_id: String,
+ text: String,
+ ) -> Result<JsValue, WasmWallError> {
+ let message = self.inner.send_message(&wall_id, &text).await?;
+ let decrypted = self.inner.decrypt_message(&message)?;
+ swb::to_value(&account_message_to_js(&self.inner, message, decrypted).await?)
+ .map_err(Into::into)
+ }
+
+ /// Send a private post reply message to the post owner.
+ pub async fn reply_to_post(
+ &self,
+ post_id: i64,
+ text: String,
+ ) -> Result<JsValue, WasmWallError> {
+ let message = self.inner.reply_to_post(post_id, &text).await?;
+ let decrypted = self.inner.decrypt_message(&message)?;
+ swb::to_value(&account_message_to_js(&self.inner, message, decrypted).await?)
+ .map_err(Into::into)
+ }
+
+ /// List 1:1 message conversations with decrypted last messages.
+ pub async fn list_message_conversations(
+ &self,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<JsValue, WasmWallError> {
+ let page = self.inner.list_message_conversations(cursor, limit).await?;
+ let mut items = Vec::with_capacity(page.items.len());
+ for conversation in page.items {
+ let friend = account_actor_to_js(&self.inner, conversation.friend).await?;
+ let decrypted = self.inner.decrypt_message(&conversation.last_message)?;
+ items.push(MessageConversationJs {
+ friend,
+ last_message: account_message_to_js(
+ &self.inner,
+ conversation.last_message,
+ decrypted,
+ )
+ .await?,
+ });
+ }
+ swb::to_value(&MessageConversationPageJs {
+ items,
+ next_cursor: page.next_cursor,
+ })
+ .map_err(Into::into)
+ }
+
+ /// List a 1:1 message thread with decrypted messages.
+ pub async fn list_message_thread(
+ &self,
+ wall_id: String,
+ cursor: Option<String>,
+ limit: Option<i32>,
+ ) -> Result<JsValue, WasmWallError> {
+ let page = self
+ .inner
+ .list_message_thread(&wall_id, cursor, limit)
+ .await?;
+ let mut items = Vec::with_capacity(page.items.len());
+ for message in page.items {
+ let decrypted = self.inner.decrypt_message(&message)?;
+ items.push(account_message_to_js(&self.inner, message, decrypted).await?);
+ }
+ swb::to_value(&MessagePageJs {
+ items,
+ next_cursor: page.next_cursor,
+ })
+ .map_err(Into::into)
+ }
+
/// Update a post caption.
pub async fn update_post_caption(
&self,