Skip to content

armgit / ente

Public Imported from GitHub
0

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

Comments/Reactions API

Neeraj Gupta5124747606b6
diff --git a/server/.gitignore b/server/.gitignore
index bbf74052f4..ef780eef5f 100644
--- a/server/.gitignore
+++ b/server/.gitignore
@@ -13,4 +13,5 @@ __debug_bin*
config/.env
config/museum.yaml
main
+museum
credentials
\ No newline at end of file
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index 69fce1af2c..edbc53add0 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -48,6 +48,7 @@ import (
"github.com/ente-io/museum/pkg/controller/family"
"github.com/ente-io/museum/pkg/controller/lock"
remoteStoreCtrl "github.com/ente-io/museum/pkg/controller/remotestore"
+ socialcontroller "github.com/ente-io/museum/pkg/controller/social"
"github.com/ente-io/museum/pkg/controller/storagebonus"
"github.com/ente-io/museum/pkg/controller/user"
userEntityCtrl "github.com/ente-io/museum/pkg/controller/userentity"
@@ -61,6 +62,7 @@ import (
fileDataRepo "github.com/ente-io/museum/pkg/repo/filedata"
"github.com/ente-io/museum/pkg/repo/passkey"
"github.com/ente-io/museum/pkg/repo/remotestore"
+ socialrepo "github.com/ente-io/museum/pkg/repo/social"
storageBonusRepo "github.com/ente-io/museum/pkg/repo/storagebonus"
userEntityRepo "github.com/ente-io/museum/pkg/repo/userentity"
"github.com/ente-io/museum/pkg/utils/billing"
@@ -263,6 +265,25 @@ func main() {
}
accessCtrl := access.NewAccessController(collectionRepo, fileRepo)
+ commentsRepo := &socialrepo.CommentsRepository{DB: db}
+ reactionsRepo := &socialrepo.ReactionsRepository{DB: db}
+ anonUsersRepo := &socialrepo.AnonUsersRepository{DB: db}
+ commentsController := &socialcontroller.CommentsController{
+ Repo: commentsRepo,
+ AccessCtrl: accessCtrl,
+ }
+ reactionsController := &socialcontroller.ReactionsController{
+ Repo: reactionsRepo,
+ CommentsRepo: commentsRepo,
+ AccessCtrl: accessCtrl,
+ }
+ socialController := &socialcontroller.Controller{
+ CommentsRepo: commentsRepo,
+ ReactionsRepo: reactionsRepo,
+ CollectionRepo: collectionRepo,
+ AccessCtrl: accessCtrl,
+ AnonUsersRepo: anonUsersRepo,
+ }
fileDataCtrl := filedata.New(fileDataRepo, accessCtrl, objectCleanupController, s3Config, fileRepo, collectionRepo)
fileController := &controller.FileController{
@@ -317,6 +338,26 @@ func main() {
UserRepo: userRepo,
JwtSecret: jwtSecretBytes,
}
+ publicCommentsCtrl := &publicCtrl.CommentsController{
+ CommentCtrl: commentsController,
+ CommentsRepo: commentsRepo,
+ ReactionsRepo: reactionsRepo,
+ UserRepo: userRepo,
+ UserAuthRepo: userAuthRepo,
+ AnonUsersRepo: anonUsersRepo,
+ JwtSecret: jwtSecretBytes,
+ }
+ publicReactionsCtrl := &publicCtrl.ReactionsController{
+ ReactionCtrl: reactionsController,
+ ReactionsRepo: reactionsRepo,
+ AnonUsersRepo: anonUsersRepo,
+ UserAuthRepo: userAuthRepo,
+ JwtSecret: jwtSecretBytes,
+ }
+ anonIdentityCtrl := &publicCtrl.AnonIdentityController{
+ JwtSecret: jwtSecretBytes,
+ AnonUsersRepo: anonUsersRepo,
+ }
collectionController := &collections.CollectionController{
CollectionRepo: collectionRepo,
@@ -330,6 +371,8 @@ func main() {
QueueRepo: queueRepo,
TaskRepo: taskLockingRepo,
CollectionActionsRepo: collectionActionRepo,
+ CommentsRepo: commentsRepo,
+ ReactionsRepo: reactionsRepo,
}
// Pending actions' controller/handler
@@ -383,10 +426,12 @@ func main() {
CollectionLinkRepo: collectionLinkRepo,
PublicCollectionCtrl: collectionLinkCtrl,
CollectionRepo: collectionRepo,
+ AnonUsersRepo: anonUsersRepo,
Cache: accessTokenCache,
BillingCtrl: billingController,
DiscordController: discordController,
RemoteStoreRepo: remoteStoreRepository,
+ AnonIdentitySecret: jwtSecretBytes,
}
fileLinkMiddleware := &middleware.FileLinkMiddleware{
FileLinkRepo: fileLinkRepo,
@@ -438,7 +483,11 @@ func main() {
familiesJwtAuthAPI.Use(rateLimiter.GlobalRateLimiter(), authMiddleware.TokenAuthMiddleware(jwt.FAMILIES.Ptr()), rateLimiter.APIRateLimitForUserMiddleware(urlSanitizer))
publicCollectionAPI := server.Group("/public-collection")
- publicCollectionAPI.Use(rateLimiter.GlobalRateLimiter(), collectionLinkMiddleware.Authenticate(urlSanitizer))
+ publicCollectionAPI.Use(
+ rateLimiter.GlobalRateLimiter(),
+ collectionLinkMiddleware.Authenticate(urlSanitizer),
+ rateLimiter.APIRateLimitMiddleware(urlSanitizer),
+ )
fileLinkApi := server.Group("/file-link")
fileLinkApi.Use(rateLimiter.GlobalRateLimiter(), fileLinkMiddleware.Authenticate(urlSanitizer))
@@ -513,6 +562,27 @@ func main() {
privateAPI.GET("/trash/v2/diff", trashHandler.GetDiffV2)
privateAPI.POST("/trash/delete", trashHandler.Delete)
privateAPI.POST("/trash/empty", trashHandler.Empty)
+ commentsHandler := &api.CommentsHandler{Controller: commentsController}
+ reactionsHandler := &api.ReactionsHandler{Controller: reactionsController}
+ socialHandler := &api.SocialHandler{Controller: socialController}
+ publicSocialHandler := &api.PublicCommentsHandler{
+ CommentsCtrl: publicCommentsCtrl,
+ ReactionsCtrl: publicReactionsCtrl,
+ AnonIdentityCtrl: anonIdentityCtrl,
+ }
+ privateAPI.GET("/comments/diff", commentsHandler.Diff)
+ privateAPI.POST("/comments", commentsHandler.Create)
+ privateAPI.PUT("/comments/:commentID", commentsHandler.Update)
+ privateAPI.DELETE("/comments/:commentID", commentsHandler.Delete)
+
+ privateAPI.GET("/reactions/diff", reactionsHandler.Diff)
+ privateAPI.PUT("/reactions", reactionsHandler.Upsert)
+ privateAPI.DELETE("/reactions/:reactionID", reactionsHandler.Delete)
+
+ privateAPI.GET("/social/diff", socialHandler.UnifiedDiff)
+ privateAPI.GET("/social/anon-profiles", socialHandler.AnonProfiles)
+ privateAPI.GET("/comments-reactions/counts", socialHandler.Counts)
+ privateAPI.GET("/comments-reactions/updated-at", socialHandler.LatestUpdates)
emergencyCtrl := &emergency.Controller{
Repo: &emergencyRepo.Repository{DB: db},
@@ -617,7 +687,6 @@ func main() {
FileDataCtrl: fileDataCtrl,
StorageBonusController: storageBonusCtrl,
}
-
fileLinkApi.GET("/info", fileHandler.LinkInfo)
fileLinkApi.GET("/pass-info", fileHandler.PasswordInfo)
fileLinkApi.GET("/thumbnail", fileHandler.LinkThumbnail)
@@ -634,6 +703,17 @@ func main() {
publicCollectionAPI.GET("/multipart-upload-urls", publicCollectionHandler.GetMultipartUploadURLs)
publicCollectionAPI.POST("/file", publicCollectionHandler.CreateFile)
publicCollectionAPI.POST("/verify-password", publicCollectionHandler.VerifyPassword)
+ publicCollectionAPI.GET("/social/diff", publicSocialHandler.SocialDiff)
+ publicCollectionAPI.GET("/comments/diff", publicSocialHandler.CommentDiff)
+ publicCollectionAPI.POST("/comments", publicSocialHandler.CreateComment)
+ publicCollectionAPI.PUT("/comments/:commentID", publicSocialHandler.UpdateComment)
+ publicCollectionAPI.DELETE("/comments/:commentID", publicSocialHandler.DeleteComment)
+ publicCollectionAPI.GET("/reactions/diff", publicSocialHandler.ReactionDiff)
+ publicCollectionAPI.POST("/reactions", publicSocialHandler.CreateReaction)
+ publicCollectionAPI.DELETE("/reactions/:reactionID", publicSocialHandler.DeleteReaction)
+ publicCollectionAPI.GET("/participants/masked-emails", publicSocialHandler.Participants)
+ publicCollectionAPI.GET("/anon-profiles", publicSocialHandler.AnonProfiles)
+ publicCollectionAPI.POST("/anon-identity", publicSocialHandler.CreateAnonIdentity)
castAPI := server.Group("/cast")
diff --git a/server/ente/anonymous_identity.go b/server/ente/anonymous_identity.go
new file mode 100644
index 0000000000..d664cac5ab
--- /dev/null
+++ b/server/ente/anonymous_identity.go
@@ -0,0 +1,62 @@
+package ente
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/golang-jwt/jwt/v4"
+)
+
+const anonIdentityTokenType = "anon-identity"
+
+// AnonymousIdentityClaim represents the JWT issued for anonymous commenters.
+type AnonymousIdentityClaim struct {
+ Typ string `json:"typ"`
+ jwt.RegisteredClaims
+}
+
+// NewAnonymousIdentityToken signs a token for the provided anonUserID.
+func NewAnonymousIdentityToken(secret []byte, anonUserID string) (string, int64, error) {
+ issuedAt := time.Now()
+ expiry := issuedAt.AddDate(1, 0, 0) // 1 year validity
+ claim := AnonymousIdentityClaim{
+ Typ: anonIdentityTokenType,
+ RegisteredClaims: jwt.RegisteredClaims{
+ Subject: anonUserID,
+ Issuer: "museum",
+ IssuedAt: jwt.NewNumericDate(issuedAt),
+ ExpiresAt: jwt.NewNumericDate(expiry),
+ },
+ }
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
+ tokenString, err := token.SignedString(secret)
+ if err != nil {
+ return "", 0, err
+ }
+ return tokenString, MicrosecondsFromTime(expiry), nil
+}
+
+// ParseAnonymousIdentityToken validates the token and returns the parsed claim.
+func ParseAnonymousIdentityToken(secret []byte, tokenString string) (*AnonymousIdentityClaim, error) {
+ token, err := jwt.ParseWithClaims(tokenString, &AnonymousIdentityClaim{}, func(t *jwt.Token) (interface{}, error) {
+ if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
+ return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
+ }
+ return secret, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ claim, ok := token.Claims.(*AnonymousIdentityClaim)
+ if !ok || !token.Valid || claim.Typ != anonIdentityTokenType {
+ return nil, fmt.Errorf("invalid anonymous identity token")
+ }
+ if claim.Subject == "" {
+ return nil, fmt.Errorf("missing subject in anonymous identity token")
+ }
+ return claim, nil
+}
+
+func MicrosecondsFromTime(t time.Time) int64 {
+ return t.UnixNano() / 1000
+}
diff --git a/server/ente/social/anon_user.go b/server/ente/social/anon_user.go
new file mode 100644
index 0000000000..f34892e4c8
--- /dev/null
+++ b/server/ente/social/anon_user.go
@@ -0,0 +1,11 @@
+package social
+
+// AnonUser captures encrypted profile metadata for anonymous public commenters.
+type AnonUser struct {
+ ID string `json:"anonUserID"`
+ CollectionID int64 `json:"collectionID"`
+ Cipher string `json:"cipher"`
+ Nonce string `json:"nonce"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+}
diff --git a/server/ente/social/comment.go b/server/ente/social/comment.go
new file mode 100644
index 0000000000..88393b07aa
--- /dev/null
+++ b/server/ente/social/comment.go
@@ -0,0 +1,17 @@
+package social
+
+// Comment represents an encrypted comment or reply stored in the database.
+type Comment struct {
+ ID string `json:"id"`
+ CollectionID int64 `json:"collectionID"`
+ FileID *int64 `json:"fileID,omitempty"`
+ ParentCommentID *string `json:"parentCommentID,omitempty"`
+ ParentCommentUserID *int64 `json:"parentCommentUserID,omitempty"`
+ UserID int64 `json:"userID"`
+ AnonUserID *string `json:"anonUserID,omitempty"`
+ Cipher string `json:"cipher,omitempty"`
+ Nonce string `json:"nonce,omitempty"`
+ IsDeleted bool `json:"isDeleted"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+}
diff --git a/server/ente/social/reaction.go b/server/ente/social/reaction.go
new file mode 100644
index 0000000000..7e24628e3e
--- /dev/null
+++ b/server/ente/social/reaction.go
@@ -0,0 +1,17 @@
+package social
+
+// Reaction represents an encrypted reaction scoped to a collection, file, or comment.
+type Reaction struct {
+ ID string `json:"id"`
+ CollectionID int64 `json:"collectionID"`
+ FileID *int64 `json:"fileID,omitempty"`
+ CommentID *string `json:"commentID,omitempty"`
+ IsCommentReply *bool `json:"isCommentReply,omitempty"`
+ UserID int64 `json:"userID"`
+ AnonUserID *string `json:"anonUserID,omitempty"`
+ Cipher string `json:"cipher,omitempty"`
+ Nonce string `json:"nonce,omitempty"`
+ IsDeleted bool `json:"isDeleted"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+}
diff --git a/server/migrations/114_comments_reactions.down.sql b/server/migrations/114_comments_reactions.down.sql
new file mode 100644
index 0000000000..53d59890e5
--- /dev/null
+++ b/server/migrations/114_comments_reactions.down.sql
@@ -0,0 +1,39 @@
+-- Drop comments/reactions schema introduced in 114_comments_reactions.up.sql
+
+-- Drop triggers first
+DROP TRIGGER IF EXISTS check_reaction_target ON reactions;
+DROP TRIGGER IF EXISTS update_reactions_updated_at ON reactions;
+DROP TRIGGER IF EXISTS reactions_null_cipher_on_delete ON reactions;
+
+DROP TRIGGER IF EXISTS soft_delete_reactions_on_comment_delete ON comments;
+DROP TRIGGER IF EXISTS check_reply_scope ON comments;
+DROP TRIGGER IF EXISTS update_comments_updated_at ON comments;
+DROP TRIGGER IF EXISTS comments_null_cipher_on_delete ON comments;
+
+-- Drop indexes (will be dropped with table if cascade, but include for clarity)
+DROP INDEX IF EXISTS idx_reactions_user;
+DROP INDEX IF EXISTS idx_reactions_anon;
+DROP INDEX IF EXISTS idx_reactions_comment;
+DROP INDEX IF EXISTS idx_reactions_collection_updated_at;
+DROP INDEX IF EXISTS idx_reactions_scope;
+
+DROP INDEX IF EXISTS idx_comments_collection_updated_at;
+DROP INDEX IF EXISTS idx_comments_user;
+DROP INDEX IF EXISTS idx_comments_parent;
+DROP INDEX IF EXISTS idx_comments_scope;
+DROP INDEX IF EXISTS idx_comments_anon;
+
+DROP INDEX IF EXISTS idx_anon_users_collection;
+
+-- Drop tables
+DROP TRIGGER IF EXISTS update_anon_users_updated_at ON anon_users;
+
+DROP TABLE IF EXISTS reactions;
+DROP TABLE IF EXISTS comments;
+DROP TABLE IF EXISTS anon_users;
+
+-- Drop helper functions (safe if unused elsewhere)
+DROP FUNCTION IF EXISTS tg_soft_delete_reactions_on_comment_delete();
+DROP FUNCTION IF EXISTS tg_check_reaction_target();
+DROP FUNCTION IF EXISTS tg_check_reply_scope();
+DROP FUNCTION IF EXISTS tg_null_cipher_on_delete();
diff --git a/server/migrations/114_comments_reactions.up.sql b/server/migrations/114_comments_reactions.up.sql
new file mode 100644
index 0000000000..9c79f86205
--- /dev/null
+++ b/server/migrations/114_comments_reactions.up.sql
@@ -0,0 +1,240 @@
+-- Create comments and reactions tables with E2EE payloads, tombstones, and delta-sync indexes
+-- Uses BIGINT microsecond timestamps via now_utc_micro_seconds()
+
+-- App supplies nanoid strings for primary keys; no pgcrypto dependency.
+
+-- Helper: null cipher when tombstoned
+CREATE OR REPLACE FUNCTION tg_null_cipher_on_delete() RETURNS trigger AS $$
+BEGIN
+ IF NEW.is_deleted THEN
+ NEW.cipher := NULL;
+ NEW.nonce := NULL;
+ END IF;
+ RETURN NEW;
+END; $$ LANGUAGE plpgsql;
+
+-- Enforce replies stay within parent scope
+CREATE OR REPLACE FUNCTION tg_check_reply_scope() RETURNS trigger AS $$
+BEGIN
+ IF NEW.parent_comment_id IS NULL THEN
+ RETURN NEW;
+ END IF;
+ PERFORM 1 FROM comments p
+ WHERE p.id = NEW.parent_comment_id
+ AND p.collection_id = NEW.collection_id
+ AND (p.file_id IS NOT DISTINCT FROM NEW.file_id);
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Reply must match parent scope';
+ END IF;
+ RETURN NEW;
+END; $$ LANGUAGE plpgsql;
+
+-- Enforce reaction target integrity (if comment reaction, collection must match)
+CREATE OR REPLACE FUNCTION tg_check_reaction_target() RETURNS trigger AS $$
+DECLARE
+ c_rec RECORD;
+BEGIN
+ IF NEW.comment_id IS NULL THEN
+ RETURN NEW;
+ END IF;
+ SELECT id, collection_id INTO c_rec FROM comments WHERE id = NEW.comment_id;
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Reaction must reference an existing comment';
+ END IF;
+ IF c_rec.collection_id <> NEW.collection_id THEN
+ RAISE EXCEPTION 'Reaction collection_id must match comment collection_id';
+ END IF;
+ RETURN NEW;
+END; $$ LANGUAGE plpgsql;
+
+-- Anonymous users table storing encrypted profile metadata for public commenters
+CREATE TABLE IF NOT EXISTS anon_users (
+ id TEXT PRIMARY KEY,
+ collection_id BIGINT NOT NULL,
+ cipher TEXT NOT NULL,
+ nonce TEXT NOT NULL,
+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds()
+);
+
+CREATE INDEX IF NOT EXISTS idx_anon_users_collection
+ ON anon_users (collection_id);
+
+CREATE TRIGGER update_anon_users_updated_at
+ BEFORE UPDATE ON anon_users
+ FOR EACH ROW EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
+
+-- Soft-delete all reactions for a comment when the comment is tombstoned
+CREATE OR REPLACE FUNCTION tg_soft_delete_reactions_on_comment_delete() RETURNS trigger AS $$
+BEGIN
+ IF NEW.is_deleted AND (OLD.is_deleted IS DISTINCT FROM NEW.is_deleted) THEN
+ UPDATE reactions
+ SET is_deleted = TRUE,
+ cipher = NULL,
+ nonce = NULL,
+ updated_at = now_utc_micro_seconds()
+ WHERE comment_id = NEW.id
+ AND is_deleted = FALSE;
+ END IF;
+ RETURN NEW;
+END; $$ LANGUAGE plpgsql;
+
+-- Comments table
+CREATE TABLE IF NOT EXISTS comments (
+ id TEXT PRIMARY KEY,
+
+ collection_id BIGINT NOT NULL,
+ file_id BIGINT NULL, -- null => collection-level comment
+
+ parent_comment_id TEXT NULL, -- reply-to (same collection_id/file_id)
+ user_id BIGINT NOT NULL,
+ anon_user_id TEXT NULL,
+
+ cipher TEXT,
+ nonce TEXT,
+
+ 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 comments_cipher_on_delete CHECK (
+ (is_deleted = FALSE AND cipher IS NOT NULL AND nonce IS NOT NULL) OR
+ (is_deleted = TRUE AND cipher IS NULL AND nonce IS NULL)
+ ),
+ CONSTRAINT comments_user_or_anon_chk CHECK (
+ (user_id = -1 AND anon_user_id IS NOT NULL) OR
+ (user_id > 0 AND anon_user_id IS NULL)
+ ),
+ CONSTRAINT fk_comments_anon_user FOREIGN KEY (anon_user_id) REFERENCES anon_users (id)
+);
+
+-- Indexes for comments
+CREATE INDEX IF NOT EXISTS idx_comments_scope
+ ON comments (collection_id, file_id)
+ WHERE is_deleted = FALSE;
+
+CREATE INDEX IF NOT EXISTS idx_comments_parent
+ ON comments (parent_comment_id)
+ WHERE is_deleted = FALSE;
+
+CREATE INDEX IF NOT EXISTS idx_comments_user
+ ON comments (user_id)
+ WHERE is_deleted = FALSE;
+
+CREATE INDEX IF NOT EXISTS idx_comments_anon
+ ON comments (anon_user_id)
+ WHERE is_deleted = FALSE;
+
+-- Delta sync by collection and updated_at
+CREATE INDEX IF NOT EXISTS idx_comments_collection_updated_at
+ ON comments (collection_id, updated_at);
+
+-- Triggers for comments
+CREATE TRIGGER comments_null_cipher_on_delete
+ BEFORE INSERT OR UPDATE ON comments
+ FOR EACH ROW EXECUTE PROCEDURE tg_null_cipher_on_delete();
+
+CREATE TRIGGER update_comments_updated_at
+ BEFORE UPDATE ON comments
+ FOR EACH ROW EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
+
+CREATE TRIGGER check_reply_scope
+ BEFORE INSERT OR UPDATE ON comments
+ FOR EACH ROW EXECUTE PROCEDURE tg_check_reply_scope();
+
+CREATE TRIGGER soft_delete_reactions_on_comment_delete
+ AFTER UPDATE ON comments
+ FOR EACH ROW WHEN (NEW.is_deleted)
+ EXECUTE PROCEDURE tg_soft_delete_reactions_on_comment_delete();
+
+-- Reactions table (multi-scope: collection, file, or comment)
+CREATE TABLE IF NOT EXISTS reactions (
+ id TEXT PRIMARY KEY,
+
+ collection_id BIGINT NOT NULL,
+ file_id BIGINT NULL, -- present when reacting to a file in a collection
+ comment_id TEXT NULL, -- present when reacting to a specific comment
+
+ user_id BIGINT NOT NULL, -- reactor
+ anon_user_id TEXT NULL,
+
+ actor_key TEXT GENERATED ALWAYS AS (
+ CASE
+ WHEN user_id = -1 AND anon_user_id IS NOT NULL THEN 'A:' || anon_user_id
+ ELSE 'U:' || user_id::TEXT
+ END
+ ) STORED,
+
+ cipher TEXT,
+ nonce TEXT,
+
+ 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(),
+
+ -- Only one of: comment OR (collection[/file])
+ CONSTRAINT reactions_target_shape CHECK (
+ (comment_id IS NOT NULL AND file_id IS NULL)
+ OR
+ (comment_id IS NULL)
+ ),
+
+ -- Enforce payload nulling on tombstone
+ CONSTRAINT reactions_cipher_on_delete CHECK (
+ (is_deleted = FALSE AND cipher IS NOT NULL AND nonce IS NOT NULL) OR
+ (is_deleted = TRUE AND cipher IS NULL AND nonce IS NULL)
+ ),
+
+ -- Unified identity for target to enforce one-per-user-per-target
+ unique_key TEXT GENERATED ALWAYS AS (
+ CASE
+ WHEN comment_id IS NOT NULL THEN 'M:' || comment_id::TEXT
+ WHEN file_id IS NOT NULL THEN 'F:' || collection_id::TEXT || '/' || file_id::TEXT
+ ELSE 'C:' || collection_id::TEXT
+ END
+ ) STORED,
+
+ CONSTRAINT uq_reactions_actor_target UNIQUE (actor_key, unique_key),
+ CONSTRAINT reactions_user_or_anon_chk CHECK (
+ (user_id = -1 AND anon_user_id IS NOT NULL) OR
+ (user_id > 0 AND anon_user_id IS NULL)
+ ),
+ CONSTRAINT fk_reactions_anon_user FOREIGN KEY (anon_user_id) REFERENCES anon_users (id)
+);
+
+-- Indexes for reactions
+CREATE INDEX IF NOT EXISTS idx_reactions_scope
+ ON reactions (collection_id, file_id, comment_id)
+ WHERE is_deleted = FALSE;
+
+-- Delta sync by collection and updated_at
+CREATE INDEX IF NOT EXISTS idx_reactions_collection_updated_at
+ ON reactions (collection_id, updated_at);
+
+-- Per-comment lookups
+CREATE INDEX IF NOT EXISTS idx_reactions_comment
+ ON reactions (comment_id)
+ WHERE is_deleted = FALSE;
+
+CREATE INDEX IF NOT EXISTS idx_reactions_user
+ ON reactions (user_id)
+ WHERE is_deleted = FALSE;
+
+CREATE INDEX IF NOT EXISTS idx_reactions_anon
+ ON reactions (anon_user_id)
+ WHERE is_deleted = FALSE;
+
+-- Triggers for reactions
+CREATE TRIGGER reactions_null_cipher_on_delete
+ BEFORE INSERT OR UPDATE ON reactions
+ FOR EACH ROW EXECUTE PROCEDURE tg_null_cipher_on_delete();
+
+CREATE TRIGGER update_reactions_updated_at
+ BEFORE UPDATE ON reactions
+ FOR EACH ROW EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
+
+CREATE TRIGGER check_reaction_target
+ BEFORE INSERT OR UPDATE ON reactions
+ FOR EACH ROW EXECUTE PROCEDURE tg_check_reaction_target();
diff --git a/server/pkg/api/comments.go b/server/pkg/api/comments.go
new file mode 100644
index 0000000000..4eebd15707
--- /dev/null
+++ b/server/pkg/api/comments.go
@@ -0,0 +1,166 @@
+package api
+
+import (
+ "net/http"
+ "strconv"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/pkg/controller/social"
+ "github.com/ente-io/museum/pkg/utils/auth"
+ "github.com/ente-io/museum/pkg/utils/handler"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+const maxCommentPayloadBytes = 20 * 1024
+
+// CommentsHandler exposes authenticated comment APIs.
+type CommentsHandler struct {
+ Controller *social.CommentsController
+}
+
+type createCommentPayload struct {
+ ID string `json:"id"`
+ CollectionID int64 `json:"collectionID" binding:"required"`
+ FileID *int64 `json:"fileID"`
+ ParentCommentID *string `json:"parentCommentID"`
+ Cipher string `json:"cipher" binding:"required"`
+ Nonce string `json:"nonce" binding:"required"`
+}
+
+type updateCommentPayload struct {
+ Cipher string `json:"cipher" binding:"required"`
+ Nonce string `json:"nonce" binding:"required"`
+}
+
+func (h *CommentsHandler) Create(c *gin.Context) {
+ var payload createCommentPayload
+ if err := c.ShouldBindJSON(&payload); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ if len(payload.Cipher) == 0 || len(payload.Cipher) > maxCommentPayloadBytes || len(payload.Nonce) == 0 {
+ handler.Error(c, ente.ErrBadRequest)
+ return
+ }
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ req := social.CreateCommentRequest{
+ Actor: social.Actor{UserID: &userID},
+ CollectionID: payload.CollectionID,
+ FileID: payload.FileID,
+ ParentCommentID: payload.ParentCommentID,
+ Cipher: payload.Cipher,
+ Nonce: payload.Nonce,
+ ID: payload.ID,
+ RequireAccess: true,
+ }
+ id, err := h.Controller.Create(c, req)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusCreated, gin.H{"id": id})
+}
+
+func (h *CommentsHandler) Diff(c *gin.Context) {
+ collectionID, err := strconv.ParseInt(c.Query("collectionID"), 10, 64)
+ if err != nil || collectionID <= 0 {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "invalid collectionID"))
+ return
+ }
+ since, err := parseDiffSinceTime(c.Query("sinceTime"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ limit, err := parseDiffLimit(c.Query("limit"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ fileID, err := parseOptionalInt64(c.Query("fileID"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ req := social.CommentDiffRequest{
+ Actor: social.Actor{UserID: &userID},
+ CollectionID: collectionID,
+ Since: since,
+ Limit: limit,
+ FileID: fileID,
+ RequireAccess: true,
+ }
+ comments, hasMore, err := h.Controller.Diff(c, req)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"comments": comments, "hasMore": hasMore})
+}
+
+func (h *CommentsHandler) Update(c *gin.Context) {
+ commentID := c.Param("commentID")
+ if commentID == "" {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "commentID required"))
+ return
+ }
+ var payload updateCommentPayload
+ if err := c.ShouldBindJSON(&payload); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ if len(payload.Cipher) == 0 || len(payload.Cipher) > maxCommentPayloadBytes || len(payload.Nonce) == 0 {
+ handler.Error(c, ente.ErrBadRequest)
+ return
+ }
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ req := social.UpdateCommentRequest{
+ Actor: social.Actor{UserID: &userID},
+ CommentID: commentID,
+ Cipher: payload.Cipher,
+ Nonce: payload.Nonce,
+ RequireAccess: true,
+ }
+ if err := h.Controller.UpdatePayload(c, req); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{})
+}
+
+func (h *CommentsHandler) Delete(c *gin.Context) {
+ commentID := c.Param("commentID")
+ if commentID == "" {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "commentID required"))
+ return
+ }
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ req := social.DeleteCommentRequest{
+ Actor: social.Actor{UserID: &userID},
+ CommentID: commentID,
+ RequireAccess: true,
+ }
+ if err := h.Controller.Delete(c, req); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{})
+}
diff --git a/server/pkg/api/diff_utils.go b/server/pkg/api/diff_utils.go
new file mode 100644
index 0000000000..1fa6e70d4b
--- /dev/null
+++ b/server/pkg/api/diff_utils.go
@@ -0,0 +1,47 @@
+package api
+
+import (
+ "strconv"
+
+ "github.com/ente-io/museum/ente"
+)
+
+const (
+ diffDefaultLimit = 1000
+ diffMaxLimit = 2000
+)
+
+func parseDiffSinceTime(raw string) (int64, error) {
+ if raw == "" {
+ return 0, nil
+ }
+ return strconv.ParseInt(raw, 10, 64)
+}
+
+func parseDiffLimit(raw string) (int, error) {
+ if raw == "" {
+ return diffDefaultLimit, nil
+ }
+ limit, err := strconv.Atoi(raw)
+ if err != nil {
+ return 0, err
+ }
+ if limit <= 0 {
+ return 0, ente.ErrBadRequest
+ }
+ if limit > diffMaxLimit {
+ limit = diffMaxLimit
+ }
+ return limit, nil
+}
+
+func parseOptionalInt64(raw string) (*int64, error) {
+ if raw == "" {
+ return nil, nil
+ }
+ value, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ return &value, nil
+}
diff --git a/server/pkg/api/public_comments.go b/server/pkg/api/public_comments.go
new file mode 100644
index 0000000000..155a24c33f
--- /dev/null
+++ b/server/pkg/api/public_comments.go
@@ -0,0 +1,335 @@
+package api
+
+import (
+ "net/http"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/pkg/controller/public"
+ "github.com/ente-io/museum/pkg/utils/auth"
+ "github.com/ente-io/museum/pkg/utils/handler"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+// PublicCommentsHandler handles public collection social APIs.
+type PublicCommentsHandler struct {
+ CommentsCtrl *public.CommentsController
+ ReactionsCtrl *public.ReactionsController
+ AnonIdentityCtrl *public.AnonIdentityController
+}
+
+const (
+ maxPublicCommentCipherSize = 20 * 1024
+ maxPublicReactionCipherSize = 2 * 1024
+)
+
+type publicCommentPayload struct {
+ ID string `json:"id"`
+ FileID *int64 `json:"fileID"`
+ ParentCommentID *string `json:"parentCommentID"`
+ Cipher string `json:"cipher" binding:"required"`
+ Nonce string `json:"nonce" binding:"required"`
+ AnonUserID *string `json:"anonUserID"`
+ AnonToken string `json:"anonToken"`
+}
+
+type publicCommentEditPayload struct {
+ Cipher string `json:"cipher" binding:"required"`
+ Nonce string `json:"nonce" binding:"required"`
+ AnonUserID *string `json:"anonUserID"`
+ AnonToken string `json:"anonToken"`
+}
+
+type publicAnonPayload struct {
+ AnonUserID *string `json:"anonUserID"`
+ AnonToken string `json:"anonToken"`
+}
+
+type publicReactionPayload struct {
+ ID string `json:"id"`
+ FileID *int64 `json:"fileID"`
+ CommentID *string `json:"commentID"`
+ Cipher string `json:"cipher" binding:"required"`
+ Nonce string `json:"nonce" binding:"required"`
+ AnonUserID *string `json:"anonUserID"`
+ AnonToken string `json:"anonToken"`
+}
+
+type publicReactionDeletePayload struct {
+ AnonUserID *string `json:"anonUserID"`
+ AnonToken string `json:"anonToken"`
+}
+
+type publicAnonIdentityPayload struct {
+ Cipher string `json:"cipher" binding:"required"`
+ Nonce string `json:"nonce" binding:"required"`
+}
+
+func (h *PublicCommentsHandler) CreateComment(c *gin.Context) {
+ var payload publicCommentPayload
+ if err := c.ShouldBindJSON(&payload); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ if len(payload.Cipher) == 0 || len(payload.Cipher) > maxPublicCommentCipherSize || len(payload.Nonce) == 0 {
+ handler.Error(c, ente.ErrBadRequest)
+ return
+ }
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ controllerReq := public.CommentRequest{
+ ID: payload.ID,
+ FileID: payload.FileID,
+ ParentCommentID: payload.ParentCommentID,
+ Cipher: payload.Cipher,
+ Nonce: payload.Nonce,
+ AnonUserID: payload.AnonUserID,
+ AnonToken: payload.AnonToken,
+ }
+ id, err := h.CommentsCtrl.CreateComment(c, collectionID, controllerReq)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusCreated, gin.H{"id": id})
+}
+
+func (h *PublicCommentsHandler) UpdateComment(c *gin.Context) {
+ var payload publicCommentEditPayload
+ if err := c.ShouldBindJSON(&payload); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ if len(payload.Cipher) == 0 || len(payload.Cipher) > maxPublicCommentCipherSize || len(payload.Nonce) == 0 {
+ handler.Error(c, ente.ErrBadRequest)
+ return
+ }
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ commentID := c.Param("commentID")
+ if commentID == "" {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "missing commentID"))
+ return
+ }
+ controllerReq := public.CommentUpdateRequest{
+ Cipher: payload.Cipher,
+ Nonce: payload.Nonce,
+ AnonUserID: payload.AnonUserID,
+ AnonToken: payload.AnonToken,
+ }
+ if err := h.CommentsCtrl.UpdateComment(c, collectionID, commentID, controllerReq); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{})
+}
+
+func (h *PublicCommentsHandler) DeleteComment(c *gin.Context) {
+ var payload publicAnonPayload
+ if err := c.ShouldBindJSON(&payload); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ commentID := c.Param("commentID")
+ if commentID == "" {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "missing commentID"))
+ return
+ }
+ controllerReq := public.CommentDeleteRequest{
+ AnonUserID: payload.AnonUserID,
+ AnonToken: payload.AnonToken,
+ }
+ if err := h.CommentsCtrl.DeleteComment(c, collectionID, commentID, controllerReq); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{})
+}
+
+func (h *PublicCommentsHandler) CommentDiff(c *gin.Context) {
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ since, err := parseDiffSinceTime(c.Query("sinceTime"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ limit, err := parseDiffLimit(c.Query("limit"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ fileID, err := parseOptionalInt64(c.Query("fileID"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ comments, hasMore, err := h.CommentsCtrl.ListComments(c, collectionID, since, limit, fileID)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"comments": comments, "hasMore": hasMore})
+}
+
+func (h *PublicCommentsHandler) CreateReaction(c *gin.Context) {
+ var payload publicReactionPayload
+ if err := c.ShouldBindJSON(&payload); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ if len(payload.Cipher) == 0 || len(payload.Cipher) > maxPublicReactionCipherSize || len(payload.Nonce) == 0 {
+ handler.Error(c, ente.ErrBadRequest)
+ return
+ }
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ controllerReq := public.ReactionRequest{
+ ID: payload.ID,
+ FileID: payload.FileID,
+ CommentID: payload.CommentID,
+ Cipher: payload.Cipher,
+ Nonce: payload.Nonce,
+ AnonUserID: payload.AnonUserID,
+ AnonToken: payload.AnonToken,
+ }
+ id, err := h.ReactionsCtrl.UpsertReaction(c, collectionID, controllerReq)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"id": id})
+}
+
+func (h *PublicCommentsHandler) ReactionDiff(c *gin.Context) {
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ since, err := parseDiffSinceTime(c.Query("sinceTime"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ limit, err := parseDiffLimit(c.Query("limit"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ fileID, err := parseOptionalInt64(c.Query("fileID"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ commentIDRaw := c.Query("commentID")
+ var commentID *string
+ if commentIDRaw != "" {
+ commentID = &commentIDRaw
+ }
+ reactions, hasMore, err := h.ReactionsCtrl.ListReactions(c, collectionID, since, limit, fileID, commentID)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"reactions": reactions, "hasMore": hasMore})
+}
+
+func (h *PublicCommentsHandler) DeleteReaction(c *gin.Context) {
+ var payload publicReactionDeletePayload
+ if err := c.ShouldBindJSON(&payload); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ reactionID := c.Param("reactionID")
+ if reactionID == "" {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "missing reactionID"))
+ return
+ }
+ controllerReq := public.ReactionDeleteRequest{
+ AnonUserID: payload.AnonUserID,
+ AnonToken: payload.AnonToken,
+ }
+ if err := h.ReactionsCtrl.DeleteReaction(c, collectionID, reactionID, controllerReq); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{})
+}
+
+func (h *PublicCommentsHandler) Participants(c *gin.Context) {
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ // ignore includeSharees flag for now
+ participants, err := h.CommentsCtrl.Participants(c.Request.Context(), collectionID)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"participants": participants})
+}
+
+func (h *PublicCommentsHandler) CreateAnonIdentity(c *gin.Context) {
+ var payload publicAnonIdentityPayload
+ if err := c.ShouldBindJSON(&payload); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ if len(payload.Cipher) == 0 || len(payload.Nonce) == 0 {
+ handler.Error(c, ente.ErrBadRequest)
+ return
+ }
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ resp, err := h.AnonIdentityCtrl.Create(c, public.CreateAnonIdentityRequest{
+ CollectionID: collectionID,
+ Cipher: payload.Cipher,
+ Nonce: payload.Nonce,
+ })
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusCreated, resp)
+}
+
+func (h *PublicCommentsHandler) AnonProfiles(c *gin.Context) {
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ profiles, err := h.CommentsCtrl.ListAnonProfiles(c, collectionID)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"profiles": profiles})
+}
+
+// SocialDiff returns both comments and reactions in a single response.
+func (h *PublicCommentsHandler) SocialDiff(c *gin.Context) {
+ collectionID := auth.MustGetPublicAccessContext(c).CollectionID
+ since, err := parseDiffSinceTime(c.Query("sinceTime"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ limit, err := parseDiffLimit(c.Query("limit"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ fileID, err := parseOptionalInt64(c.Query("fileID"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+
+ comments, hasMoreComments, err := h.CommentsCtrl.ListComments(c, collectionID, since, limit, fileID)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+
+ reactions, hasMoreReactions, err := h.ReactionsCtrl.ListReactions(c, collectionID, since, limit, fileID, nil)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "comments": comments,
+ "reactions": reactions,
+ "hasMoreComments": hasMoreComments,
+ "hasMoreReactions": hasMoreReactions,
+ })
+}
diff --git a/server/pkg/api/reactions.go b/server/pkg/api/reactions.go
new file mode 100644
index 0000000000..6cb9941a32
--- /dev/null
+++ b/server/pkg/api/reactions.go
@@ -0,0 +1,133 @@
+package api
+
+import (
+ "net/http"
+ "strconv"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/pkg/controller/social"
+ "github.com/ente-io/museum/pkg/utils/auth"
+ "github.com/ente-io/museum/pkg/utils/handler"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+const reactionCipherLength = 156
+
+// ReactionsHandler exposes authenticated reaction APIs.
+type ReactionsHandler struct {
+ Controller *social.ReactionsController
+}
+
+type reactionPayload struct {
+ ID string `json:"id"`
+ CollectionID int64 `json:"collectionID" binding:"required"`
+ FileID *int64 `json:"fileID"`
+ CommentID *string `json:"commentID"`
+ Cipher string `json:"cipher" binding:"required"`
+ Nonce string `json:"nonce" binding:"required"`
+}
+
+func (h *ReactionsHandler) Upsert(c *gin.Context) {
+ var payload reactionPayload
+ if err := c.ShouldBindJSON(&payload); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ if len(payload.Cipher) != reactionCipherLength || len(payload.Nonce) == 0 {
+ handler.Error(c, ente.ErrBadRequest)
+ return
+ }
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ req := social.UpsertReactionRequest{
+ Actor: social.Actor{UserID: &userID},
+ ID: payload.ID,
+ CollectionID: payload.CollectionID,
+ FileID: payload.FileID,
+ CommentID: payload.CommentID,
+ Cipher: payload.Cipher,
+ Nonce: payload.Nonce,
+ RequireAccess: true,
+ }
+ id, err := h.Controller.Upsert(c, req)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"id": id})
+}
+
+func (h *ReactionsHandler) Diff(c *gin.Context) {
+ collectionID, err := strconv.ParseInt(c.Query("collectionID"), 10, 64)
+ if err != nil || collectionID <= 0 {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "invalid collectionID"))
+ return
+ }
+ since, err := parseDiffSinceTime(c.Query("sinceTime"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ limit, err := parseDiffLimit(c.Query("limit"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ fileID, err := parseOptionalInt64(c.Query("fileID"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ commentIDRaw := c.Query("commentID")
+ var commentID *string
+ if commentIDRaw != "" {
+ commentID = &commentIDRaw
+ }
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ req := social.ReactionDiffRequest{
+ Actor: social.Actor{UserID: &userID},
+ CollectionID: collectionID,
+ Since: since,
+ Limit: limit,
+ FileID: fileID,
+ CommentID: commentID,
+ RequireAccess: true,
+ }
+ resp, hasMore, err := h.Controller.Diff(c, req)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"reactions": resp, "hasMore": hasMore})
+}
+
+func (h *ReactionsHandler) Delete(c *gin.Context) {
+ reactionID := c.Param("reactionID")
+ if reactionID == "" {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "reactionID required"))
+ return
+ }
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ req := social.ReactionDeleteRequest{
+ Actor: social.Actor{UserID: &userID},
+ ReactionID: reactionID,
+ RequireAccess: true,
+ }
+ if err := h.Controller.Delete(c, req); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{})
+}
diff --git a/server/pkg/api/social.go b/server/pkg/api/social.go
new file mode 100644
index 0000000000..08a9c70ba3
--- /dev/null
+++ b/server/pkg/api/social.go
@@ -0,0 +1,138 @@
+package api
+
+import (
+ "net/http"
+ "strconv"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/pkg/controller/social"
+ "github.com/ente-io/museum/pkg/utils/auth"
+ "github.com/ente-io/museum/pkg/utils/handler"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+// SocialHandler exposes unified diff and counts endpoints.
+type SocialHandler struct {
+ Controller *social.Controller
+}
+
+func (h *SocialHandler) UnifiedDiff(c *gin.Context) {
+ collectionID, err := strconv.ParseInt(c.Query("collectionID"), 10, 64)
+ if err != nil || collectionID <= 0 {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "invalid collectionID"))
+ return
+ }
+ baseSinceRaw := c.Query("sinceTime")
+ baseSince, err := parseDiffSinceTime(baseSinceRaw)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ commentsSinceRaw := c.Query("commentsSinceTime")
+ commentsSince, err := parseDiffSinceTime(commentsSinceRaw)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ if commentsSinceRaw == "" {
+ commentsSince = baseSince
+ }
+ reactionsSinceRaw := c.Query("reactionsSinceTime")
+ reactionsSince, err := parseDiffSinceTime(reactionsSinceRaw)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ if reactionsSinceRaw == "" {
+ reactionsSince = baseSince
+ }
+ limit, err := parseDiffLimit(c.Query("limit"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ fileID, err := parseOptionalInt64(c.Query("fileID"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ req := social.UnifiedDiffRequest{
+ Actor: social.Actor{UserID: &userID},
+ CollectionID: collectionID,
+ CommentsSince: commentsSince,
+ ReactionsSince: reactionsSince,
+ Limit: limit,
+ FileID: fileID,
+ RequireAccess: true,
+ }
+ comments, reactions, hasMoreComments, hasMoreReactions, err := h.Controller.UnifiedDiff(c, req)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "comments": comments,
+ "reactions": reactions,
+ "hasMoreComments": hasMoreComments,
+ "hasMoreReactions": hasMoreReactions,
+ })
+}
+
+func (h *SocialHandler) Counts(c *gin.Context) {
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ counts, err := h.Controller.CountActiveCollections(c.Request.Context(), userID)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"counts": counts})
+}
+
+func (h *SocialHandler) LatestUpdates(c *gin.Context) {
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ app := auth.GetApp(c)
+ updates, err := h.Controller.LatestUpdates(c.Request.Context(), userID, app)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"updates": updates})
+}
+
+func (h *SocialHandler) AnonProfiles(c *gin.Context) {
+ collectionID, err := strconv.ParseInt(c.Query("collectionID"), 10, 64)
+ if err != nil || collectionID <= 0 {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBadRequest, "invalid collectionID"))
+ return
+ }
+ userID := auth.GetUserID(c.Request.Header)
+ if userID <= 0 {
+ handler.Error(c, ente.ErrAuthenticationRequired)
+ return
+ }
+ profiles, err := h.Controller.ListAnonProfiles(c, social.AnonProfilesRequest{
+ Actor: social.Actor{UserID: &userID},
+ CollectionID: collectionID,
+ RequireAccess: true,
+ })
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"profiles": profiles})
+}
+
diff --git a/server/pkg/controller/collections/collection.go b/server/pkg/controller/collections/collection.go
index b61f21466f..3ba16d35b2 100644
--- a/server/pkg/controller/collections/collection.go
+++ b/server/pkg/controller/collections/collection.go
@@ -3,11 +3,13 @@ package collections
import (
"context"
"fmt"
+
"github.com/ente-io/museum/pkg/controller"
"github.com/ente-io/museum/pkg/controller/access"
"github.com/ente-io/museum/pkg/controller/email"
"github.com/ente-io/museum/pkg/controller/public"
"github.com/ente-io/museum/pkg/repo/cast"
+ socialrepo "github.com/ente-io/museum/pkg/repo/social"
"github.com/ente-io/museum/pkg/utils/array"
"github.com/ente-io/museum/pkg/utils/auth"
"github.com/gin-gonic/gin"
@@ -25,17 +27,19 @@ const (
// CollectionController encapsulates logic that deals with collections
type CollectionController struct {
- CollectionLinkCtrl *public.CollectionLinkController
- EmailCtrl *email.EmailNotificationController
- AccessCtrl access.Controller
- BillingCtrl *controller.BillingController
- CollectionRepo *repo.CollectionRepository
- UserRepo *repo.UserRepository
- FileRepo *repo.FileRepository
- QueueRepo *repo.QueueRepository
- CastRepo *cast.Repository
- TaskRepo *repo.TaskLockRepository
- CollectionActionsRepo *repo.CollectionActionsRepository
+ CollectionLinkCtrl *public.CollectionLinkController
+ EmailCtrl *email.EmailNotificationController
+ AccessCtrl access.Controller
+ BillingCtrl *controller.BillingController
+ CollectionRepo *repo.CollectionRepository
+ UserRepo *repo.UserRepository
+ FileRepo *repo.FileRepository
+ QueueRepo *repo.QueueRepository
+ CastRepo *cast.Repository
+ TaskRepo *repo.TaskLockRepository
+ CollectionActionsRepo *repo.CollectionActionsRepository
+ CommentsRepo *socialrepo.CommentsRepository
+ ReactionsRepo *socialrepo.ReactionsRepository
}
// Create creates a collection
@@ -58,8 +62,8 @@ func (c *CollectionController) Create(collection ente.Collection, ownerID int64)
}
collection, err := c.CollectionRepo.Create(collection)
if err != nil {
- if err == ente.ErrUncategorizeCollectionAlreadyExists || err == ente.ErrFavoriteCollectionAlreadyExist {
- dbCollection, err := c.CollectionRepo.GetCollectionByType(ownerID, collectionType, app)
+ if err == ente.ErrUncategorizeCollectionAlreadyExists || err == ente.ErrFavoriteCollectionAlreadyExist {
+ dbCollection, err := c.CollectionRepo.GetCollectionByType(ownerID, collectionType, app)
if err != nil {
return ente.Collection{}, stacktrace.Propagate(err, "")
}
@@ -214,6 +218,9 @@ func (c *CollectionController) HandleAccountDeletion(ctx context.Context, userID
if err != nil {
return stacktrace.Propagate(err, "")
}
+ if cleanupErr := c.removeUserSocialActivity(ctx, shareCollection.CollectionID, shareCollection.ToUserID); cleanupErr != nil {
+ return cleanupErr
+ }
}
err = c.CastRepo.RevokeTokenForUser(ctx, userID)
if err != nil {
@@ -234,3 +241,17 @@ func (c *CollectionController) verifyOwnership(cID int64, userID int64) error {
}
return nil
}
+
+func (c *CollectionController) removeUserSocialActivity(ctx context.Context, collectionID int64, userID int64) error {
+ if c.CommentsRepo != nil {
+ if err := c.CommentsRepo.SoftDeleteByCollectionAndUser(ctx, collectionID, userID); err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ }
+ if c.ReactionsRepo != nil {
+ if err := c.ReactionsRepo.SoftDeleteByCollectionAndUser(ctx, collectionID, userID); err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ }
+ return nil
+}
diff --git a/server/pkg/controller/collections/share.go b/server/pkg/controller/collections/share.go
index c7ed08bf2a..efb04ba13a 100644
--- a/server/pkg/controller/collections/share.go
+++ b/server/pkg/controller/collections/share.go
@@ -146,6 +146,9 @@ func (c *CollectionController) UnShare(ctx *gin.Context, cID int64, fromUserID i
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
+ if err := c.removeUserSocialActivity(ctx.Request.Context(), cID, toUserID); err != nil {
+ return nil, err
+ }
err = c.CastRepo.RevokeForGivenUserAndCollection(ctx, cID, toUserID)
if err != nil {
return nil, stacktrace.Propagate(err, "")
@@ -182,6 +185,9 @@ func (c *CollectionController) Leave(ctx *gin.Context, cID int64) error {
if err != nil {
return stacktrace.Propagate(err, "")
}
+ if err := c.removeUserSocialActivity(ctx.Request.Context(), cID, userID); err != nil {
+ return err
+ }
return nil
}
diff --git a/server/pkg/controller/public/actor.go b/server/pkg/controller/public/actor.go
new file mode 100644
index 0000000000..d1dd4bd0f2
--- /dev/null
+++ b/server/pkg/controller/public/actor.go
@@ -0,0 +1,91 @@
+package public
+
+import (
+ "database/sql"
+ "errors"
+ "strings"
+
+ "github.com/ente-io/museum/ente"
+ socialcontroller "github.com/ente-io/museum/pkg/controller/social"
+ "github.com/ente-io/museum/pkg/repo"
+ "github.com/ente-io/museum/pkg/utils/auth"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+func resolvePublicActor(c *gin.Context, userAuthRepo *repo.UserAuthRepository, jwtSecret []byte, bodyAnonID *string, bodyAnonToken string, requireIdentity bool) (socialcontroller.Actor, error) {
+ if ctxAnonID, ok := auth.GetPublicAnonUserID(c); ok && ctxAnonID != nil && *ctxAnonID != "" {
+ actor := socialcontroller.Actor{AnonUserID: ctxAnonID}
+ if err := actor.ValidateAnon(); err != nil {
+ return socialcontroller.Actor{}, err
+ }
+ return actor, nil
+ }
+ if token := auth.GetToken(c); token != "" {
+ app := auth.GetApp(c)
+ userID, expired, err := userAuthRepo.GetUserIDWithToken(token, app)
+ if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return socialcontroller.Actor{}, ente.ErrAuthenticationRequired
+ }
+ return socialcontroller.Actor{}, stacktrace.Propagate(err, "")
+ }
+ if expired {
+ return socialcontroller.Actor{}, ente.ErrAuthenticationRequired
+ }
+ return socialcontroller.Actor{UserID: &userID}, nil
+
+ }
+
+ anonID, anonToken := extractAnonIdentity(c, bodyAnonID, bodyAnonToken)
+ if anonID == nil || anonToken == "" {
+ if requireIdentity {
+ return socialcontroller.Actor{}, ente.ErrAuthenticationRequired
+ }
+ return socialcontroller.Actor{}, nil
+ }
+ claim, err := ente.ParseAnonymousIdentityToken(jwtSecret, anonToken)
+ if err != nil {
+ return socialcontroller.Actor{}, stacktrace.Propagate(err, "")
+ }
+ if claim.Subject != *anonID {
+ return socialcontroller.Actor{}, ente.ErrBadRequest
+ }
+ actor := socialcontroller.Actor{AnonUserID: anonID}
+ if err := actor.ValidateAnon(); err != nil {
+ return socialcontroller.Actor{}, err
+ }
+ return actor, nil
+}
+
+func extractAnonIdentity(c *gin.Context, bodyAnonID *string, bodyAnonToken string) (*string, string) {
+ headerAnonID := strings.TrimSpace(c.GetHeader("X-Anon-User-ID"))
+ var anonID *string
+ if headerAnonID != "" {
+ copyID := headerAnonID
+ anonID = &copyID
+ }
+ headerToken := parseBearerToken(c.GetHeader("Authorization"))
+ token := headerToken
+ if token == "" {
+ token = strings.TrimSpace(bodyAnonToken)
+ }
+ if anonID == nil && bodyAnonID != nil && *bodyAnonID != "" {
+ anonID = bodyAnonID
+ }
+ return anonID, token
+}
+
+func parseBearerToken(header string) string {
+ if header == "" {
+ return ""
+ }
+ parts := strings.SplitN(header, " ", 2)
+ if len(parts) != 2 {
+ return ""
+ }
+ if strings.EqualFold(parts[0], "Bearer") {
+ return strings.TrimSpace(parts[1])
+ }
+ return ""
+}
diff --git a/server/pkg/controller/public/anon_identity.go b/server/pkg/controller/public/anon_identity.go
new file mode 100644
index 0000000000..66f31dc622
--- /dev/null
+++ b/server/pkg/controller/public/anon_identity.go
@@ -0,0 +1,61 @@
+package public
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/ente-io/museum/ente"
+ socialentity "github.com/ente-io/museum/ente/social"
+ socialrepo "github.com/ente-io/museum/pkg/repo/social"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+ gonanoid "github.com/matoous/go-nanoid/v2"
+)
+
+// AnonIdentityController issues anonymous identities for public commenters.
+type AnonIdentityController struct {
+ JwtSecret []byte
+ AnonUsersRepo *socialrepo.AnonUsersRepository
+}
+
+// AnonIdentityResponse is returned when minting anon identities.
+type AnonIdentityResponse struct {
+ AnonUserID string `json:"anonUserID"`
+ Token string `json:"token"`
+ ExpiresAt int64 `json:"expiresAt"`
+}
+
+// CreateAnonIdentityRequest captures the profile payload for a new anonymous user.
+type CreateAnonIdentityRequest struct {
+ CollectionID int64
+ Cipher string
+ Nonce string
+}
+
+func (c *AnonIdentityController) Create(ctx *gin.Context, req CreateAnonIdentityRequest) (AnonIdentityResponse, error) {
+ if strings.TrimSpace(req.Cipher) == "" || strings.TrimSpace(req.Nonce) == "" {
+ return AnonIdentityResponse{}, ente.ErrBadRequest
+ }
+ rawID, err := gonanoid.New()
+ if err != nil {
+ return AnonIdentityResponse{}, stacktrace.Propagate(err, "")
+ }
+ anonID := fmt.Sprintf("anon_%s", rawID)
+ if err := c.AnonUsersRepo.Insert(ctx.Request.Context(), socialentity.AnonUser{
+ ID: anonID,
+ CollectionID: req.CollectionID,
+ Cipher: req.Cipher,
+ Nonce: req.Nonce,
+ }); err != nil {
+ return AnonIdentityResponse{}, stacktrace.Propagate(err, "")
+ }
+ token, expiresAt, err := ente.NewAnonymousIdentityToken(c.JwtSecret, anonID)
+ if err != nil {
+ return AnonIdentityResponse{}, stacktrace.Propagate(err, "")
+ }
+ return AnonIdentityResponse{
+ AnonUserID: anonID,
+ Token: token,
+ ExpiresAt: expiresAt,
+ }, nil
+}
diff --git a/server/pkg/controller/public/anon_user_validation.go b/server/pkg/controller/public/anon_user_validation.go
new file mode 100644
index 0000000000..488d733b2f
--- /dev/null
+++ b/server/pkg/controller/public/anon_user_validation.go
@@ -0,0 +1,32 @@
+package public
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+
+ "github.com/ente-io/museum/ente"
+ socialcontroller "github.com/ente-io/museum/pkg/controller/social"
+ socialrepo "github.com/ente-io/museum/pkg/repo/social"
+ "github.com/ente-io/stacktrace"
+)
+
+func ensureAnonUserForCollection(ctx context.Context, repo *socialrepo.AnonUsersRepository, collectionID int64, actor socialcontroller.Actor) error {
+ if repo == nil || !actor.IsAnonymous() {
+ return nil
+ }
+ if actor.AnonUserID == nil || *actor.AnonUserID == "" {
+ return ente.ErrBadRequest
+ }
+ anonUser, err := repo.GetByID(ctx, *actor.AnonUserID)
+ if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return ente.ErrAuthenticationRequired
+ }
+ return stacktrace.Propagate(err, "")
+ }
+ if anonUser.CollectionID != collectionID {
+ return ente.ErrPermissionDenied
+ }
+ return nil
+}
diff --git a/server/pkg/controller/public/comments.go b/server/pkg/controller/public/comments.go
new file mode 100644
index 0000000000..dea08225dd
--- /dev/null
+++ b/server/pkg/controller/public/comments.go
@@ -0,0 +1,172 @@
+package public
+
+import (
+ "context"
+ "sort"
+
+ "github.com/ente-io/museum/ente"
+ socialentity "github.com/ente-io/museum/ente/social"
+ socialcontroller "github.com/ente-io/museum/pkg/controller/social"
+ "github.com/ente-io/museum/pkg/repo"
+ socialrepo "github.com/ente-io/museum/pkg/repo/social"
+ emailUtil "github.com/ente-io/museum/pkg/utils/email"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+const maxCommentPayloadSize = 20 * 1024
+
+// CommentsController handles comments exposed via public collection links.
+type CommentsController struct {
+ CommentCtrl *socialcontroller.CommentsController
+ CommentsRepo *socialrepo.CommentsRepository
+ ReactionsRepo *socialrepo.ReactionsRepository
+ UserRepo *repo.UserRepository
+ UserAuthRepo *repo.UserAuthRepository
+ AnonUsersRepo *socialrepo.AnonUsersRepository
+ JwtSecret []byte
+}
+
+// CommentRequest models incoming payload for creating a comment.
+type CommentRequest struct {
+ ID string `json:"id"`
+ FileID *int64 `json:"fileID"`
+ ParentCommentID *string `json:"parentCommentID"`
+ Cipher string `json:"cipher" binding:"required"`
+ Nonce string `json:"nonce" binding:"required"`
+ AnonUserID *string `json:"anonUserID"`
+ AnonToken string `json:"anonToken"`
+}
+
+type CommentUpdateRequest struct {
+ Cipher string `json:"cipher" binding:"required"`
+ Nonce string `json:"nonce" binding:"required"`
+ AnonUserID *string `json:"anonUserID"`
+ AnonToken string `json:"anonToken"`
+}
+
+type CommentDeleteRequest struct {
+ AnonUserID *string `json:"anonUserID"`
+ AnonToken string `json:"anonToken"`
+}
+
+type participant struct {
+ UserID int64 `json:"userID"`
+ EmailMasked string `json:"emailMasked"`
+}
+
+func (c *CommentsController) CreateComment(ctx *gin.Context, collectionID int64, req CommentRequest) (string, error) {
+ if len(req.Cipher) == 0 || len(req.Cipher) > maxCommentPayloadSize {
+ return "", ente.ErrBadRequest
+ }
+ if len(req.Nonce) == 0 {
+ return "", ente.ErrBadRequest
+ }
+ actor, err := resolvePublicActor(ctx, c.UserAuthRepo, c.JwtSecret, req.AnonUserID, req.AnonToken, true)
+ if err != nil {
+ return "", err
+ }
+ if err := ensureAnonUserForCollection(ctx.Request.Context(), c.AnonUsersRepo, collectionID, actor); err != nil {
+ return "", err
+ }
+ createReq := socialcontroller.CreateCommentRequest{
+ Actor: actor,
+ CollectionID: collectionID,
+ FileID: req.FileID,
+ ParentCommentID: req.ParentCommentID,
+ Cipher: req.Cipher,
+ Nonce: req.Nonce,
+ ID: req.ID,
+ RequireAccess: false,
+ }
+ return c.CommentCtrl.Create(ctx, createReq)
+}
+
+func (c *CommentsController) UpdateComment(ctx *gin.Context, collectionID int64, commentID string, req CommentUpdateRequest) error {
+ if len(req.Cipher) == 0 || len(req.Cipher) > maxCommentPayloadSize {
+ return ente.ErrBadRequest
+ }
+ if len(req.Nonce) == 0 {
+ return ente.ErrBadRequest
+ }
+ actor, err := resolvePublicActor(ctx, c.UserAuthRepo, c.JwtSecret, req.AnonUserID, req.AnonToken, true)
+ if err != nil {
+ return err
+ }
+ if err := ensureAnonUserForCollection(ctx.Request.Context(), c.AnonUsersRepo, collectionID, actor); err != nil {
+ return err
+ }
+ updateReq := socialcontroller.UpdateCommentRequest{
+ Actor: actor,
+ CommentID: commentID,
+ Cipher: req.Cipher,
+ Nonce: req.Nonce,
+ }
+ return c.CommentCtrl.UpdatePayload(ctx, updateReq)
+}
+
+func (c *CommentsController) DeleteComment(ctx *gin.Context, collectionID int64, commentID string, req CommentDeleteRequest) error {
+ actor, err := resolvePublicActor(ctx, c.UserAuthRepo, c.JwtSecret, req.AnonUserID, req.AnonToken, true)
+ if err != nil {
+ return err
+ }
+ if err := ensureAnonUserForCollection(ctx.Request.Context(), c.AnonUsersRepo, collectionID, actor); err != nil {
+ return err
+ }
+ deleteReq := socialcontroller.DeleteCommentRequest{
+ Actor: actor,
+ CommentID: commentID,
+ RequireAccess: false,
+ }
+ return c.CommentCtrl.Delete(ctx, deleteReq)
+}
+
+func (c *CommentsController) ListComments(ctx *gin.Context, collectionID int64, since int64, limit int, fileID *int64) ([]socialentity.Comment, bool, error) {
+ diffReq := socialcontroller.CommentDiffRequest{
+ Actor: socialcontroller.Actor{},
+ CollectionID: collectionID,
+ Since: since,
+ Limit: limit,
+ FileID: fileID,
+ RequireAccess: false,
+ }
+ return c.CommentCtrl.Diff(ctx, diffReq)
+}
+
+func (c *CommentsController) Participants(ctx context.Context, collectionID int64) ([]participant, error) {
+ ids := map[int64]struct{}{}
+ commentIDs, err := c.CommentsRepo.GetActiveUserIDs(ctx, collectionID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ for _, id := range commentIDs {
+ ids[id] = struct{}{}
+ }
+ reactionIDs, err := c.ReactionsRepo.GetActiveUserIDs(ctx, collectionID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ for _, id := range reactionIDs {
+ ids[id] = struct{}{}
+ }
+ participants := make([]participant, 0, len(ids))
+ for id := range ids {
+ user, err := c.UserRepo.GetUserByIDInternal(id)
+ if err != nil {
+ continue
+ }
+ participants = append(participants, participant{
+ UserID: id,
+ EmailMasked: emailUtil.GetMaskedEmail(user.Email),
+ })
+ }
+ // Sort by userID for consistent ordering
+ sort.Slice(participants, func(i, j int) bool {
+ return participants[i].UserID < participants[j].UserID
+ })
+ return participants, nil
+}
+
+func (c *CommentsController) ListAnonProfiles(ctx *gin.Context, collectionID int64) ([]socialentity.AnonUser, error) {
+ return c.AnonUsersRepo.ListByCollection(ctx.Request.Context(), collectionID)
+}
diff --git a/server/pkg/controller/public/reactions.go b/server/pkg/controller/public/reactions.go
new file mode 100644
index 0000000000..29341a43c3
--- /dev/null
+++ b/server/pkg/controller/public/reactions.go
@@ -0,0 +1,89 @@
+package public
+
+import (
+ "github.com/ente-io/museum/ente"
+ socialentity "github.com/ente-io/museum/ente/social"
+ socialcontroller "github.com/ente-io/museum/pkg/controller/social"
+ "github.com/ente-io/museum/pkg/repo"
+ socialrepo "github.com/ente-io/museum/pkg/repo/social"
+ "github.com/gin-gonic/gin"
+)
+
+const reactionCipherLength = 156
+
+// ReactionsController exposes reactions for public collections.
+type ReactionsController struct {
+ ReactionCtrl *socialcontroller.ReactionsController
+ ReactionsRepo *socialrepo.ReactionsRepository
+ AnonUsersRepo *socialrepo.AnonUsersRepository
+ UserAuthRepo *repo.UserAuthRepository
+ JwtSecret []byte
+}
+
+type ReactionRequest struct {
+ ID string `json:"id"`
+ FileID *int64 `json:"fileID"`
+ CommentID *string `json:"commentID"`
+ Cipher string `json:"cipher" binding:"required"`
+ Nonce string `json:"nonce" binding:"required"`
+ AnonUserID *string `json:"anonUserID"`
+ AnonToken string `json:"anonToken"`
+}
+
+type ReactionDeleteRequest struct {
+ AnonUserID *string `json:"anonUserID"`
+ AnonToken string `json:"anonToken"`
+}
+
+func (c *ReactionsController) UpsertReaction(ctx *gin.Context, collectionID int64, req ReactionRequest) (string, error) {
+ if len(req.Cipher) != reactionCipherLength || len(req.Nonce) == 0 {
+ return "", ente.ErrBadRequest
+ }
+ actor, err := resolvePublicActor(ctx, c.UserAuthRepo, c.JwtSecret, req.AnonUserID, req.AnonToken, true)
+ if err != nil {
+ return "", err
+ }
+ if err := ensureAnonUserForCollection(ctx.Request.Context(), c.AnonUsersRepo, collectionID, actor); err != nil {
+ return "", err
+ }
+ upsertReq := socialcontroller.UpsertReactionRequest{
+ Actor: actor,
+ ID: req.ID,
+ CollectionID: collectionID,
+ FileID: req.FileID,
+ CommentID: req.CommentID,
+ Cipher: req.Cipher,
+ Nonce: req.Nonce,
+ RequireAccess: false,
+ }
+ return c.ReactionCtrl.Upsert(ctx, upsertReq)
+}
+
+func (c *ReactionsController) DeleteReaction(ctx *gin.Context, collectionID int64, reactionID string, req ReactionDeleteRequest) error {
+ actor, err := resolvePublicActor(ctx, c.UserAuthRepo, c.JwtSecret, req.AnonUserID, req.AnonToken, true)
+ if err != nil {
+ return err
+ }
+ if err := ensureAnonUserForCollection(ctx.Request.Context(), c.AnonUsersRepo, collectionID, actor); err != nil {
+ return err
+ }
+ deleteReq := socialcontroller.ReactionDeleteRequest{
+ Actor: actor,
+ ReactionID: reactionID,
+ RequireAccess: false,
+ }
+ return c.ReactionCtrl.Delete(ctx, deleteReq)
+}
+
+func (c *ReactionsController) ListReactions(ctx *gin.Context, collectionID int64, since int64, limit int, fileID *int64, commentID *string) ([]socialentity.Reaction, bool, error) {
+ diffReq := socialcontroller.ReactionDiffRequest{
+ Actor: socialcontroller.Actor{},
+ CollectionID: collectionID,
+ Since: since,
+ Limit: limit,
+ FileID: fileID,
+ CommentID: commentID,
+ RequireAccess: false,
+ }
+ return c.ReactionCtrl.Diff(ctx, diffReq)
+}
diff --git a/server/pkg/controller/social/actor.go b/server/pkg/controller/social/actor.go
new file mode 100644
index 0000000000..8756877c30
--- /dev/null
+++ b/server/pkg/controller/social/actor.go
@@ -0,0 +1,33 @@
+package social
+
+import "github.com/ente-io/museum/ente"
+
+// Actor represents a user identity (authenticated or anonymous) performing an action.
+type Actor struct {
+ UserID *int64
+ AnonUserID *string
+}
+
+// IsAnonymous reports whether the actor is using an anonymous persona.
+func (a Actor) IsAnonymous() bool {
+ return a.UserID == nil
+}
+
+// ValidateAnon ensures anonymous actors always supply an anonUserID.
+func (a Actor) ValidateAnon() error {
+ if !a.IsAnonymous() {
+ return nil
+ }
+ if a.AnonUserID == nil || *a.AnonUserID == "" {
+ return ente.ErrBadRequest
+ }
+ return nil
+}
+
+// UserIDValue returns the concrete userID if present.
+func (a Actor) UserIDValue() (int64, bool) {
+ if a.UserID == nil {
+ return 0, false
+ }
+ return *a.UserID, true
+}
diff --git a/server/pkg/controller/social/comment_validation_test.go b/server/pkg/controller/social/comment_validation_test.go
new file mode 100644
index 0000000000..b012d12b98
--- /dev/null
+++ b/server/pkg/controller/social/comment_validation_test.go
@@ -0,0 +1,76 @@
+package social
+
+import (
+ "testing"
+
+ socialentity "github.com/ente-io/museum/ente/social"
+ "github.com/stretchr/testify/require"
+)
+
+func TestValidateReplyFileContext(t *testing.T) {
+ fileID := int64(42)
+ otherFileID := int64(7)
+ parentWithFile := &socialentity.Comment{FileID: &fileID}
+ parentWithoutFile := &socialentity.Comment{}
+
+ tests := []struct {
+ name string
+ parent *socialentity.Comment
+ request *int64
+ wantErr bool
+ }{
+ {name: "no parent no file", parent: nil, request: nil, wantErr: false},
+ {name: "no parent with file", parent: nil, request: &fileID, wantErr: false},
+ {name: "parent without file and no request file", parent: parentWithoutFile, request: nil, wantErr: false},
+ {name: "parent without file but request file", parent: parentWithoutFile, request: &fileID, wantErr: true},
+ {name: "parent with file and matching request", parent: parentWithFile, request: &fileID, wantErr: false},
+ {name: "parent with file missing request", parent: parentWithFile, request: nil, wantErr: true},
+ {name: "parent with file mismatched request", parent: parentWithFile, request: &otherFileID, wantErr: true},
+ }
+
+ for _, tc := range tests {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ err := validateReplyFileContext(tc.parent, tc.request)
+ if tc.wantErr {
+ require.Error(t, err)
+ } else {
+ require.NoError(t, err)
+ }
+ })
+ }
+}
+
+func TestValidateCommentReactionContext(t *testing.T) {
+ fileID := int64(10)
+ otherFileID := int64(11)
+ commentWithFile := &socialentity.Comment{FileID: &fileID}
+ commentWithoutFile := &socialentity.Comment{}
+
+ tests := []struct {
+ name string
+ comment *socialentity.Comment
+ request *int64
+ wantErr bool
+ }{
+ {name: "nil comment no file", comment: nil, request: nil, wantErr: false},
+ {name: "nil comment with file", comment: nil, request: &fileID, wantErr: false},
+ {name: "comment without file no request file", comment: commentWithoutFile, request: nil, wantErr: false},
+ {name: "comment without file but request file", comment: commentWithoutFile, request: &fileID, wantErr: true},
+ {name: "comment with file missing request", comment: commentWithFile, request: nil, wantErr: true},
+ {name: "comment with file mismatch", comment: commentWithFile, request: &otherFileID, wantErr: true},
+ {name: "comment with file match", comment: commentWithFile, request: &fileID, wantErr: false},
+ }
+
+ for _, tc := range tests {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ err := validateCommentReactionContext(tc.comment, tc.request)
+ if tc.wantErr {
+ require.Error(t, err)
+ } else {
+ require.NoError(t, err)
+ }
+ })
+ }
+}
diff --git a/server/pkg/controller/social/comments_controller.go b/server/pkg/controller/social/comments_controller.go
new file mode 100644
index 0000000000..5e36baddb1
--- /dev/null
+++ b/server/pkg/controller/social/comments_controller.go
@@ -0,0 +1,228 @@
+package social
+
+import (
+ "github.com/ente-io/museum/ente"
+ socialentity "github.com/ente-io/museum/ente/social"
+ "github.com/ente-io/museum/pkg/controller/access"
+ socialrepo "github.com/ente-io/museum/pkg/repo/social"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+// CommentsController wires comment-specific business logic.
+type CommentsController struct {
+ Repo *socialrepo.CommentsRepository
+ AccessCtrl access.Controller
+}
+
+// CreateCommentRequest encapsulates parameters for adding a comment.
+type CreateCommentRequest struct {
+ Actor Actor
+ CollectionID int64
+ FileID *int64
+ ParentCommentID *string
+ Cipher string
+ Nonce string
+ ID string
+ RequireAccess bool
+}
+
+// CommentDiffRequest describes the paging request for a collection's comments.
+type CommentDiffRequest struct {
+ Actor Actor
+ CollectionID int64
+ Since int64
+ Limit int
+ FileID *int64
+ RequireAccess bool
+}
+
+// UpdateCommentRequest holds the information needed to edit a comment.
+type UpdateCommentRequest struct {
+ Actor Actor
+ CommentID string
+ Cipher string
+ Nonce string
+ RequireAccess bool
+}
+
+// DeleteCommentRequest defines the delete operation parameters.
+type DeleteCommentRequest struct {
+ Actor Actor
+ CommentID string
+ RequireAccess bool
+}
+
+// Create inserts a new comment; returns the supplied ID on success.
+func (c *CommentsController) Create(ctx *gin.Context, req CreateCommentRequest) (string, error) {
+ var err error
+ req.ID, err = NormalizeCommentID(req.ID)
+ if err != nil {
+ return "", stacktrace.Propagate(err, "")
+ }
+ if len(req.Cipher) == 0 || len(req.Nonce) == 0 {
+ return "", ente.ErrBadRequest
+ }
+ userID, hasUserID := req.Actor.UserIDValue()
+ if req.Actor.IsAnonymous() {
+ if err := req.Actor.ValidateAnon(); err != nil {
+ return "", err
+ }
+ } else if !hasUserID || userID <= 0 {
+ return "", ente.ErrAuthenticationRequired
+ }
+ if req.RequireAccess && req.Actor.IsAnonymous() {
+ return "", ente.ErrPermissionDenied
+ }
+ if req.RequireAccess {
+ if _, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
+ CollectionID: req.CollectionID,
+ ActorUserID: userID,
+ }); err != nil {
+ return "", stacktrace.Propagate(err, "")
+ }
+ }
+
+ var parentComment *socialentity.Comment
+ if req.ParentCommentID != nil {
+ parentComment, err = c.Repo.GetByID(ctx.Request.Context(), *req.ParentCommentID)
+ if err != nil {
+ return "", stacktrace.Propagate(err, "")
+ }
+ if parentComment.CollectionID != req.CollectionID {
+ return "", stacktrace.Propagate(ente.ErrBadRequest, "parent comment belongs to a different collection")
+ }
+ if parentComment.IsDeleted {
+ return "", stacktrace.Propagate(ente.ErrBadRequest, "cannot reply to a deleted comment")
+ }
+ }
+ if err := validateReplyFileContext(parentComment, req.FileID); err != nil {
+ return "", err
+ }
+
+ comment := socialentity.Comment{
+ ID: req.ID,
+ CollectionID: req.CollectionID,
+ FileID: req.FileID,
+ ParentCommentID: req.ParentCommentID,
+ UserID: -1,
+ AnonUserID: req.Actor.AnonUserID,
+ Cipher: req.Cipher,
+ Nonce: req.Nonce,
+ }
+ if hasUserID {
+ comment.UserID = userID
+ }
+ if len(req.Cipher) > 0 {
+ comment.Cipher = req.Cipher
+ }
+ if len(req.Nonce) > 0 {
+ comment.Nonce = req.Nonce
+ }
+ if err := c.Repo.Insert(ctx.Request.Context(), comment); err != nil {
+ return "", stacktrace.Propagate(err, "")
+ }
+ return comment.ID, nil
+}
+
+// Diff returns a window of comments for the requested collection.
+func (c *CommentsController) Diff(ctx *gin.Context, req CommentDiffRequest) ([]socialentity.Comment, bool, error) {
+ userID, hasUserID := req.Actor.UserIDValue()
+ if req.RequireAccess {
+ if !hasUserID || userID <= 0 {
+ return nil, false, ente.ErrAuthenticationRequired
+ }
+ if _, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
+ CollectionID: req.CollectionID,
+ ActorUserID: userID,
+ }); err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+ }
+ return c.Repo.GetDiff(ctx.Request.Context(), req.CollectionID, req.Since, req.Limit, req.FileID)
+}
+
+// UpdatePayload edits the encrypted payload of a comment.
+func (c *CommentsController) UpdatePayload(ctx *gin.Context, req UpdateCommentRequest) error {
+ if len(req.Cipher) == 0 || len(req.Nonce) == 0 {
+ return ente.ErrBadRequest
+ }
+ userID, hasUserID := req.Actor.UserIDValue()
+ comment, err := c.Repo.GetByID(ctx.Request.Context(), req.CommentID)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if req.Actor.IsAnonymous() {
+ if err := req.Actor.ValidateAnon(); err != nil {
+ return err
+ }
+ if comment.AnonUserID == nil || req.Actor.AnonUserID == nil || *comment.AnonUserID != *req.Actor.AnonUserID {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "")
+ }
+ } else if !hasUserID || comment.UserID != userID {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "")
+ }
+ return c.Repo.UpdateCipher(ctx.Request.Context(), req.CommentID, req.Cipher, req.Nonce)
+}
+
+// Delete removes a comment if the actor is allowed to do so.
+func (c *CommentsController) Delete(ctx *gin.Context, req DeleteCommentRequest) error {
+ userID, hasUserID := req.Actor.UserIDValue()
+ comment, err := c.Repo.GetByID(ctx.Request.Context(), req.CommentID)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ switch {
+ case req.Actor.IsAnonymous():
+ if err := req.Actor.ValidateAnon(); err != nil {
+ return err
+ }
+ if comment.AnonUserID == nil || req.Actor.AnonUserID == nil || *comment.AnonUserID != *req.Actor.AnonUserID {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "")
+ }
+ default:
+ if !hasUserID {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "")
+ }
+ if comment.UserID == userID {
+ // author is allowed
+ } else if req.RequireAccess {
+ resp, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
+ CollectionID: comment.CollectionID,
+ ActorUserID: userID,
+ })
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if resp.Role == nil {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "")
+ }
+ minRole := ente.ADMIN
+ if !resp.Role.Satisfies(&minRole) {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "")
+ }
+ } else {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "")
+ }
+ }
+ return c.Repo.SoftDelete(ctx.Request.Context(), req.CommentID)
+}
+
+func validateReplyFileContext(parent *socialentity.Comment, requestedFileID *int64) error {
+ if parent == nil {
+ return nil
+ }
+ if parent.FileID != nil {
+ switch {
+ case requestedFileID == nil:
+ return stacktrace.Propagate(ente.ErrBadRequest, "fileID is required when replying to a file-scoped comment")
+ case *requestedFileID != *parent.FileID:
+ return stacktrace.Propagate(ente.ErrBadRequest, "fileID must match the parent comment's fileID")
+ }
+ return nil
+ }
+ if requestedFileID != nil {
+ return stacktrace.Propagate(ente.ErrBadRequest, "fileID must be omitted when replying to a collection-level comment")
+ }
+ return nil
+}
diff --git a/server/pkg/controller/social/controller.go b/server/pkg/controller/social/controller.go
new file mode 100644
index 0000000000..5742904b7d
--- /dev/null
+++ b/server/pkg/controller/social/controller.go
@@ -0,0 +1,248 @@
+package social
+
+import (
+ "context"
+ "sort"
+
+ "github.com/ente-io/museum/ente"
+ socialentity "github.com/ente-io/museum/ente/social"
+ "github.com/ente-io/museum/pkg/controller/access"
+ "github.com/ente-io/museum/pkg/repo"
+ socialrepo "github.com/ente-io/museum/pkg/repo/social"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+// Controller combines comments and reactions for unified endpoints.
+type Controller struct {
+ CommentsRepo *socialrepo.CommentsRepository
+ ReactionsRepo *socialrepo.ReactionsRepository
+ CollectionRepo *repo.CollectionRepository
+ AccessCtrl access.Controller
+ AnonUsersRepo *socialrepo.AnonUsersRepository
+}
+
+// UnifiedDiffRequest describes paging parameters for the social diff.
+type UnifiedDiffRequest struct {
+ Actor Actor
+ CollectionID int64
+ CommentsSince int64
+ ReactionsSince int64
+ Limit int
+ FileID *int64
+ RequireAccess bool
+}
+
+// CollectionCount summarizes activity for a collection.
+type CollectionCount struct {
+ CollectionID int64 `json:"collectionID"`
+ Comments int64 `json:"comments"`
+ Reactions int64 `json:"reactions"`
+}
+
+// CollectionLatestUpdate captures the latest activity timestamps per collection.
+type CollectionLatestUpdate struct {
+ CollectionID int64 `json:"collectionID"`
+ CommentsUpdatedAt *int64 `json:"commentsUpdatedAt,omitempty"`
+ ReactionsUpdatedAt *int64 `json:"reactionsUpdatedAt,omitempty"`
+ AnonProfilesUpdatedAt *int64 `json:"anonProfilesUpdatedAt,omitempty"`
+}
+
+// AnonProfilesRequest describes the parameters for listing anonymous profiles.
+type AnonProfilesRequest struct {
+ Actor Actor
+ CollectionID int64
+ RequireAccess bool
+}
+
+// UnifiedDiff returns comments and reactions snapshots side by side.
+func (c *Controller) UnifiedDiff(ctx *gin.Context, req UnifiedDiffRequest) ([]socialentity.Comment, []socialentity.Reaction, bool, bool, error) {
+ if req.RequireAccess {
+ userID, hasUserID := req.Actor.UserIDValue()
+ if !hasUserID || userID <= 0 {
+ return nil, nil, false, false, ente.ErrAuthenticationRequired
+ }
+ if _, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
+ CollectionID: req.CollectionID,
+ ActorUserID: userID,
+ }); err != nil {
+ return nil, nil, false, false, stacktrace.Propagate(err, "")
+ }
+ }
+ comments, moreComments, err := c.CommentsRepo.GetDiff(ctx.Request.Context(), req.CollectionID, req.CommentsSince, req.Limit, req.FileID)
+ if err != nil {
+ return nil, nil, false, false, stacktrace.Propagate(err, "")
+ }
+ reactions, moreReactions, err := c.ReactionsRepo.GetDiff(ctx.Request.Context(), req.CollectionID, req.ReactionsSince, req.Limit, req.FileID, nil)
+ if err != nil {
+ return nil, nil, false, false, stacktrace.Propagate(err, "")
+ }
+ return comments, reactions, moreComments, moreReactions, nil
+}
+
+// CountActiveCollections returns the active counts per collection accessible to the actor.
+func (c *Controller) CountActiveCollections(ctx context.Context, userID int64) ([]CollectionCount, error) {
+ ownedMap, err := c.CollectionRepo.GetCollectionIDsOwnedByUser(userID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ shared, err := c.CollectionRepo.GetCollectionIDsSharedWithUser(userID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ collectionIDs := make([]int64, 0, len(ownedMap)+len(shared))
+ for id := range ownedMap {
+ collectionIDs = append(collectionIDs, id)
+ }
+ for _, id := range shared {
+ if _, ok := ownedMap[id]; ok {
+ continue
+ }
+ collectionIDs = append(collectionIDs, id)
+ }
+ if len(collectionIDs) == 0 {
+ return nil, nil
+ }
+ commentCounts, err := c.CommentsRepo.CountActiveByCollection(ctx, collectionIDs)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ reactionCounts, err := c.ReactionsRepo.CountActiveByCollection(ctx, collectionIDs)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ results := make([]CollectionCount, 0, len(collectionIDs))
+ sort.Slice(collectionIDs, func(i, j int) bool {
+ return collectionIDs[i] < collectionIDs[j]
+ })
+ seen := map[int64]struct{}{}
+ for _, id := range collectionIDs {
+ if _, ok := seen[id]; ok {
+ continue
+ }
+ seen[id] = struct{}{}
+ results = append(results, CollectionCount{
+ CollectionID: id,
+ Comments: commentCounts[id],
+ Reactions: reactionCounts[id],
+ })
+ }
+ return results, nil
+}
+
+// LatestUpdates returns the most recent comment/reaction timestamps for collections accessible to the user.
+func (c *Controller) LatestUpdates(ctx context.Context, userID int64, app ente.App) ([]CollectionLatestUpdate, error) {
+ ownedMap, err := c.CollectionRepo.GetCollectionIDsOwnedByUser(userID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ shared, err := c.CollectionRepo.GetCollectionIDsSharedWithUser(userID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ candidateIDs := make([]int64, 0, len(ownedMap)+len(shared))
+ for id := range ownedMap {
+ candidateIDs = append(candidateIDs, id)
+ }
+ candidateIDs = append(candidateIDs, shared...)
+ if len(candidateIDs) == 0 {
+ return nil, nil
+ }
+ collectionIDs, err := c.CollectionRepo.FilterNonDeletedCollectionIDs(candidateIDs, app)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if len(collectionIDs) == 0 {
+ return nil, nil
+ }
+
+ commentUpdates, err := c.CommentsRepo.LatestUpdateByCollection(ctx, collectionIDs)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ reactionUpdates, err := c.ReactionsRepo.LatestUpdateByCollection(ctx, collectionIDs)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ anonUpdates := map[int64]int64{}
+ if c.AnonUsersRepo != nil {
+ anonUpdates, err = c.AnonUsersRepo.LatestUpdateByCollection(ctx, collectionIDs)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ }
+
+ activityMap := make(map[int64]*CollectionLatestUpdate)
+ assignComment := func(collectionID int64, updatedAt int64) {
+ entry, ok := activityMap[collectionID]
+ if !ok {
+ entry = &CollectionLatestUpdate{CollectionID: collectionID}
+ activityMap[collectionID] = entry
+ }
+ ts := updatedAt
+ entry.CommentsUpdatedAt = &ts
+ }
+ assignReaction := func(collectionID int64, updatedAt int64) {
+ entry, ok := activityMap[collectionID]
+ if !ok {
+ entry = &CollectionLatestUpdate{CollectionID: collectionID}
+ activityMap[collectionID] = entry
+ }
+ ts := updatedAt
+ entry.ReactionsUpdatedAt = &ts
+ }
+ assignAnon := func(collectionID int64, updatedAt int64) {
+ entry, ok := activityMap[collectionID]
+ if !ok {
+ entry = &CollectionLatestUpdate{CollectionID: collectionID}
+ activityMap[collectionID] = entry
+ }
+ ts := updatedAt
+ entry.AnonProfilesUpdatedAt = &ts
+ }
+
+ for id, ts := range commentUpdates {
+ assignComment(id, ts)
+ }
+ for id, ts := range reactionUpdates {
+ assignReaction(id, ts)
+ }
+ for id, ts := range anonUpdates {
+ assignAnon(id, ts)
+ }
+ if len(activityMap) == 0 {
+ return nil, nil
+ }
+
+ ids := make([]int64, 0, len(activityMap))
+ for id := range activityMap {
+ ids = append(ids, id)
+ }
+ sort.Slice(ids, func(i, j int) bool {
+ return ids[i] < ids[j]
+ })
+
+ results := make([]CollectionLatestUpdate, 0, len(activityMap))
+ for _, id := range ids {
+ results = append(results, *activityMap[id])
+ }
+ return results, nil
+}
+
+// ListAnonProfiles returns encrypted anonymous profiles for a collection when allowed.
+func (c *Controller) ListAnonProfiles(ctx *gin.Context, req AnonProfilesRequest) ([]socialentity.AnonUser, error) {
+ if req.RequireAccess {
+ userID, hasUserID := req.Actor.UserIDValue()
+ if !hasUserID || userID <= 0 {
+ return nil, ente.ErrAuthenticationRequired
+ }
+ if _, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
+ CollectionID: req.CollectionID,
+ ActorUserID: userID,
+ }); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ }
+ return c.AnonUsersRepo.ListByCollection(ctx.Request.Context(), req.CollectionID)
+}
+
diff --git a/server/pkg/controller/social/id_helper.go b/server/pkg/controller/social/id_helper.go
new file mode 100644
index 0000000000..e476758f87
--- /dev/null
+++ b/server/pkg/controller/social/id_helper.go
@@ -0,0 +1,46 @@
+package social
+
+import (
+ "strings"
+
+ "github.com/ente-io/museum/ente"
+ gonanoid "github.com/matoous/go-nanoid/v2"
+)
+
+const (
+ commentIDPrefix = "cmt_"
+ reactionIDPrefix = "rct_"
+ anonIDPrefix = "anon_"
+ nanoidSuffixLength = 21
+)
+
+// NormalizeCommentID optionally generates or validates a comment ID.
+func NormalizeCommentID(id string) (string, error) {
+ return normalizeOrGenerateID(commentIDPrefix, id)
+}
+
+// NormalizeReactionID optionally generates or validates a reaction ID.
+func NormalizeReactionID(id string) (string, error) {
+ return normalizeOrGenerateID(reactionIDPrefix, id)
+}
+
+func normalizeOrGenerateID(prefix, id string) (string, error) {
+ if id == "" {
+ return generatePrefixedID(prefix)
+ }
+ if !strings.HasPrefix(id, prefix) {
+ return "", ente.ErrBadRequest
+ }
+ if len(id) != len(prefix)+nanoidSuffixLength {
+ return "", ente.ErrBadRequest
+ }
+ return id, nil
+}
+
+func generatePrefixedID(prefix string) (string, error) {
+ random, err := gonanoid.New(nanoidSuffixLength)
+ if err != nil {
+ return "", err
+ }
+ return prefix + random, nil
+}
diff --git a/server/pkg/controller/social/reactions_controller.go b/server/pkg/controller/social/reactions_controller.go
new file mode 100644
index 0000000000..a2969b7d64
--- /dev/null
+++ b/server/pkg/controller/social/reactions_controller.go
@@ -0,0 +1,191 @@
+package social
+
+import (
+ "github.com/ente-io/museum/ente"
+ socialentity "github.com/ente-io/museum/ente/social"
+ "github.com/ente-io/museum/pkg/controller/access"
+ socialrepo "github.com/ente-io/museum/pkg/repo/social"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+)
+
+// ReactionsController orchestrates reactions operations.
+type ReactionsController struct {
+ Repo *socialrepo.ReactionsRepository
+ CommentsRepo *socialrepo.CommentsRepository
+ AccessCtrl access.Controller
+}
+
+// UpsertReactionRequest holds the payload for creating or updating a reaction.
+type UpsertReactionRequest struct {
+ Actor Actor
+ ID string
+ CollectionID int64
+ FileID *int64
+ CommentID *string
+ Cipher string
+ Nonce string
+ RequireAccess bool
+}
+
+// ReactionDiffRequest describes paging for reactions.
+type ReactionDiffRequest struct {
+ Actor Actor
+ CollectionID int64
+ Since int64
+ Limit int
+ FileID *int64
+ CommentID *string
+ RequireAccess bool
+}
+
+// ReactionDeleteRequest contains parameters to remove a reaction.
+type ReactionDeleteRequest struct {
+ Actor Actor
+ ReactionID string
+ RequireAccess bool
+}
+
+// Upsert creates or updates a reaction entry.
+func (c *ReactionsController) Upsert(ctx *gin.Context, req UpsertReactionRequest) (string, error) {
+ var err error
+ req.ID, err = NormalizeReactionID(req.ID)
+ if err != nil {
+ return "", stacktrace.Propagate(err, "")
+ }
+ if len(req.Cipher) == 0 || len(req.Nonce) == 0 {
+ return "", ente.ErrBadRequest
+ }
+ userID, hasUserID := req.Actor.UserIDValue()
+ if req.RequireAccess && req.Actor.IsAnonymous() {
+ return "", ente.ErrAuthenticationRequired
+ }
+ if req.Actor.IsAnonymous() {
+ if err := req.Actor.ValidateAnon(); err != nil {
+ return "", err
+ }
+ } else if !hasUserID || userID <= 0 {
+ return "", ente.ErrAuthenticationRequired
+ }
+ if req.RequireAccess {
+ if _, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
+ CollectionID: req.CollectionID,
+ ActorUserID: userID,
+ }); err != nil {
+ return "", stacktrace.Propagate(err, "")
+ }
+ }
+
+ var targetComment *socialentity.Comment
+ if req.CommentID != nil {
+ targetComment, err = c.CommentsRepo.GetByID(ctx.Request.Context(), *req.CommentID)
+ if err != nil {
+ return "", stacktrace.Propagate(err, "")
+ }
+ if targetComment.CollectionID != req.CollectionID {
+ return "", stacktrace.Propagate(ente.ErrBadRequest, "reaction commentID belongs to a different collection")
+ }
+ if targetComment.IsDeleted {
+ return "", stacktrace.Propagate(ente.ErrBadRequest, "cannot react to a deleted comment")
+ }
+ if err := validateCommentReactionContext(targetComment, req.FileID); err != nil {
+ return "", err
+ }
+ }
+
+ reaction := socialentity.Reaction{
+ ID: req.ID,
+ CollectionID: req.CollectionID,
+ FileID: req.FileID,
+ CommentID: req.CommentID,
+ Cipher: req.Cipher,
+ Nonce: req.Nonce,
+ }
+ if req.Actor.IsAnonymous() {
+ reaction.UserID = -1
+ reaction.AnonUserID = req.Actor.AnonUserID
+ } else {
+ reaction.UserID = userID
+ }
+ if targetComment != nil {
+ // file_id must remain nil for reactions that target comments, we only use the request
+ // file_id to validate that the caller has consistent context.
+ reaction.FileID = nil
+ }
+ id, err := c.Repo.Upsert(ctx.Request.Context(), reaction)
+ if err != nil {
+ return "", stacktrace.Propagate(err, "")
+ }
+ return id, nil
+}
+
+// Diff returns reaction windows for the provided scope.
+func (c *ReactionsController) Diff(ctx *gin.Context, req ReactionDiffRequest) ([]socialentity.Reaction, bool, error) {
+ userID, hasUserID := req.Actor.UserIDValue()
+ if req.RequireAccess {
+ if !hasUserID || userID <= 0 {
+ return nil, false, ente.ErrAuthenticationRequired
+ }
+ if _, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
+ CollectionID: req.CollectionID,
+ ActorUserID: userID,
+ }); err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+ }
+ return c.Repo.GetDiff(ctx.Request.Context(), req.CollectionID, req.Since, req.Limit, req.FileID, req.CommentID)
+}
+
+// Delete removes a reaction if the actor owns it.
+func (c *ReactionsController) Delete(ctx *gin.Context, req ReactionDeleteRequest) error {
+ userID, hasUserID := req.Actor.UserIDValue()
+ reaction, err := c.Repo.GetByID(ctx.Request.Context(), req.ReactionID)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if req.Actor.IsAnonymous() {
+ if err := req.Actor.ValidateAnon(); err != nil {
+ return err
+ }
+ if reaction.AnonUserID == nil || req.Actor.AnonUserID == nil || *reaction.AnonUserID != *req.Actor.AnonUserID {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "")
+ }
+ } else if !hasUserID || reaction.UserID != userID {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "")
+ }
+ if req.RequireAccess {
+ if !hasUserID || userID <= 0 {
+ return ente.ErrAuthenticationRequired
+ }
+ if _, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
+ CollectionID: reaction.CollectionID,
+ ActorUserID: userID,
+ }); err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ }
+ repoUserID := int64(-1)
+ if hasUserID {
+ repoUserID = userID
+ }
+ return c.Repo.SoftDeleteByID(ctx.Request.Context(), req.ReactionID, repoUserID, req.Actor.AnonUserID)
+}
+
+func validateCommentReactionContext(comment *socialentity.Comment, requestedFileID *int64) error {
+ if comment == nil {
+ return nil
+ }
+ if comment.FileID != nil {
+ switch {
+ case requestedFileID == nil:
+ return stacktrace.Propagate(ente.ErrBadRequest, "fileID is required when reacting to a file-scoped comment")
+ case *requestedFileID != *comment.FileID:
+ return stacktrace.Propagate(ente.ErrBadRequest, "fileID must match the target comment's fileID")
+ }
+ return nil
+ }
+ if requestedFileID != nil {
+ return stacktrace.Propagate(ente.ErrBadRequest, "fileID must be omitted when reacting to a collection-level comment")
+ }
+ return nil
+}
diff --git a/server/pkg/controller/usage.go b/server/pkg/controller/usage.go
index bc2de2966a..9b5f2131d2 100644
--- a/server/pkg/controller/usage.go
+++ b/server/pkg/controller/usage.go
@@ -124,6 +124,9 @@ func (c *UsageController) canUploadFile(ctx context.Context, userID int64, size
return stacktrace.Propagate(ente.ErrStorageLimitExceeded,
fmt.Sprintf("locker storage limit exceeded (limit %d, usage %d)", maxStorage, projectedLockerUsage))
}
+
+ // Locker uploads should not be blocked by Photos subscription limits.
+ return nil
}
var subStorage int64
diff --git a/server/pkg/middleware/collection_link.go b/server/pkg/middleware/collection_link.go
index 3ab7bccb14..e4d3f0ba34 100644
--- a/server/pkg/middleware/collection_link.go
+++ b/server/pkg/middleware/collection_link.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/sha256"
+ "database/sql"
"errors"
"fmt"
"golang.org/x/net/idna"
@@ -17,6 +18,7 @@ import (
public2 "github.com/ente-io/museum/pkg/controller/public"
"github.com/ente-io/museum/pkg/repo/public"
+ socialrepo "github.com/ente-io/museum/pkg/repo/social"
"github.com/ente-io/museum/ente"
"github.com/ente-io/museum/pkg/controller"
@@ -39,10 +41,12 @@ type CollectionLinkMiddleware struct {
CollectionLinkRepo *public.CollectionLinkRepo
PublicCollectionCtrl *public2.CollectionLinkController
CollectionRepo *repo.CollectionRepository
+ AnonUsersRepo *socialrepo.AnonUsersRepository
Cache *cache.Cache
BillingCtrl *controller.BillingController
DiscordController *discord.DiscordController
RemoteStoreRepo *remotestore.Repository
+ AnonIdentitySecret []byte
}
// Authenticate returns a middle ware that extracts the `X-Auth-Access-Token`
@@ -119,15 +123,32 @@ func (m *CollectionLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context
m.Cache.Set(cacheKey, publicCollectionSummary, cache.DefaultExpiration)
}
- c.Set(auth.PublicAccessKey, ente.PublicAccessContext{
+ publicCtx := ente.PublicAccessContext{
ID: publicCollectionSummary.ID,
IP: clientIP,
UserAgent: userAgent,
CollectionID: publicCollectionSummary.CollectionID,
- })
+ }
+ c.Set(auth.PublicAccessKey, publicCtx)
+
+ if err := m.attachAnonIdentity(c, publicCtx.CollectionID); err != nil {
+ status := http.StatusInternalServerError
+ switch {
+ case errors.Is(err, ente.ErrAuthenticationRequired):
+ status = http.StatusUnauthorized
+ case errors.Is(err, ente.ErrPermissionDenied):
+ status = http.StatusForbidden
+ case errors.Is(err, ente.ErrBadRequest):
+ status = http.StatusBadRequest
+ }
+ c.AbortWithStatusJSON(status, gin.H{"error": err.Error()})
+ return
+ }
+
c.Next()
}
}
+
// validateOwnersSubscription checks if the owner has an active subscription.
// Returns (isFreeUser, error) where isFreeUser is true if user is on free plan but has active subscription.
func (m *CollectionLinkMiddleware) validateOwnersSubscription(c *gin.Context, cID int64) (bool, error) {
@@ -260,6 +281,38 @@ func (m *CollectionLinkMiddleware) validateOrigin(c *gin.Context, ownerID int64)
return nil
}
+func (m *CollectionLinkMiddleware) attachAnonIdentity(c *gin.Context, collectionID int64) error {
+ if len(m.AnonIdentitySecret) == 0 {
+ return nil
+ }
+ token := strings.TrimSpace(c.GetHeader("X-Anon-User-Token"))
+ if token == "" {
+ return nil
+ }
+ claim, err := ente.ParseAnonymousIdentityToken(m.AnonIdentitySecret, token)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ anonID := claim.Subject
+ if anonID == "" {
+ return ente.ErrAuthenticationRequired
+ }
+ if m.AnonUsersRepo != nil {
+ anonUser, err := m.AnonUsersRepo.GetByID(c.Request.Context(), anonID)
+ if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return ente.ErrAuthenticationRequired
+ }
+ return stacktrace.Propagate(err, "")
+ }
+ if anonUser.CollectionID != collectionID {
+ return ente.ErrPermissionDenied
+ }
+ }
+ auth.SetPublicAnonUserID(c, anonID)
+ return nil
+}
+
func computeHashKeyForList(list []string, delim string) string {
var buffer bytes.Buffer
for i := range list {
diff --git a/server/pkg/middleware/rate_limit.go b/server/pkg/middleware/rate_limit.go
index 609c0d06b1..46042b884e 100644
--- a/server/pkg/middleware/rate_limit.go
+++ b/server/pkg/middleware/rate_limit.go
@@ -157,5 +157,13 @@ func (r *RateLimitMiddleware) getLimiter(reqPath string, reqMethod string) *limi
} else if reqPath == "/files/preview" {
return r.limit200ReqPerSec
}
+ if reqPath == "/public-collection/anon-identity" {
+ return r.limit10ReqPerMin
+ }
+ if (strings.HasPrefix(reqPath, "/public-collection/comments") ||
+ strings.HasPrefix(reqPath, "/public-collection/reactions")) &&
+ (reqMethod == http.MethodPost || reqMethod == http.MethodPut || reqMethod == http.MethodDelete) {
+ return r.limit200ReqPerMin
+ }
return nil
}
diff --git a/server/pkg/repo/collection.go b/server/pkg/repo/collection.go
index e1003899c9..ac3b782d99 100644
--- a/server/pkg/repo/collection.go
+++ b/server/pkg/repo/collection.go
@@ -372,6 +372,37 @@ func (repo *CollectionRepository) GetCollectionIDsSharedWithUser(userID int64) (
return cIDs, nil
}
+// FilterNonDeletedCollectionIDs returns collection IDs that are not deleted and match the provided app.
+func (repo *CollectionRepository) FilterNonDeletedCollectionIDs(collectionIDs []int64, app ente.App) ([]int64, error) {
+ if len(collectionIDs) == 0 {
+ return nil, nil
+ }
+ rows, err := repo.DB.Query(`
+ SELECT collection_id
+ FROM collections
+ WHERE collection_id = ANY($1)
+ AND is_deleted = FALSE
+ AND app = $2
+ `, pq.Array(collectionIDs), app)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+
+ result := make([]int64, 0, len(collectionIDs))
+ for rows.Next() {
+ var collectionID int64
+ if err := rows.Scan(&collectionID); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ result = append(result, collectionID)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return result, nil
+}
+
func (repo *CollectionRepository) GetCollectionsSharedWithOrByUser(userID int64) ([]int64, error) {
rows, err := repo.DB.Query(`
SELECT collection_id
diff --git a/server/pkg/repo/social/anon_users.go b/server/pkg/repo/social/anon_users.go
new file mode 100644
index 0000000000..fdbb2ed3e3
--- /dev/null
+++ b/server/pkg/repo/social/anon_users.go
@@ -0,0 +1,114 @@
+package social
+
+import (
+ "context"
+ "database/sql"
+
+ socialentity "github.com/ente-io/museum/ente/social"
+ "github.com/ente-io/stacktrace"
+ "github.com/lib/pq"
+)
+
+// AnonUsersRepository manages anonymous user profiles tied to public collections.
+type AnonUsersRepository struct {
+ DB *sql.DB
+}
+
+func (r *AnonUsersRepository) Insert(ctx context.Context, user socialentity.AnonUser) error {
+ _, err := r.DB.ExecContext(ctx, `
+ INSERT INTO anon_users (id, collection_id, cipher, nonce)
+ VALUES ($1, $2, $3, $4)
+ `,
+ user.ID,
+ user.CollectionID,
+ user.Cipher,
+ user.Nonce,
+ )
+ return stacktrace.Propagate(err, "")
+}
+
+func (r *AnonUsersRepository) GetByID(ctx context.Context, id string) (*socialentity.AnonUser, error) {
+ anon := &socialentity.AnonUser{}
+ err := r.DB.QueryRowContext(ctx, `
+ SELECT id, collection_id, cipher, nonce, created_at, updated_at
+ FROM anon_users
+ WHERE id = $1
+ `, id).Scan(
+ &anon.ID,
+ &anon.CollectionID,
+ &anon.Cipher,
+ &anon.Nonce,
+ &anon.CreatedAt,
+ &anon.UpdatedAt,
+ )
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return anon, nil
+}
+
+func (r *AnonUsersRepository) ListByCollection(ctx context.Context, collectionID int64) ([]socialentity.AnonUser, error) {
+ rows, err := r.DB.QueryContext(ctx, `
+ SELECT id, collection_id, cipher, nonce, created_at, updated_at
+ FROM anon_users
+ WHERE collection_id = $1
+ ORDER BY created_at ASC
+ `, collectionID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+
+ var result []socialentity.AnonUser
+ for rows.Next() {
+ var anon socialentity.AnonUser
+ if err := rows.Scan(
+ &anon.ID,
+ &anon.CollectionID,
+ &anon.Cipher,
+ &anon.Nonce,
+ &anon.CreatedAt,
+ &anon.UpdatedAt,
+ ); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ result = append(result, anon)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return result, nil
+}
+
+// LatestUpdateByCollection returns the most recent updated_at timestamp per collection.
+func (r *AnonUsersRepository) LatestUpdateByCollection(ctx context.Context, collectionIDs []int64) (map[int64]int64, error) {
+ results := make(map[int64]int64)
+ if len(collectionIDs) == 0 {
+ return results, nil
+ }
+ rows, err := r.DB.QueryContext(ctx, `
+ SELECT collection_id, MAX(updated_at)
+ FROM anon_users
+ WHERE collection_id = ANY($1)
+ GROUP BY collection_id
+ `, pq.Array(collectionIDs))
+ if err != nil {
+ return results, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var (
+ collectionID int64
+ updatedAt int64
+ )
+ if err := rows.Scan(&collectionID, &updatedAt); err != nil {
+ return results, stacktrace.Propagate(err, "")
+ }
+ results[collectionID] = updatedAt
+ }
+ if err := rows.Err(); err != nil {
+ return results, stacktrace.Propagate(err, "")
+ }
+ return results, nil
+}
diff --git a/server/pkg/repo/social/comments.go b/server/pkg/repo/social/comments.go
new file mode 100644
index 0000000000..915809bc03
--- /dev/null
+++ b/server/pkg/repo/social/comments.go
@@ -0,0 +1,393 @@
+package social
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/ente-io/museum/ente"
+ socialentity "github.com/ente-io/museum/ente/social"
+ "github.com/ente-io/stacktrace"
+ "github.com/lib/pq"
+)
+
+// CommentsRepository manages comment records.
+type CommentsRepository struct {
+ DB *sql.DB
+}
+
+func (repo *CommentsRepository) Insert(ctx context.Context, comment socialentity.Comment) error {
+ _, err := repo.DB.ExecContext(ctx, `
+ INSERT INTO comments (id, collection_id, file_id, parent_comment_id, user_id, anon_user_id, cipher, nonce, is_deleted)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
+ `,
+ comment.ID,
+ comment.CollectionID,
+ comment.FileID,
+ comment.ParentCommentID,
+ comment.UserID,
+ comment.AnonUserID,
+ comment.Cipher,
+ comment.Nonce,
+ false,
+ )
+ return stacktrace.Propagate(err, "")
+}
+
+func (repo *CommentsRepository) UpdateCipher(ctx context.Context, id string, cipher string, nonce string) error {
+ result, err := repo.DB.ExecContext(ctx, `
+ UPDATE comments
+ SET cipher = $1,
+ nonce = $2,
+ updated_at = now_utc_micro_seconds()
+ WHERE id = $3
+ AND is_deleted = FALSE
+ `, cipher, nonce, id)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ rows, err := result.RowsAffected()
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if rows == 0 {
+ return stacktrace.Propagate(ente.ErrNotFound, "")
+ }
+ return nil
+}
+
+func (repo *CommentsRepository) SoftDelete(ctx context.Context, id string) error {
+ result, err := repo.DB.ExecContext(ctx, `
+ UPDATE comments
+ SET is_deleted = TRUE,
+ cipher = NULL,
+ nonce = NULL,
+ updated_at = now_utc_micro_seconds()
+ WHERE id = $1
+ AND is_deleted = FALSE
+ `, id)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ rows, err := result.RowsAffected()
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if rows == 0 {
+ return stacktrace.Propagate(ente.ErrNotFound, "")
+ }
+ return nil
+}
+
+// SoftDeleteByCollectionAndUser removes all comments created by a user inside a collection.
+func (repo *CommentsRepository) SoftDeleteByCollectionAndUser(ctx context.Context, collectionID int64, userID int64) error {
+ _, err := repo.DB.ExecContext(ctx, `
+ UPDATE comments
+ SET is_deleted = TRUE,
+ cipher = NULL,
+ nonce = NULL,
+ updated_at = now_utc_micro_seconds()
+ WHERE collection_id = $1
+ AND user_id = $2
+ AND is_deleted = FALSE
+ `, collectionID, userID)
+ return stacktrace.Propagate(err, "")
+}
+
+func (repo *CommentsRepository) GetByID(ctx context.Context, id string) (*socialentity.Comment, error) {
+ var (
+ fileID sql.NullInt64
+ parent sql.NullString
+ anon sql.NullString
+ cipher sql.NullString
+ nonce sql.NullString
+ )
+ comment := &socialentity.Comment{}
+ err := repo.DB.QueryRowContext(ctx, `
+ SELECT id, collection_id, file_id, parent_comment_id, user_id, anon_user_id, cipher, nonce, is_deleted, created_at, updated_at
+ FROM comments
+ WHERE id = $1
+ `, id).Scan(
+ &comment.ID,
+ &comment.CollectionID,
+ &fileID,
+ &parent,
+ &comment.UserID,
+ &anon,
+ &cipher,
+ &nonce,
+ &comment.IsDeleted,
+ &comment.CreatedAt,
+ &comment.UpdatedAt,
+ )
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if fileID.Valid {
+ comment.FileID = &fileID.Int64
+ }
+ if parent.Valid {
+ comment.ParentCommentID = &parent.String
+ }
+ if anon.Valid {
+ comment.AnonUserID = &anon.String
+ }
+ if cipher.Valid {
+ comment.Cipher = cipher.String
+ }
+ if nonce.Valid {
+ comment.Nonce = nonce.String
+ }
+ return comment, nil
+}
+
+func (repo *CommentsRepository) GetDiff(ctx context.Context, collectionID int64, since int64, limit int, fileID *int64) ([]socialentity.Comment, bool, error) {
+ query := `
+ SELECT id, collection_id, file_id, parent_comment_id, user_id, anon_user_id, cipher, nonce, is_deleted, created_at, updated_at
+ FROM comments
+ WHERE collection_id = $1
+ AND updated_at > $2
+ AND ($3::BIGINT IS NULL OR file_id IS NOT DISTINCT FROM $3::BIGINT)
+ ORDER BY updated_at ASC
+ LIMIT $4
+ `
+ rows, err := repo.DB.QueryContext(ctx, query, collectionID, since, fileID, limit+1)
+ if err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+
+ comments := make([]socialentity.Comment, 0, limit+1)
+ for rows.Next() {
+ var (
+ file sql.NullInt64
+ parent sql.NullString
+ anon sql.NullString
+ cipher sql.NullString
+ nonce sql.NullString
+ comment socialentity.Comment
+ )
+ if err := rows.Scan(
+ &comment.ID,
+ &comment.CollectionID,
+ &file,
+ &parent,
+ &comment.UserID,
+ &anon,
+ &cipher,
+ &nonce,
+ &comment.IsDeleted,
+ &comment.CreatedAt,
+ &comment.UpdatedAt,
+ ); err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+ if file.Valid {
+ comment.FileID = &file.Int64
+ }
+ if parent.Valid {
+ comment.ParentCommentID = &parent.String
+ }
+ if anon.Valid {
+ comment.AnonUserID = &anon.String
+ }
+ if cipher.Valid {
+ comment.Cipher = cipher.String
+ }
+ if nonce.Valid {
+ comment.Nonce = nonce.String
+ }
+ comments = append(comments, comment)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+
+ hasMore := false
+ if len(comments) > limit {
+ hasMore = true
+ comments = comments[:limit]
+ }
+ return comments, hasMore, nil
+}
+
+func (repo *CommentsRepository) CountActiveByCollection(ctx context.Context, collectionIDs []int64) (map[int64]int64, error) {
+ counts := make(map[int64]int64)
+ if len(collectionIDs) == 0 {
+ return counts, nil
+ }
+ rows, err := repo.DB.QueryContext(ctx, `
+ SELECT collection_id, COUNT(*)
+ FROM comments
+ WHERE collection_id = ANY($1)
+ AND is_deleted = FALSE
+ GROUP BY collection_id
+ `, pq.Array(collectionIDs))
+ if err != nil {
+ return counts, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var collectionID int64
+ var count int64
+ if err := rows.Scan(&collectionID, &count); err != nil {
+ return counts, stacktrace.Propagate(err, "")
+ }
+ counts[collectionID] = count
+ }
+ if err := rows.Err(); err != nil {
+ return counts, stacktrace.Propagate(err, "")
+ }
+ return counts, nil
+}
+
+// LatestUpdateByCollection returns the most recent updated_at timestamp for each collection.
+func (repo *CommentsRepository) LatestUpdateByCollection(ctx context.Context, collectionIDs []int64) (map[int64]int64, error) {
+ results := make(map[int64]int64)
+ if len(collectionIDs) == 0 {
+ return results, nil
+ }
+ rows, err := repo.DB.QueryContext(ctx, `
+ SELECT collection_id, MAX(updated_at)
+ FROM comments
+ WHERE collection_id = ANY($1)
+ GROUP BY collection_id
+ `, pq.Array(collectionIDs))
+ if err != nil {
+ return results, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var (
+ collectionID int64
+ updatedAt int64
+ )
+ if err := rows.Scan(&collectionID, &updatedAt); err != nil {
+ return results, stacktrace.Propagate(err, "")
+ }
+ results[collectionID] = updatedAt
+ }
+ if err := rows.Err(); err != nil {
+ return results, stacktrace.Propagate(err, "")
+ }
+ return results, nil
+}
+
+func (repo *CommentsRepository) GetActiveUserIDs(ctx context.Context, collectionID int64) ([]int64, error) {
+ rows, err := repo.DB.QueryContext(ctx, `
+ SELECT DISTINCT user_id
+ FROM comments
+ WHERE collection_id = $1
+ AND user_id > 0
+ AND is_deleted = FALSE
+ `, collectionID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+ ids := make([]int64, 0)
+ for rows.Next() {
+ var id int64
+ if err := rows.Scan(&id); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ ids = append(ids, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return ids, nil
+}
+
+// GetAlbumFeedComments returns comments relevant to the feed for a user:
+// 1. Comments on files owned by the user (excluding user's own comments)
+// 2. Replies to user's comments
+func (repo *CommentsRepository) GetAlbumFeedComments(ctx context.Context, collectionID int64, userID int64, since int64, limit int) ([]socialentity.Comment, bool, error) {
+ query := `
+ SELECT c.id, c.collection_id, c.file_id, c.parent_comment_id, p.user_id AS parent_comment_user_id,
+ c.user_id, c.anon_user_id, c.cipher, c.nonce, c.is_deleted, c.created_at, c.updated_at
+ FROM comments c
+ LEFT JOIN comments p ON c.parent_comment_id = p.id
+ WHERE c.collection_id = $1
+ AND c.updated_at > $2
+ AND c.is_deleted = FALSE
+ AND c.user_id != $3
+ AND (
+ -- Comments on files owned by the user
+ c.file_id IN (
+ SELECT file_id FROM collection_files
+ WHERE collection_id = $1 AND f_owner_id = $3 AND is_deleted = FALSE
+ )
+ OR
+ -- Replies to user's comments (including replies to replies)
+ c.parent_comment_id IN (
+ SELECT id FROM comments WHERE collection_id = $1 AND user_id = $3
+ )
+ )
+ ORDER BY c.updated_at DESC
+ LIMIT $4
+ `
+ rows, err := repo.DB.QueryContext(ctx, query, collectionID, since, userID, limit+1)
+ if err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+
+ comments := make([]socialentity.Comment, 0, limit+1)
+ for rows.Next() {
+ var (
+ file sql.NullInt64
+ parent sql.NullString
+ parentUserID sql.NullInt64
+ anon sql.NullString
+ cipher sql.NullString
+ nonce sql.NullString
+ comment socialentity.Comment
+ )
+ if err := rows.Scan(
+ &comment.ID,
+ &comment.CollectionID,
+ &file,
+ &parent,
+ &parentUserID,
+ &comment.UserID,
+ &anon,
+ &cipher,
+ &nonce,
+ &comment.IsDeleted,
+ &comment.CreatedAt,
+ &comment.UpdatedAt,
+ ); err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+ if file.Valid {
+ comment.FileID = &file.Int64
+ }
+ if parent.Valid {
+ comment.ParentCommentID = &parent.String
+ }
+ if parentUserID.Valid {
+ comment.ParentCommentUserID = &parentUserID.Int64
+ }
+ if anon.Valid {
+ comment.AnonUserID = &anon.String
+ }
+ if cipher.Valid {
+ comment.Cipher = cipher.String
+ }
+ if nonce.Valid {
+ comment.Nonce = nonce.String
+ }
+ comments = append(comments, comment)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+
+ hasMore := false
+ if len(comments) > limit {
+ hasMore = true
+ comments = comments[:limit]
+ }
+ return comments, hasMore, nil
+}
diff --git a/server/pkg/repo/social/reactions.go b/server/pkg/repo/social/reactions.go
new file mode 100644
index 0000000000..cc5503f9b2
--- /dev/null
+++ b/server/pkg/repo/social/reactions.go
@@ -0,0 +1,312 @@
+package social
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+
+ "github.com/ente-io/museum/ente"
+ socialentity "github.com/ente-io/museum/ente/social"
+ "github.com/ente-io/stacktrace"
+ "github.com/lib/pq"
+)
+
+// ReactionsRepository manages reaction records.
+type ReactionsRepository struct {
+ DB *sql.DB
+}
+
+func (repo *ReactionsRepository) Upsert(ctx context.Context, reaction socialentity.Reaction) (string, error) {
+ var id string
+ err := repo.DB.QueryRowContext(ctx, `
+ INSERT INTO reactions (id, collection_id, file_id, comment_id, user_id, anon_user_id, cipher, nonce, is_deleted)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, FALSE)
+ ON CONFLICT (actor_key, unique_key)
+ DO UPDATE SET cipher = EXCLUDED.cipher,
+ nonce = EXCLUDED.nonce,
+ is_deleted = FALSE,
+ updated_at = now_utc_micro_seconds()
+ RETURNING id
+ `,
+ reaction.ID,
+ reaction.CollectionID,
+ reaction.FileID,
+ reaction.CommentID,
+ reaction.UserID,
+ reaction.AnonUserID,
+ reaction.Cipher,
+ reaction.Nonce,
+ ).Scan(&id)
+ if err != nil {
+ return "", stacktrace.Propagate(err, "")
+ }
+ return id, nil
+}
+
+func (repo *ReactionsRepository) SoftDeleteByID(ctx context.Context, id string, userID int64, anonUserID *string) error {
+ actorKey, err := buildActorKey(userID, anonUserID)
+ if err != nil {
+ return err
+ }
+ result, err := repo.DB.ExecContext(ctx, `
+ UPDATE reactions
+ SET is_deleted = TRUE,
+ cipher = NULL,
+ nonce = NULL,
+ updated_at = now_utc_micro_seconds()
+ WHERE id = $1
+ AND actor_key = $2
+ `, id, actorKey)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ rows, err := result.RowsAffected()
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ if rows == 0 {
+ return stacktrace.Propagate(ente.ErrNotFound, "")
+ }
+ return nil
+}
+
+// SoftDeleteByCollectionAndUser removes all reactions created by a user inside a collection.
+func (repo *ReactionsRepository) SoftDeleteByCollectionAndUser(ctx context.Context, collectionID int64, userID int64) error {
+ _, err := repo.DB.ExecContext(ctx, `
+ UPDATE reactions
+ SET is_deleted = TRUE,
+ cipher = NULL,
+ nonce = NULL,
+ updated_at = now_utc_micro_seconds()
+ WHERE collection_id = $1
+ AND user_id = $2
+ AND is_deleted = FALSE
+ `, collectionID, userID)
+ return stacktrace.Propagate(err, "")
+}
+
+func (repo *ReactionsRepository) GetByID(ctx context.Context, id string) (*socialentity.Reaction, error) {
+ var (
+ file sql.NullInt64
+ comment sql.NullString
+ anon sql.NullString
+ cipher sql.NullString
+ nonce sql.NullString
+ )
+ reaction := &socialentity.Reaction{}
+ err := repo.DB.QueryRowContext(ctx, `
+ SELECT id, collection_id, file_id, comment_id, user_id, anon_user_id, cipher, nonce, is_deleted, created_at, updated_at
+ FROM reactions
+ WHERE id = $1
+ `, id).Scan(
+ &reaction.ID,
+ &reaction.CollectionID,
+ &file,
+ &comment,
+ &reaction.UserID,
+ &anon,
+ &cipher,
+ &nonce,
+ &reaction.IsDeleted,
+ &reaction.CreatedAt,
+ &reaction.UpdatedAt,
+ )
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ if file.Valid {
+ reaction.FileID = &file.Int64
+ }
+ if comment.Valid {
+ reaction.CommentID = &comment.String
+ }
+ if anon.Valid {
+ reaction.AnonUserID = &anon.String
+ }
+ if cipher.Valid {
+ reaction.Cipher = cipher.String
+ }
+ if nonce.Valid {
+ reaction.Nonce = nonce.String
+ }
+ return reaction, nil
+}
+
+func (repo *ReactionsRepository) GetDiff(ctx context.Context, collectionID int64, since int64, limit int, fileID *int64, commentID *string) ([]socialentity.Reaction, bool, error) {
+ query := `
+ SELECT id, collection_id, file_id, comment_id, user_id, anon_user_id, cipher, nonce, is_deleted, created_at, updated_at
+ FROM reactions
+ WHERE collection_id = $1
+ AND updated_at > $2
+ AND (
+ $3::bigint IS NULL
+ OR file_id = $3::bigint
+ OR comment_id IN (SELECT id FROM comments WHERE collection_id = $1 AND file_id = $3::bigint)
+ )
+ AND ($4::text IS NULL OR comment_id = $4::text)
+ ORDER BY updated_at ASC
+ LIMIT $5
+ `
+ rows, err := repo.DB.QueryContext(ctx, query, collectionID, since, fileID, commentID, limit+1)
+ if err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+
+ reactions := make([]socialentity.Reaction, 0, limit+1)
+ for rows.Next() {
+ var (
+ file sql.NullInt64
+ comment sql.NullString
+ anon sql.NullString
+ cipher sql.NullString
+ nonce sql.NullString
+ reaction socialentity.Reaction
+ )
+ if err := rows.Scan(
+ &reaction.ID,
+ &reaction.CollectionID,
+ &file,
+ &comment,
+ &reaction.UserID,
+ &anon,
+ &cipher,
+ &nonce,
+ &reaction.IsDeleted,
+ &reaction.CreatedAt,
+ &reaction.UpdatedAt,
+ ); err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+ if file.Valid {
+ reaction.FileID = &file.Int64
+ }
+ if comment.Valid {
+ reaction.CommentID = &comment.String
+ }
+ if anon.Valid {
+ reaction.AnonUserID = &anon.String
+ }
+ if cipher.Valid {
+ reaction.Cipher = cipher.String
+ }
+ if nonce.Valid {
+ reaction.Nonce = nonce.String
+ }
+ reactions = append(reactions, reaction)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, false, stacktrace.Propagate(err, "")
+ }
+
+ hasMore := false
+ if len(reactions) > limit {
+ hasMore = true
+ reactions = reactions[:limit]
+ }
+ return reactions, hasMore, nil
+}
+
+func (repo *ReactionsRepository) CountActiveByCollection(ctx context.Context, collectionIDs []int64) (map[int64]int64, error) {
+ counts := make(map[int64]int64)
+ if len(collectionIDs) == 0 {
+ return counts, nil
+ }
+ rows, err := repo.DB.QueryContext(ctx, `
+ SELECT collection_id, COUNT(*)
+ FROM reactions
+ WHERE collection_id = ANY($1)
+ AND is_deleted = FALSE
+ GROUP BY collection_id
+ `, pq.Array(collectionIDs))
+ if err != nil {
+ return counts, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var collectionID int64
+ var count int64
+ if err := rows.Scan(&collectionID, &count); err != nil {
+ return counts, stacktrace.Propagate(err, "")
+ }
+ counts[collectionID] = count
+ }
+ if err := rows.Err(); err != nil {
+ return counts, stacktrace.Propagate(err, "")
+ }
+ return counts, nil
+}
+
+// LatestUpdateByCollection returns the most recent updated_at timestamp for each collection.
+func (repo *ReactionsRepository) LatestUpdateByCollection(ctx context.Context, collectionIDs []int64) (map[int64]int64, error) {
+ results := make(map[int64]int64)
+ if len(collectionIDs) == 0 {
+ return results, nil
+ }
+ rows, err := repo.DB.QueryContext(ctx, `
+ SELECT collection_id, MAX(updated_at)
+ FROM reactions
+ WHERE collection_id = ANY($1)
+ GROUP BY collection_id
+ `, pq.Array(collectionIDs))
+ if err != nil {
+ return results, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var (
+ collectionID int64
+ updatedAt int64
+ )
+ if err := rows.Scan(&collectionID, &updatedAt); err != nil {
+ return results, stacktrace.Propagate(err, "")
+ }
+ results[collectionID] = updatedAt
+ }
+ if err := rows.Err(); err != nil {
+ return results, stacktrace.Propagate(err, "")
+ }
+ return results, nil
+}
+
+func (repo *ReactionsRepository) GetActiveUserIDs(ctx context.Context, collectionID int64) ([]int64, error) {
+ rows, err := repo.DB.QueryContext(ctx, `
+ SELECT DISTINCT user_id
+ FROM reactions
+ WHERE collection_id = $1
+ AND user_id > 0
+ AND is_deleted = FALSE
+ `, collectionID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+ ids := make([]int64, 0)
+ for rows.Next() {
+ var id int64
+ if err := rows.Scan(&id); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ ids = append(ids, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return ids, nil
+}
+
+func buildActorKey(userID int64, anonUserID *string) (string, error) {
+ if userID == -1 {
+ if anonUserID == nil || *anonUserID == "" {
+ return "", stacktrace.Propagate(ente.ErrBadRequest, "missing anon user id for anonymous actor")
+ }
+ return fmt.Sprintf("A:%s", *anonUserID), nil
+ }
+ if anonUserID != nil {
+ return "", stacktrace.Propagate(ente.ErrBadRequest, "anon_user_id must be empty for authenticated actor")
+ }
+ return fmt.Sprintf("U:%d", userID), nil
+}
+
diff --git a/server/pkg/utils/auth/auth.go b/server/pkg/utils/auth/auth.go
index 8b52808e36..83cda2274c 100644
--- a/server/pkg/utils/auth/auth.go
+++ b/server/pkg/utils/auth/auth.go
@@ -18,6 +18,7 @@ import (
const (
PublicAccessKey = "X-Public-Access-ID"
+ PublicAnonUserKey = "X-Public-Anon-User-ID"
FileLinkAccessKey = "X-Public-FileLink-Access-ID"
CastContext = "X-Cast-Context"
)
@@ -135,6 +136,22 @@ func MustGetPublicAccessContext(c *gin.Context) ente.PublicAccessContext {
return c.MustGet(PublicAccessKey).(ente.PublicAccessContext)
}
+func SetPublicAnonUserID(c *gin.Context, anonID string) {
+ c.Set(PublicAnonUserKey, anonID)
+}
+
+func GetPublicAnonUserID(c *gin.Context) (*string, bool) {
+ value, ok := c.Get(PublicAnonUserKey)
+ if !ok {
+ return nil, false
+ }
+ if anonID, ok := value.(string); ok {
+ copyID := anonID
+ return &copyID, true
+ }
+ return nil, false
+}
+
func MustGetFileLinkAccessContext(c *gin.Context) *ente.FileLinkAccessContext {
return c.MustGet(FileLinkAccessKey).(*ente.FileLinkAccessContext)
}