Skip to content

armgit / ente

Public Imported from GitHub
0

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

Simplify Space like storage

Neeraj Guptaa82130b30f44
diff --git a/rust/bindings/wasm/ente-wasm/src/space.rs b/rust/bindings/wasm/ente-wasm/src/space.rs
index 65b4aee426..90824815aa 100644
--- a/rust/bindings/wasm/ente-wasm/src/space.rs
+++ b/rust/bindings/wasm/ente-wasm/src/space.rs
@@ -159,7 +159,6 @@ struct PostJs {
key_version: i32,
objects: Vec<PostObjectJs>,
created_at: String,
- likes: i64,
viewer_liked: bool,
}
@@ -209,7 +208,7 @@ struct MessageJs {
quote: Option<MessageQuoteJs>,
reply_post_id: Option<i64>,
reply_message_id: Option<String>,
- likes: i64,
+ liked: bool,
viewer_liked: bool,
is_deleted: bool,
created_at: String,
@@ -435,7 +434,6 @@ async fn account_post_to_js(
key_version: post.key_version,
objects: post_objects_to_js(Some(&decrypted.post_key), post.objects)?,
created_at: post.created_at,
- likes: post.likes,
viewer_liked: post.viewer_liked,
})
}
@@ -456,7 +454,6 @@ async fn link_post_to_js(
key_version: post.key_version,
objects: post_objects_to_js(Some(&decrypted.post_key), post.objects)?,
created_at: post.created_at,
- likes: post.likes,
viewer_liked: post.viewer_liked,
})
}
@@ -518,7 +515,7 @@ async fn account_message_to_js(
quote,
reply_post_id: message.reply_post_id,
reply_message_id: message.reply_message_id,
- likes: message.likes,
+ liked: message.liked,
viewer_liked: message.viewer_liked,
is_deleted: message.is_deleted,
created_at: message.created_at,
@@ -589,7 +586,7 @@ async fn account_message_response_to_js(
quote,
reply_post_id: message.reply_post_id,
reply_message_id: message.reply_message_id,
- likes: message.likes,
+ liked: message.liked,
viewer_liked: message.viewer_liked,
is_deleted: message.is_deleted,
created_at: message.created_at,
@@ -903,7 +900,6 @@ impl SpaceAccountCtxHandle {
key_version: item.key_version,
objects: item.objects,
created_at: item.created_at,
- likes: item.likes,
viewer_liked: item.viewer_liked,
})
.collect(),
diff --git a/rust/space/src/client/mod.rs b/rust/space/src/client/mod.rs
index 3ba54fa07d..6ddefb373d 100644
--- a/rust/space/src/client/mod.rs
+++ b/rust/space/src/client/mod.rs
@@ -534,7 +534,6 @@ fn post_response_from_feed_item(item: &FeedItem) -> PostResponse {
key_version: item.key_version,
objects: item.objects.clone(),
created_at: item.created_at.clone(),
- likes: item.likes,
viewer_liked: item.viewer_liked,
}
}
diff --git a/rust/space/src/client/tests.rs b/rust/space/src/client/tests.rs
index af7060a304..85e9990574 100644
--- a/rust/space/src/client/tests.rs
+++ b/rust/space/src/client/tests.rs
@@ -270,7 +270,6 @@ async fn space_link_decrypt_post_key_uses_post_version() {
key_version: 1,
objects: Vec::new(),
created_at: "2026-04-16T00:00:00Z".to_owned(),
- likes: 0,
viewer_liked: false,
};
@@ -1444,7 +1443,7 @@ async fn message_actions_use_message_endpoints() {
"messageCipher": "cipher",
"encryptedMessageKey": "key",
"replyMessageId": "wmsg_parent",
- "likes": 0,
+ "liked": false,
"viewerLiked": false,
"isDeleted": false,
"createdAt": "2026-04-16T00:00:00Z",
@@ -1963,7 +1962,6 @@ async fn list_feed_uses_space_feed_endpoint() {
"keyVersion": 3,
"objects": [],
"createdAt": "2026-04-16T00:00:00Z",
- "likes": 2,
"viewerLiked": true
}],
"nextCursor": "cursor-2"
@@ -2012,7 +2010,6 @@ async fn list_posts_uses_space_posts_page_endpoint() {
"keyVersion": 3,
"objects": [],
"createdAt": "2026-04-16T00:00:00Z",
- "likes": 2,
"viewerLiked": true
}],
"nextCursor": "41"
@@ -2076,7 +2073,6 @@ async fn fetch_post_decrypted_uses_post_by_id_endpoint() {
"keyVersion": 3,
"objects": [],
"createdAt": "2026-04-16T00:00:00Z",
- "likes": 0,
"viewerLiked": false
})
.to_string(),
diff --git a/rust/space/src/models.rs b/rust/space/src/models.rs
index 7676f1b893..88d2598813 100644
--- a/rust/space/src/models.rs
+++ b/rust/space/src/models.rs
@@ -139,7 +139,6 @@ pub struct FeedItem {
#[serde(default)]
pub objects: Vec<PostObjectPayload>,
pub created_at: String,
- pub likes: i64,
pub viewer_liked: bool,
}
diff --git a/rust/space/src/transport.rs b/rust/space/src/transport.rs
index e1afbfc192..984e202471 100644
--- a/rust/space/src/transport.rs
+++ b/rust/space/src/transport.rs
@@ -195,7 +195,7 @@ pub struct MessageResponse {
#[serde(default)]
pub reply_message_id: Option<String>,
#[serde(default)]
- pub likes: i64,
+ pub liked: bool,
#[serde(default)]
pub viewer_liked: bool,
#[serde(default)]
@@ -281,7 +281,6 @@ pub struct PostResponse {
#[serde(default)]
pub objects: Vec<PostObjectPayload>,
pub created_at: String,
- pub likes: i64,
pub viewer_liked: bool,
}
diff --git a/server/migrations/125_space.down.sql b/server/migrations/125_space.down.sql
index 622a0dc9ac..0281a74ba5 100644
--- a/server/migrations/125_space.down.sql
+++ b/server/migrations/125_space.down.sql
@@ -9,14 +9,11 @@ DROP TABLE IF EXISTS space_friend_requests;
DROP TRIGGER IF EXISTS update_space_friend_shares_updated_at ON space_friend_shares;
DROP TABLE IF EXISTS space_friend_shares;
-DROP TABLE IF EXISTS space_message_likes;
-
DROP TRIGGER IF EXISTS update_space_messages_updated_at ON space_messages;
DROP TRIGGER IF EXISTS space_messages_null_cipher_on_delete ON space_messages;
DROP TABLE IF EXISTS space_messages;
DROP FUNCTION IF EXISTS tg_space_messages_null_cipher_on_delete();
-DROP TABLE IF EXISTS space_post_likes;
DROP TABLE IF EXISTS space_temp_objects;
DROP TABLE IF EXISTS space_post_assets;
diff --git a/server/migrations/125_space.up.sql b/server/migrations/125_space.up.sql
index 990455d397..18e5797654 100644
--- a/server/migrations/125_space.up.sql
+++ b/server/migrations/125_space.up.sql
@@ -153,19 +153,6 @@ CREATE TABLE IF NOT EXISTS space_temp_objects (
CREATE INDEX IF NOT EXISTS idx_space_temp_objects_expires
ON space_temp_objects (cleanup_after ASC);
-CREATE TABLE IF NOT EXISTS space_post_likes (
- post_id BIGINT NOT NULL REFERENCES space_posts (post_id) ON DELETE CASCADE,
- actor_space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,
- created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
- PRIMARY KEY (post_id, actor_space_id)
-);
-
-CREATE INDEX IF NOT EXISTS idx_space_post_likes_post_created_user
- ON space_post_likes (post_id, created_at DESC, actor_space_id DESC);
-
-CREATE INDEX IF NOT EXISTS idx_space_post_likes_actor_created_post
- ON space_post_likes (actor_space_id, created_at DESC, post_id DESC);
-
CREATE TABLE IF NOT EXISTS space_friend_shares (
space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,
friend_space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,
@@ -219,6 +206,7 @@ BEGIN
NEW.message_cipher := NULL;
NEW.sender_encrypted_message_key := NULL;
NEW.recipient_encrypted_message_key := NULL;
+ NEW.recipient_liked_at := NULL;
END IF;
RETURN NEW;
END; $$ LANGUAGE plpgsql;
@@ -240,24 +228,49 @@ CREATE TABLE IF NOT EXISTS space_messages (
recipient_encrypted_message_key BYTEA,
reply_post_id BIGINT REFERENCES space_posts (post_id) ON DELETE SET NULL,
reply_message_id TEXT REFERENCES space_messages (message_id) ON DELETE SET NULL,
+ recipient_liked_at BIGINT,
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_space_messages_distinct_spaces CHECK (sender_space_id <> recipient_space_id),
- CONSTRAINT chk_space_messages_kind CHECK (kind IN ('regular', 'post_reply')),
+ CONSTRAINT chk_space_messages_kind CHECK (kind IN ('regular', 'post_reply', 'post_like')),
CONSTRAINT chk_space_messages_regular_shape CHECK (kind <> 'regular' OR reply_post_id IS NULL),
+ CONSTRAINT chk_space_messages_post_like_shape CHECK (
+ kind <> 'post_like' OR (
+ reply_post_id IS NOT NULL
+ AND reply_message_id IS NULL
+ AND message_cipher IS NULL
+ AND sender_encrypted_message_key IS NULL
+ AND recipient_encrypted_message_key IS NULL
+ AND recipient_liked_at IS NULL
+ AND is_deleted = FALSE
+ )
+ ),
+ CONSTRAINT chk_space_messages_recipient_like CHECK (
+ recipient_liked_at IS NULL OR (kind <> 'post_like' AND is_deleted = FALSE)
+ ),
CONSTRAINT chk_space_messages_single_reply_target CHECK (reply_post_id IS NULL OR reply_message_id IS NULL),
CONSTRAINT chk_space_messages_cipher_on_delete CHECK (
(
+ kind <> 'post_like'
+ AND
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 (
+ kind <> 'post_like'
+ AND
is_deleted = TRUE
AND message_cipher IS NULL
AND sender_encrypted_message_key IS NULL
AND recipient_encrypted_message_key IS NULL
+ ) OR (
+ kind = 'post_like'
+ AND is_deleted = FALSE
+ AND message_cipher IS NULL
+ AND sender_encrypted_message_key IS NULL
+ AND recipient_encrypted_message_key IS NULL
)
)
);
@@ -281,15 +294,17 @@ CREATE INDEX IF NOT EXISTS idx_space_messages_reply_message
ON space_messages (reply_message_id)
WHERE reply_message_id IS NOT NULL;
-CREATE TABLE IF NOT EXISTS space_message_likes (
- message_id TEXT NOT NULL REFERENCES space_messages (message_id) ON DELETE CASCADE,
- actor_space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,
- created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
- PRIMARY KEY (message_id, actor_space_id)
-);
+CREATE UNIQUE INDEX IF NOT EXISTS uq_space_messages_post_like
+ ON space_messages (reply_post_id, sender_space_id)
+ WHERE kind = 'post_like';
+
+CREATE INDEX IF NOT EXISTS idx_space_messages_sender_liked
+ ON space_messages (sender_space_id, recipient_liked_at DESC, message_id DESC)
+ WHERE recipient_liked_at IS NOT NULL AND is_deleted = FALSE;
-CREATE INDEX IF NOT EXISTS idx_space_message_likes_actor_created
- ON space_message_likes (actor_space_id, created_at DESC, message_id DESC);
+CREATE INDEX IF NOT EXISTS idx_space_messages_recipient_liked
+ ON space_messages (recipient_space_id, recipient_liked_at DESC, message_id DESC)
+ WHERE recipient_liked_at IS NOT NULL AND is_deleted = FALSE;
CREATE TRIGGER space_messages_null_cipher_on_delete
BEFORE INSERT OR UPDATE ON space_messages
diff --git a/server/space/controller/helpers.go b/server/space/controller/helpers.go
index b62066dc32..8dcb614830 100644
--- a/server/space/controller/helpers.go
+++ b/server/space/controller/helpers.go
@@ -148,7 +148,6 @@ func toPostResponse(post *spacerepo.SpacePostRecord, assets []spacerepo.SpacePos
CaptionCipher: encodeSpaceField(post.CaptionCipher),
KeyVersion: post.KeyVersion,
CreatedAt: formatMicros(post.CreatedAt),
- Likes: post.Likes,
ViewerLiked: post.ViewerLiked,
}
if len(assets) > 0 {
diff --git a/server/space/controller/messages.go b/server/space/controller/messages.go
index 473775d517..a4b19e843b 100644
--- a/server/space/controller/messages.go
+++ b/server/space/controller/messages.go
@@ -16,6 +16,7 @@ import (
const (
spaceMessageKindRegular = "regular"
spaceMessageKindPostReply = "post_reply"
+ spaceMessageKindPostLike = "post_like"
maxSpaceMessageCipherEncodedBytes = 8 * 1024
maxSpaceMessageCipherDecodedBytes = 6 * 1024
@@ -203,10 +204,13 @@ func (c *MessagesController) ToggleLike(ctx *gin.Context, messageID string, req
if message.IsDeleted {
return nil, ente.NewBadRequestWithMessage("cannot like a deleted message")
}
- otherSpaceID := message.SenderSpaceID
- if message.SenderSpaceID == actorSpace.SpaceID {
- otherSpaceID = message.RecipientSpaceID
+ if message.Kind == spaceMessageKindPostLike {
+ return nil, ente.NewBadRequestWithMessage("cannot like a post like")
+ }
+ if message.RecipientSpaceID != actorSpace.SpaceID {
+ return nil, ente.NewBadRequestWithMessage("only the recipient can like a message")
}
+ otherSpaceID := message.SenderSpaceID
if _, err := c.FriendsRepo.GetShareForFriendAndSpace(ctx.Request.Context(), userID, actorSpace.SpaceID, otherSpaceID); err != nil {
if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {
return nil, ente.ErrPermissionDenied
@@ -239,6 +243,9 @@ func (c *MessagesController) Delete(ctx *gin.Context, messageID string) error {
if message.SenderID != userID || message.SenderSpaceID != senderSpace.SpaceID {
return ente.ErrPermissionDenied
}
+ if message.Kind == spaceMessageKindPostLike {
+ return ente.NewBadRequestWithMessage("cannot delete a post like")
+ }
if _, err := c.FriendsRepo.GetShareForFriendAndSpace(ctx.Request.Context(), userID, senderSpace.SpaceID, message.RecipientSpaceID); err != nil {
if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {
return ente.ErrPermissionDenied
@@ -332,7 +339,7 @@ func toMessageResponse(message repo.SpaceMessageRecord) *models.MessageResponse
MessageCipher: encodeSpaceField(message.MessageCipher),
EncryptedMessageKey: encodeSpaceField(message.EncryptedMessageKey),
Text: message.Text,
- Likes: message.Likes,
+ Liked: message.Liked,
ViewerLiked: message.ViewerLiked,
IsDeleted: message.IsDeleted,
CreatedAt: formatMicros(message.CreatedAt),
diff --git a/server/space/controller/messages_test.go b/server/space/controller/messages_test.go
index e7dbdcef45..e10150dcb4 100644
--- a/server/space/controller/messages_test.go
+++ b/server/space/controller/messages_test.go
@@ -81,7 +81,7 @@ func TestMessageLikeAndDeleteAccess(t *testing.T) {
require.True(t, liked.Liked)
viewed, err := repos.Messages.GetMessage(ctx, message.MessageID, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
- require.Equal(t, int64(1), viewed.Likes)
+ require.True(t, viewed.Liked)
require.True(t, viewed.ViewerLiked)
require.NoError(t, controller.Delete(newSpaceControllerContext(bobID), messageToDelete.MessageID))
diff --git a/server/space/models/models.go b/server/space/models/models.go
index 6e0a1660cf..3b358f2e88 100644
--- a/server/space/models/models.go
+++ b/server/space/models/models.go
@@ -344,7 +344,7 @@ type MessageResponse struct {
Quote *MessageQuoteResponse `json:"quote,omitempty"`
ReplyPostID *int64 `json:"replyPostId,omitempty"`
ReplyMessageID *string `json:"replyMessageId,omitempty"`
- Likes int64 `json:"likes"`
+ Liked bool `json:"liked"`
ViewerLiked bool `json:"viewerLiked"`
IsDeleted bool `json:"isDeleted"`
CreatedAt string `json:"createdAt"`
@@ -412,7 +412,6 @@ type PostResponse struct {
KeyVersion int `json:"keyVersion"`
Objects []PostObjectPayload `json:"objects,omitempty"`
CreatedAt string `json:"createdAt"`
- Likes int64 `json:"likes"`
ViewerLiked bool `json:"viewerLiked"`
}
diff --git a/server/space/repo/account_deletion.go b/server/space/repo/account_deletion.go
index 21468e952e..39c4ff99ab 100644
--- a/server/space/repo/account_deletion.go
+++ b/server/space/repo/account_deletion.go
@@ -90,25 +90,24 @@ func resetSpaceAccessTx(ctx context.Context, tx *sql.Tx, userID int64, spaceIDs
return stacktrace.Propagate(err, "failed to delete space notification read markers")
}
if _, err := tx.ExecContext(ctx, `
- DELETE FROM space_post_likes
- WHERE actor_space_id = ANY($1)
- OR post_id IN (
+ DELETE FROM space_messages
+ WHERE kind = 'post_like'
+ AND (
+ sender_space_id = ANY($1)
+ OR reply_post_id IN (
SELECT post_id
FROM space_posts
WHERE space_id = ANY($1)
- )
+ )
+ )
`, spaceIDArray); err != nil {
return stacktrace.Propagate(err, "failed to delete space post likes")
}
if _, err := tx.ExecContext(ctx, `
- DELETE FROM space_message_likes
- WHERE actor_space_id = ANY($1)
- OR message_id IN (
- SELECT message_id
- FROM space_messages
- WHERE sender_space_id = ANY($1)
- OR recipient_space_id = ANY($1)
- )
+ UPDATE space_messages
+ SET recipient_liked_at = NULL
+ WHERE recipient_liked_at IS NOT NULL
+ AND (sender_space_id = ANY($1) OR recipient_space_id = ANY($1))
`, spaceIDArray); err != nil {
return stacktrace.Propagate(err, "failed to delete space message likes")
}
diff --git a/server/space/repo/messages.go b/server/space/repo/messages.go
index 1d8f6ab9c3..d290949d63 100644
--- a/server/space/repo/messages.go
+++ b/server/space/repo/messages.go
@@ -3,7 +3,6 @@ package repo
import (
"context"
"database/sql"
- "sort"
"strconv"
"strings"
@@ -25,18 +24,22 @@ const spaceMessageSelectColumns = `
END AS encrypted_message_key,
m.reply_post_id,
m.reply_message_id,
- (SELECT COUNT(*) FROM space_message_likes ml WHERE ml.message_id = m.message_id) AS likes,
- EXISTS (SELECT 1 FROM space_message_likes ml WHERE ml.message_id = m.message_id AND ml.actor_space_id = %s) AS viewer_liked,
+ (m.recipient_liked_at IS NOT NULL) AS liked,
+ (m.recipient_liked_at IS NOT NULL AND m.recipient_space_id = %s) AS viewer_liked,
m.is_deleted,
m.created_at,
m.updated_at,
- '' AS text,
- NULL::bigint AS quote_post_id,
- '' AS quote_space_id,
- '\x'::bytea AS quote_encrypted_post_key,
- '\x'::bytea AS quote_caption_cipher,
- 0 AS quote_key_version,
- NULL::text AS quote_object_key,
+ CASE
+ WHEN m.kind = 'post_like' AND m.sender_space_id = %s THEN 'You liked a post'
+ WHEN m.kind = 'post_like' THEN 'Liked your post'
+ ELSE ''
+ END AS text,
+ quote_post.post_id AS quote_post_id,
+ COALESCE(quote_post.space_id, '') AS quote_space_id,
+ COALESCE(quote_post.encrypted_post_key, '\x'::bytea) AS quote_encrypted_post_key,
+ COALESCE(quote_post.caption_cipher, '\x'::bytea) AS quote_caption_cipher,
+ COALESCE(quote_post.key_version, 0) AS quote_key_version,
+ quote_asset.object_key AS quote_object_key,
sender_space.owner_id,
sender_space.space_id,
sender_space.space_slug,
@@ -66,6 +69,14 @@ const spaceMessageJoins = `
LEFT JOIN space_profile_assets sender_avatar ON sender_avatar.space_id = sender_space.space_id AND sender_avatar.asset_type = 'avatar'
JOIN spaces recipient_space ON recipient_space.space_id = m.recipient_space_id
LEFT JOIN space_profile_assets recipient_avatar ON recipient_avatar.space_id = recipient_space.space_id AND recipient_avatar.asset_type = 'avatar'
+ LEFT JOIN space_posts quote_post ON quote_post.post_id = m.reply_post_id AND quote_post.is_deleted = FALSE
+ LEFT JOIN LATERAL (
+ SELECT object_key
+ FROM space_post_assets
+ WHERE post_id = quote_post.post_id
+ ORDER BY position ASC, asset_id ASC
+ LIMIT 1
+ ) quote_asset ON TRUE
`
func (r *MessagesRepository) CreateMessage(ctx context.Context, input CreateSpaceMessageRecord) (*SpaceMessageRecord, error) {
@@ -151,17 +162,6 @@ func (r *MessagesRepository) ListThread(ctx context.Context, viewerID int64, vie
if err := rows.Err(); err != nil {
return nil, "", stacktrace.Propagate(err, "")
}
- postLikes, err := r.listThreadPostLikes(ctx, viewerID, viewerSpaceID, otherSpaceID, cursor, limit+1)
- if err != nil {
- return nil, "", err
- }
- out = append(out, postLikes...)
- sort.Slice(out, func(i, j int) bool {
- if out[i].CreatedAt != out[j].CreatedAt {
- return out[i].CreatedAt > out[j].CreatedAt
- }
- return out[i].MessageID > out[j].MessageID
- })
nextCursor := ""
if len(out) > limit {
nextCursor = formatMessageCursor(out[limit-1])
@@ -170,105 +170,25 @@ func (r *MessagesRepository) ListThread(ctx context.Context, viewerID int64, vie
return out, nextCursor, nil
}
-func (r *MessagesRepository) listThreadPostLikes(ctx context.Context, viewerID int64, viewerSpaceID string, otherSpaceID string, cursor string, limit int) ([]SpaceMessageRecord, error) {
- args := []any{viewerID, viewerSpaceID, otherSpaceID}
- query := `
- SELECT
- 'post_like:' || p.post_id::text || ':' || pl.actor_space_id AS message_id,
- 'post_like' AS kind,
- sender_space.owner_id AS sender_id,
- pl.actor_space_id AS sender_space_id,
- recipient_space.owner_id AS recipient_id,
- p.space_id AS recipient_space_id,
- '\x'::bytea AS message_cipher,
- '\x'::bytea AS encrypted_message_key,
- NULL::bigint AS reply_post_id,
- NULL::text AS reply_message_id,
- 0 AS likes,
- FALSE AS viewer_liked,
- FALSE AS is_deleted,
- pl.created_at,
- pl.created_at AS updated_at,
- CASE WHEN pl.actor_space_id = $2 THEN 'You liked a post' ELSE 'Liked your post' END AS text,
- p.post_id AS quote_post_id,
- p.space_id AS quote_space_id,
- p.encrypted_post_key AS quote_encrypted_post_key,
- p.caption_cipher AS quote_caption_cipher,
- p.key_version AS quote_key_version,
- asset.object_key AS quote_object_key,
- sender_space.owner_id,
- sender_space.space_id,
- sender_space.space_slug,
- sender_space.public_key,
- sender_space.current_version,
- sender_space.encrypted_profile,
- sender_avatar.object_id,
- sender_avatar.size,
- sender_space.updated_at,
- (SELECT COUNT(*) FROM space_friend_shares fs WHERE fs.space_id = sender_space.space_id) AS sender_friends,
- (SELECT COUNT(*) FROM space_posts sp WHERE sp.space_id = sender_space.space_id AND sp.is_deleted = FALSE) AS sender_posts,
- recipient_space.owner_id,
- recipient_space.space_id,
- recipient_space.space_slug,
- recipient_space.public_key,
- recipient_space.current_version,
- recipient_space.encrypted_profile,
- recipient_avatar.object_id,
- recipient_avatar.size,
- recipient_space.updated_at,
- (SELECT COUNT(*) FROM space_friend_shares fs WHERE fs.space_id = recipient_space.space_id) AS recipient_friends,
- (SELECT COUNT(*) FROM space_posts rp WHERE rp.space_id = recipient_space.space_id AND rp.is_deleted = FALSE) AS recipient_posts
- FROM space_post_likes pl
- JOIN space_posts p ON p.post_id = pl.post_id
- JOIN spaces sender_space ON sender_space.space_id = pl.actor_space_id
- LEFT JOIN space_profile_assets sender_avatar ON sender_avatar.space_id = sender_space.space_id AND sender_avatar.asset_type = 'avatar'
- JOIN spaces recipient_space ON recipient_space.space_id = p.space_id
- LEFT JOIN space_profile_assets recipient_avatar ON recipient_avatar.space_id = recipient_space.space_id AND recipient_avatar.asset_type = 'avatar'
- LEFT JOIN LATERAL (
- SELECT object_key
- FROM space_post_assets
- WHERE post_id = p.post_id AND p.is_deleted = FALSE
- ORDER BY position ASC, asset_id ASC
- LIMIT 1
- ) asset ON TRUE
- WHERE (
- (pl.actor_space_id = $2 AND p.space_id = $3)
- OR
- (pl.actor_space_id = $3 AND p.space_id = $2)
- )
- AND (sender_space.owner_id = $1 OR recipient_space.owner_id = $1)
- AND p.is_deleted = FALSE`
- if cursorCreatedAt, cursorMessageID, ok := parseMessageCursor(cursor); ok {
- args = append(args, cursorCreatedAt, cursorMessageID)
- query += ` AND (pl.created_at, 'post_like:' || p.post_id::text || ':' || pl.actor_space_id) < ($4, $5)`
- }
- args = append(args, limit)
- query += ` ORDER BY pl.created_at DESC, 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([]SpaceMessageRecord, 0, limit)
- 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, "")
- }
- return out, nil
-}
-
func (r *MessagesRepository) SetLike(ctx context.Context, messageID string, actorSpaceID string, like bool) error {
if like {
- _, err := r.DB.ExecContext(ctx, `INSERT INTO space_message_likes (message_id, actor_space_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, messageID, actorSpaceID)
+ _, err := r.DB.ExecContext(ctx, `
+ UPDATE space_messages
+ SET recipient_liked_at = COALESCE(recipient_liked_at, now_utc_micro_seconds())
+ WHERE message_id = $1
+ AND recipient_space_id = $2
+ AND kind <> 'post_like'
+ AND is_deleted = FALSE
+ `, messageID, actorSpaceID)
return stacktrace.Propagate(err, "")
}
- _, err := r.DB.ExecContext(ctx, `DELETE FROM space_message_likes WHERE message_id = $1 AND actor_space_id = $2`, messageID, actorSpaceID)
+ _, err := r.DB.ExecContext(ctx, `
+ UPDATE space_messages
+ SET recipient_liked_at = NULL
+ WHERE message_id = $1
+ AND recipient_space_id = $2
+ AND kind <> 'post_like'
+ `, messageID, actorSpaceID)
return stacktrace.Propagate(err, "")
}
@@ -286,6 +206,7 @@ func (r *MessagesRepository) DeleteMessage(ctx context.Context, messageID string
AND m.sender_space_id = sender_space.space_id
AND sender_space.owner_id = $2
AND m.sender_space_id = $3
+ AND m.kind <> 'post_like'
AND m.is_deleted = FALSE
`, messageID, senderID, senderSpaceID)
if err != nil {
@@ -298,9 +219,6 @@ func (r *MessagesRepository) DeleteMessage(ctx context.Context, messageID string
if affected == 0 {
return sql.ErrNoRows
}
- if _, err := tx.ExecContext(ctx, `DELETE FROM space_message_likes WHERE message_id = $1`, messageID); err != nil {
- return stacktrace.Propagate(err, "")
- }
if err := tx.Commit(); err != nil {
return stacktrace.Propagate(err, "")
}
@@ -321,85 +239,45 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
rows, err := r.DB.QueryContext(ctx, `
WITH message_candidates AS (
SELECT
- 'message' AS activity_type,
- 'message:' || m.message_id AS activity_id,
+ CASE WHEN m.kind = 'post_like' THEN 'post_like' ELSE 'message' END AS activity_type,
+ CASE WHEN m.kind = 'post_like' THEN m.message_id ELSE 'message:' || m.message_id END AS activity_id,
m.created_at AS activity_created_at,
CASE WHEN m.sender_space_id = $2 THEN m.recipient_space_id ELSE m.sender_space_id END AS friend_space_id,
- m.message_id,
- CASE WHEN m.kind = 'post_reply' THEN m.reply_post_id ELSE NULL::bigint END AS post_id,
- CASE WHEN m.recipient_space_id = $2 THEN m.created_at ELSE NULL::bigint END AS notification_created_at,
- FALSE AS is_outgoing
+ CASE WHEN m.kind = 'post_like' THEN NULL::text ELSE m.message_id END AS message_id,
+ CASE WHEN m.kind IN ('post_reply', 'post_like') THEN m.reply_post_id ELSE NULL::bigint END AS post_id,
+ CASE
+ WHEN m.kind = 'post_like' AND m.recipient_space_id = $2 THEN m.created_at
+ WHEN m.kind <> 'post_like' AND m.recipient_space_id = $2 THEN m.created_at
+ ELSE NULL::bigint
+ END AS notification_created_at,
+ (m.sender_space_id = $2) AS is_outgoing
FROM space_messages m
+ LEFT JOIN space_posts p ON p.post_id = m.reply_post_id
WHERE (m.sender_space_id = $2 OR m.recipient_space_id = $2)
AND m.is_deleted = FALSE
AND NOT (m.kind = 'post_reply' AND m.recipient_space_id = $2)
+ AND (
+ m.kind <> 'post_like'
+ OR (m.reply_post_id IS NOT NULL AND p.is_deleted = FALSE)
+ )
UNION ALL
SELECT
'message_like' AS activity_type,
- 'message_like:' || ml.message_id || ':' || ml.actor_space_id AS activity_id,
- ml.created_at AS activity_created_at,
- liker_space.space_id AS friend_space_id,
- m.message_id,
- NULL::bigint AS post_id,
- ml.created_at AS notification_created_at,
- FALSE AS is_outgoing
- FROM space_message_likes ml
- JOIN space_messages m ON m.message_id = ml.message_id
- JOIN spaces liker_space ON liker_space.space_id = ml.actor_space_id
- WHERE m.sender_space_id = $2
- AND m.recipient_space_id = ml.actor_space_id
- AND ml.actor_space_id <> $2
- AND m.is_deleted = FALSE
-
- UNION ALL
-
- SELECT
- 'message_like' AS activity_type,
- 'message_like:' || ml.message_id || ':' || ml.actor_space_id AS activity_id,
- ml.created_at AS activity_created_at,
- m.sender_space_id AS friend_space_id,
+ 'message_like:' || m.message_id || ':' || m.recipient_space_id AS activity_id,
+ m.recipient_liked_at AS activity_created_at,
+ CASE WHEN m.sender_space_id = $2 THEN m.recipient_space_id ELSE m.sender_space_id END AS friend_space_id,
m.message_id,
NULL::bigint AS post_id,
- NULL::bigint AS notification_created_at,
- TRUE AS is_outgoing
- FROM space_message_likes ml
- JOIN space_messages m ON m.message_id = ml.message_id
- WHERE ml.actor_space_id = $2
- AND m.recipient_space_id = $2
- AND m.sender_space_id <> $2
+ CASE WHEN m.sender_space_id = $2 THEN m.recipient_liked_at ELSE NULL::bigint END AS notification_created_at,
+ (m.recipient_space_id = $2) AS is_outgoing
+ FROM space_messages m
+ WHERE (m.sender_space_id = $2 OR m.recipient_space_id = $2)
+ AND m.sender_space_id <> m.recipient_space_id
+ AND m.kind <> 'post_like'
AND m.is_deleted = FALSE
- ),
- post_like_events AS (
- SELECT
- actor_space.space_id AS friend_space_id,
- p.post_id,
- MAX(pl.created_at) AS liked_at,
- MAX(pl.created_at) AS notification_created_at,
- FALSE AS is_outgoing
- FROM space_post_likes pl
- JOIN space_posts p ON p.post_id = pl.post_id
- JOIN spaces actor_space ON actor_space.space_id = pl.actor_space_id
- WHERE p.space_id = $2
- AND pl.actor_space_id <> $2
- AND p.is_deleted = FALSE
- GROUP BY actor_space.space_id, p.post_id
-
- UNION ALL
-
- SELECT
- p.space_id AS friend_space_id,
- p.post_id,
- MAX(pl.created_at) AS liked_at,
- NULL::bigint AS notification_created_at,
- TRUE AS is_outgoing
- FROM space_post_likes pl
- JOIN space_posts p ON p.post_id = pl.post_id
- WHERE pl.actor_space_id = $2
- AND p.space_id <> $2
- AND p.is_deleted = FALSE
- GROUP BY p.space_id, p.post_id
+ AND m.recipient_liked_at IS NOT NULL
),
post_reply_events AS (
SELECT DISTINCT ON (m.sender_space_id, m.reply_post_id)
@@ -417,18 +295,6 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
AND p.space_id = $2
ORDER BY m.sender_space_id, m.reply_post_id, m.created_at DESC, m.message_id DESC
),
- post_like_candidates AS (
- SELECT
- 'post_like' AS activity_type,
- 'post_like:' || l.post_id::text || ':' || l.friend_space_id AS activity_id,
- l.liked_at AS activity_created_at,
- l.friend_space_id,
- NULL::text AS message_id,
- l.post_id,
- l.notification_created_at,
- l.is_outgoing
- FROM post_like_events l
- ),
post_reply_candidates AS (
SELECT
'post_reply' AS activity_type,
@@ -440,23 +306,21 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
r.replied_at AS notification_created_at,
FALSE AS is_outgoing
FROM post_reply_events r
- ),
- activity_candidates AS (
- SELECT * FROM message_candidates
- UNION ALL
- SELECT * FROM post_like_candidates
- UNION ALL
- SELECT * FROM post_reply_candidates
- ),
- readable_activities AS (
- SELECT
- m.sender_space_id AS friend_space_id,
- m.created_at AS readable_created_at
- FROM space_messages m
- WHERE m.recipient_space_id = $2
- AND m.sender_space_id <> $2
- AND m.kind = 'regular'
- AND m.is_deleted = FALSE
+ ),
+ activity_candidates AS (
+ SELECT * FROM message_candidates
+ UNION ALL
+ SELECT * FROM post_reply_candidates
+ ),
+ readable_activities AS (
+ SELECT
+ m.sender_space_id AS friend_space_id,
+ m.created_at AS readable_created_at
+ FROM space_messages m
+ WHERE m.recipient_space_id = $2
+ AND m.sender_space_id <> $2
+ AND m.kind = 'regular'
+ AND m.is_deleted = FALSE
UNION ALL
@@ -483,61 +347,37 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
WHERE ra.readable_created_at > COALESCE(nrm.read_at, 0)
GROUP BY ra.friend_space_id
),
- post_like_unread_counts AS (
- SELECT
- actor_space.space_id AS friend_space_id,
- COUNT(*) AS unread_count
- FROM space_post_likes pl
- JOIN space_posts p ON p.post_id = pl.post_id
- JOIN spaces actor_space ON actor_space.space_id = pl.actor_space_id
- LEFT JOIN space_notification_read_markers nrm
- ON nrm.viewer_space_id = $2
- AND nrm.friend_space_id = actor_space.space_id
- WHERE p.space_id = $2
- AND pl.actor_space_id <> $2
- AND p.is_deleted = FALSE
- AND pl.created_at > COALESCE(nrm.read_at, 0)
- GROUP BY actor_space.space_id
+ latest_activities AS (
+ SELECT DISTINCT ON (friend_space_id)
+ friend_space_id,
+ activity_created_at AS sort_created_at,
+ activity_id AS sort_id
+ FROM activity_candidates
+ ORDER BY friend_space_id, activity_created_at DESC, activity_id DESC
),
- latest_activities AS (
- SELECT DISTINCT ON (friend_space_id)
- friend_space_id,
- activity_created_at AS sort_created_at,
- activity_id AS sort_id
- FROM activity_candidates
- ORDER BY friend_space_id, activity_created_at DESC, activity_id DESC
- ),
- candidates_with_read_state AS (
- SELECT
- c.*,
- COALESCE(nrm.read_at, 0) AS read_at,
- COALESCE(ruc.unread_count, 0) AS unread_count,
- COALESCE(pluc.unread_count, 0) AS post_like_unread_count,
- la.sort_created_at,
- la.sort_id,
- (
- c.notification_created_at IS NOT NULL
- AND c.notification_created_at > COALESCE(nrm.read_at, 0)
- ) AS notification_unread
- FROM activity_candidates c
- JOIN latest_activities la ON la.friend_space_id = c.friend_space_id
+ candidates_with_read_state AS (
+ SELECT
+ c.*,
+ COALESCE(nrm.read_at, 0) AS read_at,
+ COALESCE(ruc.unread_count, 0) AS unread_count,
+ la.sort_created_at,
+ la.sort_id,
+ (
+ c.notification_created_at IS NOT NULL
+ AND c.notification_created_at > COALESCE(nrm.read_at, 0)
+ ) AS notification_unread
+ FROM activity_candidates c
+ JOIN latest_activities la ON la.friend_space_id = c.friend_space_id
LEFT JOIN space_notification_read_markers nrm
ON nrm.viewer_space_id = $2
AND nrm.friend_space_id = c.friend_space_id
LEFT JOIN readable_unread_counts ruc
ON ruc.friend_space_id = c.friend_space_id
- LEFT JOIN post_like_unread_counts pluc
- ON pluc.friend_space_id = c.friend_space_id
),
ranked AS (
SELECT
c.*,
- CASE
- WHEN c.unread_count = 0
- AND c.post_like_unread_count = 1
- AND c.activity_type <> 'message_like' THEN 0
- ELSE c.unread_count + c.post_like_unread_count
- END AS conversation_unread_count,
+ c.unread_count AS conversation_unread_count,
BOOL_OR(c.notification_unread) OVER (PARTITION BY c.friend_space_id) AS conversation_notification_unread,
ROW_NUMBER() OVER (
PARTITION BY c.friend_space_id
@@ -580,8 +420,8 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID int
END AS encrypted_message_key,
m.reply_post_id,
m.reply_message_id,
- COALESCE((SELECT COUNT(*) FROM space_message_likes ml WHERE ml.message_id = m.message_id), 0) AS likes,
- COALESCE(EXISTS (SELECT 1 FROM space_message_likes ml WHERE ml.message_id = m.message_id AND ml.actor_space_id = $2), FALSE) AS viewer_liked,
+ COALESCE(m.recipient_liked_at IS NOT NULL, FALSE) AS liked,
+ COALESCE(m.recipient_liked_at IS NOT NULL AND m.recipient_space_id = $2, FALSE) AS viewer_liked,
COALESCE(m.is_deleted, FALSE) AS is_deleted,
COALESCE(m.created_at, 0) AS message_created_at,
COALESCE(m.updated_at, 0) AS message_updated_at,
@@ -672,64 +512,29 @@ func (r *MessagesRepository) GetLatestConversationActivityAt(ctx context.Context
WITH activity_candidates AS (
SELECT
m.created_at AS activity_created_at,
- 'message:' || m.message_id AS activity_id,
+ CASE WHEN m.kind = 'post_like' THEN m.message_id ELSE 'message:' || m.message_id END AS activity_id,
CASE WHEN m.sender_space_id = $1 THEN m.recipient_space_id ELSE m.sender_space_id END AS friend_space_id
FROM space_messages m
+ LEFT JOIN space_posts p ON p.post_id = m.reply_post_id
WHERE (m.sender_space_id = $1 OR m.recipient_space_id = $1)
AND m.is_deleted = FALSE
AND NOT (m.kind = 'post_reply' AND m.recipient_space_id = $1)
+ AND (
+ m.kind <> 'post_like'
+ OR (m.reply_post_id IS NOT NULL AND p.is_deleted = FALSE)
+ )
UNION ALL
SELECT
- ml.created_at AS activity_created_at,
- 'message_like:' || ml.message_id || ':' || ml.actor_space_id AS activity_id,
- liker_space.space_id AS friend_space_id
- FROM space_message_likes ml
- JOIN space_messages m ON m.message_id = ml.message_id
- JOIN spaces liker_space ON liker_space.space_id = ml.actor_space_id
- WHERE m.sender_space_id = $1
- AND m.recipient_space_id = ml.actor_space_id
- AND ml.actor_space_id <> $1
- AND m.is_deleted = FALSE
-
- UNION ALL
-
- SELECT
- ml.created_at AS activity_created_at,
- 'message_like:' || ml.message_id || ':' || ml.actor_space_id AS activity_id,
- m.sender_space_id AS friend_space_id
- FROM space_message_likes ml
- JOIN space_messages m ON m.message_id = ml.message_id
- WHERE ml.actor_space_id = $1
- AND m.recipient_space_id = $1
- AND m.sender_space_id <> $1
+ m.recipient_liked_at AS activity_created_at,
+ 'message_like:' || m.message_id || ':' || m.recipient_space_id AS activity_id,
+ CASE WHEN m.sender_space_id = $1 THEN m.recipient_space_id ELSE m.sender_space_id END AS friend_space_id
+ FROM space_messages m
+ WHERE (m.sender_space_id = $1 OR m.recipient_space_id = $1)
+ AND m.kind <> 'post_like'
AND m.is_deleted = FALSE
-
- UNION ALL
-
- SELECT
- pl.created_at AS activity_created_at,
- 'post_like:' || pl.post_id::text || ':' || pl.actor_space_id AS activity_id,
- actor_space.space_id AS friend_space_id
- FROM space_post_likes pl
- JOIN space_posts p ON p.post_id = pl.post_id
- JOIN spaces actor_space ON actor_space.space_id = pl.actor_space_id
- WHERE p.space_id = $1
- AND pl.actor_space_id <> $1
- AND p.is_deleted = FALSE
-
- UNION ALL
-
- SELECT
- pl.created_at AS activity_created_at,
- 'post_like:' || pl.post_id::text || ':' || p.space_id AS activity_id,
- p.space_id AS friend_space_id
- FROM space_post_likes pl
- JOIN space_posts p ON p.post_id = pl.post_id
- WHERE pl.actor_space_id = $1
- AND p.space_id <> $1
- AND p.is_deleted = FALSE
+ AND m.recipient_liked_at IS NOT NULL
UNION ALL
@@ -776,26 +581,25 @@ func (r *MessagesRepository) HasUnreadNotifications(ctx context.Context, viewerI
UNION ALL
SELECT
- liker_space.space_id AS friend_space_id,
- ml.created_at AS notification_created_at
- FROM space_message_likes ml
- JOIN space_messages m ON m.message_id = ml.message_id
- JOIN spaces liker_space ON liker_space.space_id = ml.actor_space_id
+ m.recipient_space_id AS friend_space_id,
+ m.recipient_liked_at AS notification_created_at
+ FROM space_messages m
WHERE m.sender_space_id = $1
- AND m.recipient_space_id = ml.actor_space_id
- AND ml.actor_space_id <> $1
+ AND m.recipient_space_id <> $1
+ AND m.kind <> 'post_like'
AND m.is_deleted = FALSE
+ AND m.recipient_liked_at IS NOT NULL
UNION ALL
SELECT
- actor_space.space_id AS friend_space_id,
- pl.created_at AS notification_created_at
- FROM space_post_likes pl
- JOIN space_posts p ON p.post_id = pl.post_id
- JOIN spaces actor_space ON actor_space.space_id = pl.actor_space_id
- WHERE p.space_id = $1
- AND pl.actor_space_id <> $1
+ m.sender_space_id AS friend_space_id,
+ m.created_at AS notification_created_at
+ FROM space_messages m
+ JOIN space_posts p ON p.post_id = m.reply_post_id
+ WHERE m.recipient_space_id = $1
+ AND m.sender_space_id <> $1
+ AND m.kind = 'post_like'
AND p.is_deleted = FALSE
UNION ALL
@@ -864,7 +668,7 @@ func scanMessageRecord(scanner interface{ Scan(dest ...any) error }) (*SpaceMess
&rec.EncryptedMessageKey,
&rec.ReplyPostID,
&rec.ReplyMessageID,
- &rec.Likes,
+ &rec.Liked,
&rec.ViewerLiked,
&rec.IsDeleted,
&rec.CreatedAt,
@@ -921,7 +725,7 @@ func scanMessageConversationRecord(scanner interface{ Scan(dest ...any) error })
&message.EncryptedMessageKey,
&message.ReplyPostID,
&message.ReplyMessageID,
- &message.Likes,
+ &message.Liked,
&message.ViewerLiked,
&message.IsDeleted,
&message.CreatedAt,
diff --git a/server/space/repo/module.go b/server/space/repo/module.go
index 614c95b1c3..4a6f50cdfa 100644
--- a/server/space/repo/module.go
+++ b/server/space/repo/module.go
@@ -99,7 +99,6 @@ type SpacePostRecord struct {
CaptionCipher []byte
KeyVersion int
CreatedAt int64
- Likes int64
ViewerLiked bool
}
@@ -141,7 +140,7 @@ type SpaceMessageRecord struct {
EncryptedMessageKey []byte
ReplyPostID sql.NullInt64
ReplyMessageID sql.NullString
- Likes int64
+ Liked bool
ViewerLiked bool
IsDeleted bool
Text string
diff --git a/server/space/repo/module_test.go b/server/space/repo/module_test.go
index 8060e39b0c..2aac52687d 100644
--- a/server/space/repo/module_test.go
+++ b/server/space/repo/module_test.go
@@ -212,8 +212,8 @@ func TestSpaceAccountDeletionResetUserAccess(t *testing.T) {
require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_friend_shares WHERE space_id = $1 OR friend_space_id = $1`, aliceSpace.SpaceID))
require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_friend_requests WHERE requester_space_id = $1 OR target_space_id = $1`, aliceSpace.SpaceID))
require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_notification_read_markers WHERE viewer_space_id = $1 OR friend_space_id = $1`, aliceSpace.SpaceID))
- require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_post_likes WHERE post_id = $1`, postID))
- require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_message_likes WHERE message_id = $1`, message.MessageID))
+ require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_messages WHERE kind = 'post_like' AND reply_post_id = $1`, postID))
+ require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_messages WHERE message_id = $1 AND recipient_liked_at IS NOT NULL`, message.MessageID))
_, _, err = testConfirmFriendRequest(ctx, module, charlieID, charlieSpace.SpaceID, pendingRequest.RequestID, "charlie-share-key", charlieSpace.CurrentVersion)
require.Error(t, err)
require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_friend_shares WHERE (space_id = $1 AND friend_space_id = $2) OR (space_id = $2 AND friend_space_id = $1)`, aliceSpace.SpaceID, charlieSpace.SpaceID))
@@ -322,18 +322,18 @@ func TestSpaceMessagesThreadAndConversations(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "regular", message.Kind)
require.Equal(t, testSpaceBytes("sender-key"), message.EncryptedMessageKey)
- require.Equal(t, int64(0), message.Likes)
+ require.False(t, message.Liked)
require.False(t, message.ViewerLiked)
require.NoError(t, module.Messages.SetLike(ctx, message.MessageID, aliceSpace.SpaceID, true))
setMessageLikeCreatedAt(t, module, 1500, message.MessageID, aliceSpace.SpaceID)
likedMessage, err := module.Messages.GetMessage(ctx, message.MessageID, aliceID, aliceSpace.SpaceID)
require.NoError(t, err)
- require.Equal(t, int64(1), likedMessage.Likes)
+ require.True(t, likedMessage.Liked)
require.True(t, likedMessage.ViewerLiked)
bobViewedMessage, err := module.Messages.GetMessage(ctx, message.MessageID, bobID, bobSpace.SpaceID)
require.NoError(t, err)
- require.Equal(t, int64(1), bobViewedMessage.Likes)
+ require.True(t, bobViewedMessage.Liked)
require.False(t, bobViewedMessage.ViewerLiked)
reply, err := module.Messages.CreateMessage(ctx, CreateSpaceMessageRecord{
@@ -375,7 +375,7 @@ func TestSpaceMessagesThreadAndConversations(t *testing.T) {
require.True(t, deletedMessage.IsDeleted)
require.Empty(t, deletedMessage.MessageCipher)
require.Empty(t, deletedMessage.EncryptedMessageKey)
- require.Equal(t, int64(0), deletedMessage.Likes)
+ require.False(t, deletedMessage.Liked)
aliceThread, nextCursor, err = module.Messages.ListThread(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, "", 10)
require.NoError(t, err)
require.Empty(t, nextCursor)
@@ -1052,7 +1052,7 @@ func TestSpaceModuleLifecycle(t *testing.T) {
requireQueuedTempObject(t, module, "space/alice/post1/full", TempObjectPurposePost, "b2-eu-cen")
requireQueuedTempObject(t, module, "space/alice/post1/thumb", TempObjectPurposePost, "b2-eu-cen")
var likeCount int
- err = module.Posts.DB.QueryRow(`SELECT COUNT(*) FROM space_post_likes WHERE post_id = $1`, postID).Scan(&likeCount)
+ err = module.Posts.DB.QueryRow(`SELECT COUNT(*) FROM space_messages WHERE kind = 'post_like' AND reply_post_id = $1`, postID).Scan(&likeCount)
require.NoError(t, err)
require.Zero(t, likeCount)
@@ -2242,7 +2242,7 @@ func setPostCreatedAt(t *testing.T, module *Module, createdAt int64, postIDs ...
func setPostLikeCreatedAt(t *testing.T, module *Module, createdAt, postID int64, actorSpaceID string) {
t.Helper()
- _, err := module.Posts.DB.Exec(`UPDATE space_post_likes SET created_at = $1 WHERE post_id = $2 AND actor_space_id = $3`, createdAt, postID, actorSpaceID)
+ _, err := module.Posts.DB.Exec(`UPDATE space_messages SET created_at = $1, updated_at = $1 WHERE kind = 'post_like' AND reply_post_id = $2 AND sender_space_id = $3`, createdAt, postID, actorSpaceID)
require.NoError(t, err)
}
@@ -2266,6 +2266,6 @@ func setMessageCreatedAt(t *testing.T, module *Module, createdAt int64, messageI
func setMessageLikeCreatedAt(t *testing.T, module *Module, createdAt int64, messageID string, actorSpaceID string) {
t.Helper()
- _, err := module.Messages.DB.Exec(`UPDATE space_message_likes SET created_at = $1 WHERE message_id = $2 AND actor_space_id = $3`, createdAt, messageID, actorSpaceID)
+ _, err := module.Messages.DB.Exec(`UPDATE space_messages SET recipient_liked_at = $1 WHERE message_id = $2 AND recipient_space_id = $3`, createdAt, messageID, actorSpaceID)
require.NoError(t, err)
}
diff --git a/server/space/repo/posts.go b/server/space/repo/posts.go
index 7bc6102f15..d81ae4d0a2 100644
--- a/server/space/repo/posts.go
+++ b/server/space/repo/posts.go
@@ -19,7 +19,6 @@ func postRecordSelectSQL(viewerLikedExpr string) string {
(SELECT COUNT(*) FROM space_posts ap WHERE ap.space_id = w.space_id AND ap.is_deleted = FALSE) AS author_posts,
p.encrypted_post_key, p.caption_cipher,
p.key_version, p.created_at,
- (SELECT COUNT(*) FROM space_post_likes pl WHERE pl.post_id = p.post_id) AS likes,
` + viewerLikedExpr + ` AS viewer_liked`
}
@@ -87,7 +86,7 @@ func (r *PostsRepository) CreatePost(ctx context.Context, ownerID int64, spaceID
func (r *PostsRepository) GetPost(ctx context.Context, postID int64, viewerID int64, viewerSpaceID string) (*SpacePostRecord, error) {
query := postRecordSelectSQL(`
- EXISTS (SELECT 1 FROM space_post_likes pl WHERE pl.post_id = p.post_id AND pl.actor_space_id = $2)`) + `
+ EXISTS (SELECT 1 FROM space_messages m WHERE m.kind = 'post_like' AND m.reply_post_id = p.post_id AND m.sender_space_id = $2)`) + `
FROM space_posts p
JOIN spaces w ON w.space_id = p.space_id
LEFT JOIN space_profile_assets w_avatar ON w_avatar.space_id = w.space_id AND w_avatar.asset_type = 'avatar'
@@ -103,7 +102,7 @@ func (r *PostsRepository) ListPostsBySpace(ctx context.Context, spaceID string,
}
args := []any{spaceID, viewerSpaceID}
query := postRecordSelectSQL(`
- EXISTS (SELECT 1 FROM space_post_likes pl WHERE pl.post_id = p.post_id AND pl.actor_space_id = $2)`) + `
+ EXISTS (SELECT 1 FROM space_messages m WHERE m.kind = 'post_like' AND m.reply_post_id = p.post_id AND m.sender_space_id = $2)`) + `
FROM space_posts p
JOIN spaces w ON w.space_id = p.space_id
LEFT JOIN space_profile_assets w_avatar ON w_avatar.space_id = w.space_id AND w_avatar.asset_type = 'avatar'
@@ -138,7 +137,7 @@ func (r *PostsRepository) ListFeed(ctx context.Context, viewerID int64, viewerSp
}
args := []any{viewerID, viewerSpaceID}
query := postRecordSelectSQL(`
- CASE WHEN p.space_id = $2 THEN FALSE ELSE EXISTS (SELECT 1 FROM space_post_likes pl WHERE pl.post_id = p.post_id AND pl.actor_space_id = $2) END`) + `
+ CASE WHEN p.space_id = $2 THEN FALSE ELSE EXISTS (SELECT 1 FROM space_messages m WHERE m.kind = 'post_like' AND m.reply_post_id = p.post_id AND m.sender_space_id = $2) END`) + `
FROM space_posts p
JOIN spaces w ON w.space_id = p.space_id
LEFT JOIN space_profile_assets w_avatar ON w_avatar.space_id = w.space_id AND w_avatar.asset_type = 'avatar'
@@ -233,7 +232,7 @@ func (r *PostsRepository) DeletePost(ctx context.Context, postID, ownerID int64)
if !isDeleted {
return nil, sql.ErrNoRows
}
- if _, err := tx.ExecContext(ctx, `DELETE FROM space_post_likes WHERE post_id = $1`, postID); err != nil {
+ if _, err := tx.ExecContext(ctx, `DELETE FROM space_messages WHERE kind = 'post_like' AND reply_post_id = $1`, postID); err != nil {
return nil, stacktrace.Propagate(err, "")
}
if err := tx.Commit(); err != nil {
@@ -279,7 +278,7 @@ func (r *PostsRepository) DeletePost(ctx context.Context, postID, ownerID int64)
}
keys = append(keys, object.key)
}
- if _, err := tx.ExecContext(ctx, `DELETE FROM space_post_likes WHERE post_id = $1`, postID); err != nil {
+ if _, err := tx.ExecContext(ctx, `DELETE FROM space_messages WHERE kind = 'post_like' AND reply_post_id = $1`, postID); err != nil {
return nil, stacktrace.Propagate(err, "")
}
if err := tx.Commit(); err != nil {
@@ -290,7 +289,16 @@ func (r *PostsRepository) DeletePost(ctx context.Context, postID, ownerID int64)
func (r *PostsRepository) SetLikeWithCreated(ctx context.Context, postID int64, actorSpaceID string, like bool) (bool, error) {
if like {
- res, err := r.DB.ExecContext(ctx, `INSERT INTO space_post_likes (post_id, actor_space_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, postID, actorSpaceID)
+ messageID := "post_like:" + strconv.FormatInt(postID, 10) + ":" + strings.TrimSpace(actorSpaceID)
+ res, err := r.DB.ExecContext(ctx, `
+ INSERT INTO space_messages (message_id, sender_space_id, recipient_space_id, kind, reply_post_id)
+ SELECT $1, $2, p.space_id, 'post_like', p.post_id
+ FROM space_posts p
+ WHERE p.post_id = $3
+ AND p.space_id <> $2
+ AND p.is_deleted = FALSE
+ ON CONFLICT DO NOTHING
+ `, messageID, actorSpaceID, postID)
if err != nil {
return false, stacktrace.Propagate(err, "")
}
@@ -300,7 +308,7 @@ func (r *PostsRepository) SetLikeWithCreated(ctx context.Context, postID int64,
}
return affected > 0, nil
}
- res, err := r.DB.ExecContext(ctx, `DELETE FROM space_post_likes WHERE post_id = $1 AND actor_space_id = $2`, postID, actorSpaceID)
+ res, err := r.DB.ExecContext(ctx, `DELETE FROM space_messages WHERE kind = 'post_like' AND reply_post_id = $1 AND sender_space_id = $2`, postID, actorSpaceID)
if err != nil {
return false, stacktrace.Propagate(err, "")
}
@@ -323,17 +331,17 @@ func (r *PostsRepository) ListPostLikers(ctx context.Context, postID int64, curs
liker_avatar.size, liker_space.updated_at,
(SELECT COUNT(*) FROM space_friend_shares fs WHERE fs.space_id = liker_space.space_id) AS liker_friends,
(SELECT COUNT(*) FROM space_posts lp WHERE lp.space_id = liker_space.space_id AND lp.is_deleted = FALSE) AS liker_posts,
- pl.created_at
- FROM space_post_likes pl
- JOIN spaces liker_space ON liker_space.space_id = pl.actor_space_id
+ m.created_at
+ FROM space_messages m
+ JOIN spaces liker_space ON liker_space.space_id = m.sender_space_id
LEFT JOIN space_profile_assets liker_avatar ON liker_avatar.space_id = liker_space.space_id AND liker_avatar.asset_type = 'avatar'
- WHERE pl.post_id = $1`
+ WHERE m.kind = 'post_like' AND m.reply_post_id = $1`
if cursorCreatedAt, cursorActorSpaceID, ok := parsePostLikerCursor(cursor); ok {
args = append(args, cursorCreatedAt, cursorActorSpaceID)
- query += ` AND (pl.created_at, pl.actor_space_id) < ($2, $3)`
+ query += ` AND (m.created_at, m.sender_space_id) < ($2, $3)`
}
args = append(args, limit+1)
- query += ` ORDER BY pl.created_at DESC, pl.actor_space_id DESC LIMIT $` + strconv.Itoa(len(args))
+ query += ` ORDER BY m.created_at DESC, m.sender_space_id DESC LIMIT $` + strconv.Itoa(len(args))
rows, err := r.DB.QueryContext(ctx, query, args...)
if err != nil {
return nil, "", stacktrace.Propagate(err, "")
@@ -391,7 +399,7 @@ func scanPostRecord(scanner interface{ Scan(dest ...any) error }) (*SpacePostRec
var rec SpacePostRecord
dest := []any{&rec.PostID, &rec.SpaceID, &rec.SpaceSlug, &rec.OwnerID}
dest = append(dest, spaceActorScanDest(&rec.Author)...)
- dest = append(dest, &rec.EncryptedPostKey, &rec.CaptionCipher, &rec.KeyVersion, &rec.CreatedAt, &rec.Likes, &rec.ViewerLiked)
+ dest = append(dest, &rec.EncryptedPostKey, &rec.CaptionCipher, &rec.KeyVersion, &rec.CreatedAt, &rec.ViewerLiked)
if err := scanner.Scan(dest...); err != nil {
return nil, stacktrace.Propagate(err, "")
}
diff --git a/web/apps/space/src/components/SpaceMessagesPage.tsx b/web/apps/space/src/components/SpaceMessagesPage.tsx
index adbde0989d..fd7e7ed1b8 100644
--- a/web/apps/space/src/components/SpaceMessagesPage.tsx
+++ b/web/apps/space/src/components/SpaceMessagesPage.tsx
@@ -110,7 +110,7 @@ const createLocalMessage = ({
id: createLocalMessageID(),
isDeleted: false,
kind: "regular",
- likeCount: 0,
+ liked: false,
recipient,
replyMessageId,
sender: currentProfileMessageActor(profile),
@@ -595,14 +595,7 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({
setMessages((currentMessages) =>
currentMessages.map((message) =>
message.id == messageId
- ? {
- ...message,
- likeCount: Math.max(
- 0,
- message.likeCount + (liked ? 1 : -1),
- ),
- viewerLiked: liked,
- }
+ ? { ...message, liked, viewerLiked: liked }
: message,
),
);
diff --git a/web/apps/space/src/screens/MessagesScreen.tsx b/web/apps/space/src/screens/MessagesScreen.tsx
index 5fce506f9a..8b6ad553e0 100644
--- a/web/apps/space/src/screens/MessagesScreen.tsx
+++ b/web/apps/space/src/screens/MessagesScreen.tsx
@@ -1258,7 +1258,7 @@ const MessageBubble: React.FC<{
minWidth: 0,
position: "relative",
width: "100%",
- zIndex: isHighlighted ? 3 : message.likeCount > 0 ? 1 : "auto",
+ zIndex: isHighlighted ? 3 : message.liked ? 1 : "auto",
}}
>
<Box
@@ -1350,7 +1350,7 @@ const MessageBubble: React.FC<{
>
{message.text}
</Box>
- {message.likeCount > 0 && (
+ {message.liked && (
<Box
component="span"
role="img"
diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.ts
index 0900d58618..9ba7e1ee31 100644
--- a/web/apps/space/src/services/space.ts
+++ b/web/apps/space/src/services/space.ts
@@ -127,8 +127,8 @@ interface SpaceMessageResponse {
id?: string;
isDeleted?: boolean;
kind: SpaceMessageKindResponse;
+ liked?: boolean;
messageId: string;
- likes?: number;
quote?: SpaceMessageQuoteResponse;
recipient: SpaceActor;
replyMessageId?: string;
@@ -246,7 +246,7 @@ export interface SpaceMessage {
id: string;
isDeleted: boolean;
kind: SpaceMessageKind;
- likeCount: number;
+ liked: boolean;
quote?: SpaceMessageQuote;
recipient: FriendProfile;
replyMessageId?: string;
@@ -306,12 +306,12 @@ interface SpaceUnreadStatusResponse {
notificationsUnread: boolean;
}
-type SpaceFriendRequestContext = SpaceAccountCtxHandle & {
+interface SpaceFriendRequestContext {
confirm_friend_request: (requestId: bigint) => Promise<unknown>;
delete_friend_request: (requestId: bigint) => Promise<void>;
list_friend_requests: () => Promise<SpaceFriendRequestResponse[]>;
request_friend_by_username: (username: string) => Promise<unknown>;
-};
+}
const timestampMsFromSpaceDate = (value: string) => {
const parsed = Date.parse(value);
@@ -646,7 +646,7 @@ const messageFromSpaceMessage = async (
id: message.messageId || message.id || message.createdAt,
isDeleted: Boolean(message.isDeleted),
kind: message.kind,
- likeCount: message.likes ?? 0,
+ liked: Boolean(message.liked),
quote,
recipient,
replyMessageId: message.replyMessageId,
@@ -1072,29 +1072,29 @@ export const loadCurrentMessageConversations =
}
};
-export const loadCurrentFriendRequestConversations =
- async (): Promise<SpaceMessageConversation[]> => {
- const ctx = await ensureCurrentSpaceContext();
- try {
- const requests = (await (
- ctx as SpaceFriendRequestContext
- ).list_friend_requests()) as SpaceFriendRequestResponse[];
- return requests.map((request) => ({
- friend: actorProfile(request.requester),
- latestActivity: {
- createdAtMs: timestampMsFromSpaceDate(request.createdAt),
- id: `friend_request:${request.requestId}`,
- outgoing: false,
- type: "friend_request",
- },
- notificationUnread: true,
- unread: true,
- unreadCount: 1,
- }));
- } finally {
- releaseCurrentSpaceContext(ctx);
- }
- };
+export const loadCurrentFriendRequestConversations = async (): Promise<
+ SpaceMessageConversation[]
+> => {
+ const ctx = await ensureCurrentSpaceContext();
+ try {
+ const friendRequestCtx = ctx as unknown as SpaceFriendRequestContext;
+ const requests = await friendRequestCtx.list_friend_requests();
+ return requests.map((request) => ({
+ friend: actorProfile(request.requester),
+ latestActivity: {
+ createdAtMs: timestampMsFromSpaceDate(request.createdAt),
+ id: `friend_request:${request.requestId}`,
+ outgoing: false,
+ type: "friend_request",
+ },
+ notificationUnread: true,
+ unread: true,
+ unreadCount: 1,
+ }));
+ } finally {
+ releaseCurrentSpaceContext(ctx);
+ }
+};
export const confirmCurrentFriendRequest = async (requestId: number) => {
const ctx = await ensureCurrentSpaceContext();