π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add space email notifications
Anand Baburajan2d35203433f8
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 4bad2beb27..036752d1fd 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -975,7 +975,7 @@ func main() {userEntityController := &userEntityCtrl.Controller{Repo: userEntityRepo}userEntityHandler := &api.UserEntityHandler{Controller: userEntityController}spaceRepos := spacerepo.NewModule(db, s3Config)- spaceModule := spacecontroller.NewModule(spaceRepos, userAuthRepo, &spacecontroller.SpaceEmailNotifier{UserRepo: userRepo})+ spaceModule := spacecontroller.NewModule(spaceRepos, userAuthRepo, &spacecontroller.SpaceEmailSender{UserRepo: userRepo})spaceHandlers := spaceapi.NewHandlers(spaceModule)privateAPI.POST("/user-entity/key", userEntityHandler.CreateKey)diff --git a/server/mail-templates/space_notification.html b/server/mail-templates/space_notification.htmlnew file mode 100644index 0000000000..bdd2cb3ed2--- /dev/null+++ b/server/mail-templates/space_notification.html@@ -0,0 +1,7 @@+{{define "content"}}+<p>Hi,</p>+<p>{{ .Message }}.</p>+<p>+ <a class="button" href="{{ .AppURL }}" target="_blank">Open Space</a>+</p>+{{end}}diff --git a/server/mail-templates/space_post_created.html b/server/mail-templates/space_post_created.htmldeleted file mode 100644index 2ae6d3b0cb..0000000000--- a/server/mail-templates/space_post_created.html+++ /dev/null@@ -1,184 +0,0 @@-<!doctype html>-<html>- <meta content="text/html; charset=utf-8" />- <meta- name="viewport"- content="width=device-width, initial-scale=1,- minimum-scale=1"- />- <style>- body {- background-color: #f0f1f3;- font-family: "Helvetica Neue", "Segoe UI", Helvetica, sans-serif;- font-size: 16px;- line-height: 27px;- margin: 0;- color: #444;- }-- pre {- background: #f4f4f4f4;- padding: 2px;- }-- table {- width: 100%;- border: 1px solid #ddd;- }-- table td {- border-color: #ddd;- padding: 5px;- }-- .wrap {- background-color: #fff;- padding: 30px;- max-width: 525px;- margin: 0 auto;- border-radius: 5px;- }-- .button {- background: #0055d4;- border-radius: 3px;- text-decoration: none !important;- color: #fff !important;- font-weight: bold;- padding: 10px 30px;- display: inline-block;- }-- .button:hover {- background: #111;- }-- .footer {- text-align: center;- font-size: 12px;- color: #888;- }-- .footer a {- color: #888;- margin-right: 5px;- }-- .gutter {- padding: 30px;- }-- img {- max-width: 100%;- height: auto;- }-- a {- color: #0055d4;- }-- a:hover {- color: #111;- }-- @media screen and (max-width: 600px) {- .wrap {- max-width: auto;- }-- .gutter {- padding: 10px;- }- }-- .footer-icons {- padding: 4px !important;- width: 24px !important;- }- </style>-- <body>- <div class="gutter" style="padding: 4px"> </div>- <div- class="wrap"- style="- background-color: rgb(255, 255, 255);- padding: 2px 30px 30px 30px;- max-width: 525px;- margin: 0 auto;- border-radius: 5px;- font-size: 16px;- "- >- <p>Hi,</p>- <p>{{ .Author }} has shared a new post.</p>- <p>- <a class="button" href="{{ .AppURL }}" target="_blank">Check it out</a>- </p>- </div>- <br />- <div- class="footer"- style="text-align: center; font-size: 12px; color: rgb(136, 136, 136)"- >- <div>- <a href="https://ente.com" target="_blank"- ><img- src="https://email-assets.ente.io/ente-green.png"- style="width: 100px; padding: 24px"- title="Ente"- alt="Ente"- /></a>- </div>- <div>- <a href="https://fosstodon.org/@ente" target="_blank"- ><img- src="https://email-assets.ente.io/mastodon-icon.png"- class="footer-icons"- style="width: 24px; padding: 4px"- title="Mastodon"- alt="Mastodon"- /></a>- <a href="https://twitter.com/enteio" target="_blank"- ><img- src="https://email-assets.ente.io/twitter-icon.png"- class="footer-icons"- style="width: 24px; padding: 4px"- title="Twitter"- alt="Twitter"- /></a>- <a href="https://ente.com/discord" target="_blank"- ><img- src="https://email-assets.ente.io/discord-icon.png"- class="footer-icons"- style="width: 24px; padding: 4px"- title="Discord"- alt="Discord"- /></a>- <a href="https://github.com/ente-io" target="_blank"- ><img- src="https://email-assets.ente.io/github-icon.png"- class="footer-icons"- style="width: 24px; padding: 4px"- title="GitHub"- alt="GitHub"- /></a>-- <a href="https://www.youtube.com/@entestudio" target="_blank"- ><img- src="https://email-assets.ente.io/youtube-icon.png"- class="footer-icons"- style="width: 24px; padding: 4px"- title="YouTube"- alt="YouTube"- /></a>- </div>- <p>- Ente Technologies, Inc.- <br />- 1111B S Governors Ave 6032 Dover, DE 19904- </p>- <br />- </div>- </body>-</html>diff --git a/server/space/controller/friends.go b/server/space/controller/friends.goindex 377f29f4aa..7fb2984030 100644--- a/server/space/controller/friends.go+++ b/server/space/controller/friends.go@@ -13,9 +13,10 @@ import ()type FriendsController struct {- FriendsRepo *repo.FriendsRepository- SpacesRepo *repo.SpacesRepository- auth authDeps+ FriendsRepo *repo.FriendsRepository+ SpacesRepo *repo.SpacesRepository+ EmailNotifier SpaceEmailNotifier+ auth authDeps}func (c *FriendsController) Add(ctx *gin.Context, req models.AddFriendPayload) (*models.FriendStatusResponse, error) {@@ -51,10 +52,11 @@ func (c *FriendsController) Add(ctx *gin.Context, req models.AddFriendPayload) (if session.KeyVersion != req.TargetKeyVersion {return nil, ente.NewBadRequestWithMessage("targetKeyVersion does not match link session")}- if _, err := c.auth.requireSpaceOwner(ctx.Request.Context(), userID, strings.TrimSpace(req.RequesterSpaceID)); err != nil {+ requesterSpace, err := c.auth.requireSpaceOwner(ctx.Request.Context(), userID, strings.TrimSpace(req.RequesterSpaceID))+ if err != nil {return nil, err}- if err := c.FriendsRepo.AddFriend(+ created, err := c.FriendsRepo.AddFriendWithCreated(ctx.Request.Context(),userID,strings.TrimSpace(req.RequesterSpaceID),@@ -63,7 +65,8 @@ func (c *FriendsController) Add(ctx *gin.Context, req models.AddFriendPayload) (req.TargetKeyVersion,strings.TrimSpace(req.RequesterEncryptedSpaceKey),req.RequesterKeyVersion,- ); err != nil {+ )+ if err != nil {if errors.Is(stacktrace.RootCause(err), repo.ErrSelfFriendship) {return nil, ente.NewBadRequestWithMessage("cannot join your own space link")}@@ -75,6 +78,9 @@ func (c *FriendsController) Add(ctx *gin.Context, req models.AddFriendPayload) (}return nil, err}+ if created && c.EmailNotifier != nil {+ go c.EmailNotifier.OnSpaceFriendAdded(requesterSpace.SpaceSlug, session.OwnerID)+ }return &models.FriendStatusResponse{Status: "friend"}, nil}diff --git a/server/space/controller/messages.go b/server/space/controller/messages.goindex 58ef70864f..08a49a4f25 100644--- a/server/space/controller/messages.go+++ b/server/space/controller/messages.go@@ -29,6 +29,7 @@ type MessagesController struct {SpacesRepo *repo.SpacesRepositoryFriendsRepo *repo.FriendsRepositoryReadMarkersRepo *repo.ReadMarkersRepository+ EmailNotifier SpaceEmailNotifierauth authDeps}@@ -118,6 +119,9 @@ func (c *MessagesController) ReplyToPost(ctx *gin.Context, postID string, req moif err != nil {return nil, err}+ if c.EmailNotifier != nil {+ go c.EmailNotifier.OnSpacePostReplied(senderSpace.SpaceSlug, recipientSpace.OwnerID)+ }return toMessageResponse(*message), nil}diff --git a/server/space/controller/module.go b/server/space/controller/module.goindex 61d304a5ee..1f9d670624 100644--- a/server/space/controller/module.go+++ b/server/space/controller/module.go@@ -17,8 +17,8 @@ type Module struct {UserAuth *baserepo.UserAuthRepository}-func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository, emailNotifiers ...SpacePostEmailNotifier) *Module {- var emailNotifier SpacePostEmailNotifier+func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository, emailNotifiers ...SpaceEmailNotifier) *Module {+ var emailNotifier SpaceEmailNotifierif len(emailNotifiers) > 0 {emailNotifier = emailNotifiers[0]}@@ -31,8 +31,8 @@ func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository, emreturn &Module{Spaces: &SpacesController{SpacesRepo: repos.Spaces, AssetsRepo: repos.Assets, auth: authDeps},Posts: &PostsController{PostsRepo: repos.Posts, SpacesRepo: repos.Spaces, FriendsRepo: repos.Friends, AssetsRepo: repos.Assets, ReadMarkersRepo: repos.Read, EmailNotifier: emailNotifier, auth: authDeps},- Friends: &FriendsController{FriendsRepo: repos.Friends, SpacesRepo: repos.Spaces, auth: authDeps},- Messages: &MessagesController{MessagesRepo: repos.Messages, PostsRepo: repos.Posts, SpacesRepo: repos.Spaces, FriendsRepo: repos.Friends, ReadMarkersRepo: repos.Read, auth: authDeps},+ Friends: &FriendsController{FriendsRepo: repos.Friends, SpacesRepo: repos.Spaces, EmailNotifier: emailNotifier, auth: authDeps},+ Messages: &MessagesController{MessagesRepo: repos.Messages, PostsRepo: repos.Posts, SpacesRepo: repos.Spaces, FriendsRepo: repos.Friends, ReadMarkersRepo: repos.Read, EmailNotifier: emailNotifier, auth: authDeps},Links: &LinksController{LinksRepo: repos.Links, SpacesRepo: repos.Spaces, auth: authDeps},Assets: &AssetsController{AssetsRepo: repos.Assets, SpacesRepo: repos.Spaces, auth: authDeps},Read: &ReadMarkersController{ReadMarkersRepo: repos.Read, PostsRepo: repos.Posts, MessagesRepo: repos.Messages, auth: authDeps},diff --git a/server/space/controller/notifications.go b/server/space/controller/notifications.goindex 0e7dc452e2..c793f58670 100644--- a/server/space/controller/notifications.go+++ b/server/space/controller/notifications.go@@ -10,25 +10,44 @@ import ("github.com/spf13/viper")-const spacePostCreatedTemplate = "space_post_created.html"+const spaceNotificationTemplate = "space_notification.html"-var sendSpacePostCreatedEmail = emailutil.SendTemplatedEmail+var sendSpaceNotificationEmail = emailutil.SendTemplatedEmailV2-type SpacePostEmailNotifier interface {+type SpaceEmailNotifier interface {OnSpacePostCreated(authorSlug string, recipientUserIDs []int64)+ OnSpacePostLiked(actorSlug string, recipientUserID int64)+ OnSpacePostReplied(actorSlug string, recipientUserID int64)+ OnSpaceFriendAdded(actorSlug string, recipientUserID int64)}-type SpaceEmailNotifier struct {+type SpaceEmailSender struct {UserRepo *baserepo.UserRepository}-func (n *SpaceEmailNotifier) OnSpacePostCreated(authorSlug string, recipientUserIDs []int64) {+func (n *SpaceEmailSender) OnSpacePostCreated(authorSlug string, recipientUserIDs []int64) {+ n.send(authorSlug, "posted a new photo", "post_created", recipientUserIDs)+}++func (n *SpaceEmailSender) OnSpacePostLiked(actorSlug string, recipientUserID int64) {+ n.send(actorSlug, "liked your post", "post_liked", []int64{recipientUserID})+}++func (n *SpaceEmailSender) OnSpacePostReplied(actorSlug string, recipientUserID int64) {+ n.send(actorSlug, "replied to your post", "post_replied", []int64{recipientUserID})+}++func (n *SpaceEmailSender) OnSpaceFriendAdded(actorSlug string, recipientUserID int64) {+ n.send(actorSlug, "added you as a friend", "friend_added", []int64{recipientUserID})+}++func (n *SpaceEmailSender) send(actorSlug, action, event string, recipientUserIDs []int64) {if n == nil || n.UserRepo == nil || len(recipientUserIDs) == 0 {return}- authorSlug = strings.TrimSpace(authorSlug)- if authorSlug == "" {- authorSlug = "A friend"+ actorSlug = strings.TrimSpace(actorSlug)+ if actorSlug == "" {+ actorSlug = "A friend"}recipientUserIDs = uniqueUserIDs(recipientUserIDs)if len(recipientUserIDs) == 0 {@@ -36,33 +55,35 @@ func (n *SpaceEmailNotifier) OnSpacePostCreated(authorSlug string, recipientUser}users, err := n.UserRepo.GetActiveUsersForIds(recipientUserIDs)if err != nil {- log.WithError(err).Error("Error fetching users for space post email")+ log.WithField("event", event).WithError(err).Error("Error fetching users for space email")return}- subject := fmt.Sprintf("%s has shared a new post", authorSlug)+ subject := fmt.Sprintf("%s %s", actorSlug, action)templateData := map[string]interface{}{- "Author": authorSlug,- "AppURL": spaceAppURL(),+ "Message": subject,+ "AppURL": spaceAppURL(),}for _, userID := range recipientUserIDs {user := users[userID]if user == nil || strings.TrimSpace(user.Email) == "" {continue}- if err := sendSpacePostCreatedEmail(+ if err := sendSpaceNotificationEmail([]string{user.Email},"Ente",subject,- spacePostCreatedTemplate,+ "base.html",+ spaceNotificationTemplate,templateData,nil,); err != nil {log.WithFields(log.Fields{"user_id": userID,"email": user.Email,- }).WithError(err).Error("Error sending space post email")+ "event": event,+ }).WithError(err).Error("Error sending space email")}}}diff --git a/server/space/controller/notifications_test.go b/server/space/controller/notifications_test.gonew file mode 100644index 0000000000..8d5ad3b998--- /dev/null+++ b/server/space/controller/notifications_test.go@@ -0,0 +1,148 @@+package controller++import (+ "crypto/sha256"+ "encoding/base64"+ "strconv"+ "testing"+ "time"++ timeutil "github.com/ente-io/museum/pkg/utils/time"+ "github.com/ente-io/museum/space/models"+ "github.com/stretchr/testify/require"+)++type recordedSpaceEmail struct {+ event string+ actorSlug string+ recipients []int64+}++type recordingSpaceEmailNotifier struct {+ events chan recordedSpaceEmail+}++func newRecordingSpaceEmailNotifier() *recordingSpaceEmailNotifier {+ return &recordingSpaceEmailNotifier{events: make(chan recordedSpaceEmail, 8)}+}++func (n *recordingSpaceEmailNotifier) OnSpacePostCreated(actorSlug string, recipientUserIDs []int64) {+ n.events <- recordedSpaceEmail{event: "post_created", actorSlug: actorSlug, recipients: append([]int64(nil), recipientUserIDs...)}+}++func (n *recordingSpaceEmailNotifier) OnSpacePostLiked(actorSlug string, recipientUserID int64) {+ n.events <- recordedSpaceEmail{event: "post_liked", actorSlug: actorSlug, recipients: []int64{recipientUserID}}+}++func (n *recordingSpaceEmailNotifier) OnSpacePostReplied(actorSlug string, recipientUserID int64) {+ n.events <- recordedSpaceEmail{event: "post_replied", actorSlug: actorSlug, recipients: []int64{recipientUserID}}+}++func (n *recordingSpaceEmailNotifier) OnSpaceFriendAdded(actorSlug string, recipientUserID int64) {+ n.events <- recordedSpaceEmail{event: "friend_added", actorSlug: actorSlug, recipients: []int64{recipientUserID}}+}++func requireSpaceEmail(t *testing.T, notifier *recordingSpaceEmailNotifier) recordedSpaceEmail {+ t.Helper()+ select {+ case event := <-notifier.events:+ return event+ case <-time.After(time.Second):+ t.Fatal("timed out waiting for space email")+ return recordedSpaceEmail{}+ }+}++func requireNoSpaceEmail(t *testing.T, notifier *recordingSpaceEmailNotifier) {+ t.Helper()+ select {+ case event := <-notifier.events:+ t.Fatalf("unexpected space email: %+v", event)+ case <-time.After(100 * time.Millisecond):+ }+}++func TestPostLikeSendsEmailOnce(t *testing.T) {+ _, repos, ctx := setupPostsControllerTest(t)+ notifier := newRecordingSpaceEmailNotifier()+ posts := NewModule(repos, nil, notifier).Posts+ aliceID := insertSpaceControllerUser(t, repos, "[email protected]", "alice-public")+ bobID := insertSpaceControllerUser(t, repos, "[email protected]", "bob-public")+ aliceSpace, err := repos.Spaces.CreateSpace(ctx, aliceID, "alice-post-like-email", "alice-space-key", "alice-profile")+ require.NoError(t, err)+ bobSpace, err := repos.Spaces.CreateSpace(ctx, bobID, "bob-post-like-email", "bob-space-key", "bob-profile")+ require.NoError(t, err)+ require.NoError(t, repos.Friends.AddFriend(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID, "alice-share-key", aliceSpace.CurrentVersion, "bob-share-key", bobSpace.CurrentVersion))+ postID, err := repos.Posts.CreatePost(ctx, aliceID, aliceSpace.SpaceID, "post-key", nil, aliceSpace.CurrentVersion, nil)+ require.NoError(t, err)++ resp, err := posts.ToggleLike(newSpaceControllerContext(bobID), base10(postID), models.LikePostRequest{Like: true})+ require.NoError(t, err)+ require.True(t, resp.Liked)+ email := requireSpaceEmail(t, notifier)+ require.Equal(t, recordedSpaceEmail{event: "post_liked", actorSlug: bobSpace.SpaceSlug, recipients: []int64{aliceID}}, email)++ _, err = posts.ToggleLike(newSpaceControllerContext(bobID), base10(postID), models.LikePostRequest{Like: true})+ require.NoError(t, err)+ requireNoSpaceEmail(t, notifier)+}++func TestPostReplySendsEmail(t *testing.T) {+ _, repos, ctx := setupMessagesControllerTest(t)+ notifier := newRecordingSpaceEmailNotifier()+ messages := NewModule(repos, nil, notifier).Messages+ aliceID, aliceSpace := createMessageControllerUserAndSpace(t, repos, "alice-post-reply-email", "alice-public")+ bobID, bobSpace := createMessageControllerUserAndSpace(t, repos, "bob-post-reply-email", "bob-public")+ require.NoError(t, repos.Friends.AddFriend(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID, "alice-share-key", aliceSpace.CurrentVersion, "bob-share-key", bobSpace.CurrentVersion))+ postID, err := repos.Posts.CreatePost(ctx, aliceID, aliceSpace.SpaceID, "post-key", nil, aliceSpace.CurrentVersion, nil)+ require.NoError(t, err)++ _, err = messages.ReplyToPost(newSpaceControllerContext(bobID), base10(postID), models.CreateMessageRequest{+ MessageCipher: spaceTestB64("reply-cipher"),+ SenderEncryptedMessageKey: spaceTestB64("reply-sender-key"),+ RecipientEncryptedMessageKey: spaceTestB64("reply-recipient-key"),+ })+ require.NoError(t, err)+ email := requireSpaceEmail(t, notifier)+ require.Equal(t, recordedSpaceEmail{event: "post_replied", actorSlug: bobSpace.SpaceSlug, recipients: []int64{aliceID}}, email)+}++func TestAddFriendSendsEmailOnce(t *testing.T) {+ _, repos, ctx := setupFriendsControllerTest(t)+ notifier := newRecordingSpaceEmailNotifier()+ friends := NewModule(repos, nil, notifier).Friends+ aliceID := insertSpaceControllerUser(t, repos, "[email protected]", "alice-public")+ bobID := insertSpaceControllerUser(t, repos, "[email protected]", "bob-public")+ aliceSpace, err := repos.Spaces.CreateSpace(ctx, aliceID, "alice-friend-email", "alice-space-key", "alice-profile")+ require.NoError(t, err)+ bobSpace, err := repos.Spaces.CreateSpace(ctx, bobID, "bob-friend-email", "bob-space-key", "bob-profile")+ require.NoError(t, err)+ authHash := sha256.Sum256([]byte("alice-friend-email-auth-key"))+ link, err := repos.Links.UpsertLink(ctx, aliceSpace.SpaceID, authHash[:], aliceSpace.CurrentVersion, "alice-link-key", "alice-link-secret")+ require.NoError(t, err)+ sessionHash := sha256.Sum256([]byte("alice-friend-email-session-token"))+ require.NoError(t, repos.Links.CreateSession(ctx, sessionHash[:], link.SpaceID, link.AuthKeyHash, link.KeyVersion, timeutil.MicrosecondsAfterMinutes(5)))+ req := models.AddFriendPayload{+ TargetSpaceID: aliceSpace.SpaceID,+ LinkSessionToken: "alice-friend-email-session-token",+ RequesterSpaceID: bobSpace.SpaceID,+ TargetEncryptedSpaceKey: base64.StdEncoding.EncodeToString([]byte("alice-target-key")),+ TargetKeyVersion: aliceSpace.CurrentVersion,+ RequesterEncryptedSpaceKey: base64.StdEncoding.EncodeToString([]byte("bob-requester-key")),+ RequesterKeyVersion: bobSpace.CurrentVersion,+ }++ resp, err := friends.Add(newSpaceControllerContext(bobID), req)+ require.NoError(t, err)+ require.Equal(t, "friend", resp.Status)+ email := requireSpaceEmail(t, notifier)+ require.Equal(t, recordedSpaceEmail{event: "friend_added", actorSlug: bobSpace.SpaceSlug, recipients: []int64{aliceID}}, email)++ _, err = friends.Add(newSpaceControllerContext(bobID), req)+ require.NoError(t, err)+ requireNoSpaceEmail(t, notifier)+}++func base10(id int64) string {+ return strconv.FormatInt(id, 10)+}diff --git a/server/space/controller/posts.go b/server/space/controller/posts.goindex cc9f3ace56..8a561b7550 100644--- a/server/space/controller/posts.go+++ b/server/space/controller/posts.go@@ -21,7 +21,7 @@ type PostsController struct {FriendsRepo *repo.FriendsRepositoryAssetsRepo *repo.AssetsRepositoryReadMarkersRepo *repo.ReadMarkersRepository- EmailNotifier SpacePostEmailNotifier+ EmailNotifier SpaceEmailNotifierauth authDeps}@@ -285,9 +285,13 @@ func (c *PostsController) ToggleLike(ctx *gin.Context, postID string, req modelsif err := c.auth.canViewSpace(ctx.Request.Context(), &viewerAuth{UserID: userID, SpaceID: actorSpace.SpaceID}, space); err != nil {return nil, err}- if err := c.PostsRepo.SetLike(ctx.Request.Context(), id, userID, actorSpace.SpaceID, req.Like); err != nil {+ created, err := c.PostsRepo.SetLikeWithCreated(ctx.Request.Context(), id, userID, actorSpace.SpaceID, req.Like)+ if err != nil {return nil, err}+ if req.Like && created && c.EmailNotifier != nil {+ go c.EmailNotifier.OnSpacePostLiked(actorSpace.SpaceSlug, post.OwnerID)+ }return &models.LikePostResponse{Liked: req.Like}, nil}diff --git a/server/space/repo/friends.go b/server/space/repo/friends.goindex 475614eb54..c8b1c5f160 100644--- a/server/space/repo/friends.go+++ b/server/space/repo/friends.go@@ -16,9 +16,14 @@ var ()func (r *FriendsRepository) AddFriend(ctx context.Context, requesterID int64, requesterSpaceID string, targetSpaceID string, targetEncryptedSpaceKey string, targetKeyVersion int, requesterEncryptedSpaceKey string, requesterKeyVersion int) error {+ _, err := r.AddFriendWithCreated(ctx, requesterID, requesterSpaceID, targetSpaceID, targetEncryptedSpaceKey, targetKeyVersion, requesterEncryptedSpaceKey, requesterKeyVersion)+ return err+}++func (r *FriendsRepository) AddFriendWithCreated(ctx context.Context, requesterID int64, requesterSpaceID string, targetSpaceID string, targetEncryptedSpaceKey string, targetKeyVersion int, requesterEncryptedSpaceKey string, requesterKeyVersion int) (bool, error) {tx, err := r.DB.BeginTx(ctx, nil)if err != nil {- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}defer tx.Rollback()@@ -30,10 +35,10 @@ func (r *FriendsRepository) AddFriend(ctx context.Context, requesterID int64, reWHERE space_id = $1FOR UPDATE`, requesterSpaceID).Scan(&requesterOwnerID, &requesterCurrentVersion); err != nil {- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}if requesterOwnerID != requesterID || requesterCurrentVersion != requesterKeyVersion {- return sql.ErrNoRows+ return false, sql.ErrNoRows}var targetOwnerID int64@@ -44,13 +49,13 @@ func (r *FriendsRepository) AddFriend(ctx context.Context, requesterID int64, reWHERE space_id = $1FOR UPDATE`, targetSpaceID).Scan(&targetOwnerID, &targetCurrentVersion); err != nil {- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}if targetOwnerID == requesterID {- return ErrSelfFriendship+ return false, ErrSelfFriendship}if targetCurrentVersion != targetKeyVersion {- return sql.ErrNoRows+ return false, sql.ErrNoRows}var alreadyFriends bool@@ -67,7 +72,7 @@ func (r *FriendsRepository) AddFriend(ctx context.Context, requesterID int64, reAND target_share.friend_space_id = $1)`, requesterSpaceID, targetOwnerID, targetSpaceID, requesterID).Scan(&alreadyFriends); err != nil {- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}if _, err := tx.ExecContext(ctx, `@@ -77,7 +82,7 @@ func (r *FriendsRepository) AddFriend(ctx context.Context, requesterID int64, reSET encrypted_space_key = EXCLUDED.encrypted_space_key,key_version = EXCLUDED.key_version`, targetSpaceID, requesterID, requesterSpaceID, targetEncryptedSpaceKey, targetKeyVersion); err != nil {- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}if _, err := tx.ExecContext(ctx, `@@ -87,7 +92,7 @@ func (r *FriendsRepository) AddFriend(ctx context.Context, requesterID int64, reSET encrypted_space_key = EXCLUDED.encrypted_space_key,key_version = EXCLUDED.key_version`, requesterSpaceID, targetOwnerID, targetSpaceID, requesterEncryptedSpaceKey, requesterKeyVersion); err != nil {- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}if !alreadyFriends {@@ -95,11 +100,14 @@ func (r *FriendsRepository) AddFriend(ctx context.Context, requesterID int64, reINSERT INTO space_friend_events (event_type, actor_id, actor_space_id, target_id, target_space_id)VALUES ('friend_add', $1, $2, $3, $4)`, requesterID, requesterSpaceID, targetOwnerID, targetSpaceID); err != nil {- return stacktrace.Propagate(err, "")+ return false, stacktrace.Propagate(err, "")}}- return stacktrace.Propagate(tx.Commit(), "")+ if err := tx.Commit(); err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ return !alreadyFriends, nil}func (r *FriendsRepository) UpsertShare(ctx context.Context, spaceID string, friendID int64, friendSpaceID string, encryptedSpaceKey string, keyVersion int) error {diff --git a/server/space/repo/posts.go b/server/space/repo/posts.goindex a1c0e0a94f..6bdf3a4972 100644--- a/server/space/repo/posts.go+++ b/server/space/repo/posts.go@@ -326,12 +326,31 @@ func (r *PostsRepository) DeletePost(ctx context.Context, postID, ownerID int64)}func (r *PostsRepository) SetLike(ctx context.Context, postID, userID int64, actorSpaceID string, like bool) error {+ _, err := r.SetLikeWithCreated(ctx, postID, userID, actorSpaceID, like)+ return err+}++func (r *PostsRepository) SetLikeWithCreated(ctx context.Context, postID, userID int64, actorSpaceID string, like bool) (bool, error) {if like {- _, err := r.DB.ExecContext(ctx, `INSERT INTO space_post_likes (post_id, user_id, actor_space_id) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, postID, userID, actorSpaceID)- return stacktrace.Propagate(err, "")+ res, err := r.DB.ExecContext(ctx, `INSERT INTO space_post_likes (post_id, user_id, actor_space_id) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, postID, userID, actorSpaceID)+ if err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ affected, err := res.RowsAffected()+ if err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ 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)+ if err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ affected, err := res.RowsAffected()+ if err != nil {+ return false, stacktrace.Propagate(err, "")}- _, err := r.DB.ExecContext(ctx, `DELETE FROM space_post_likes WHERE post_id = $1 AND actor_space_id = $2`, postID, actorSpaceID)- return stacktrace.Propagate(err, "")+ return affected > 0, nil}func (r *PostsRepository) ListPostLikers(ctx context.Context, postID int64, cursor string, limit int) ([]SpacePostLikerRecord, string, error) {