Skip to content

armgit / ente

Public Imported from GitHub
0

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

[server] Minor fixes & api to get remove-actions

Neeraj Gupta187228c01ac6
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index 268cf18041..71b1b8366a 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -316,16 +316,16 @@ func main() {
}
collectionController := &collections.CollectionController{
- CollectionRepo: collectionRepo,
- EmailCtrl: emailNotificationCtrl,
- AccessCtrl: accessCtrl,
- CollectionLinkCtrl: collectionLinkCtrl,
- UserRepo: userRepo,
- FileRepo: fileRepo,
- CastRepo: &castDb,
- BillingCtrl: billingController,
- QueueRepo: queueRepo,
- TaskRepo: taskLockingRepo,
+ CollectionRepo: collectionRepo,
+ EmailCtrl: emailNotificationCtrl,
+ AccessCtrl: accessCtrl,
+ CollectionLinkCtrl: collectionLinkCtrl,
+ UserRepo: userRepo,
+ FileRepo: fileRepo,
+ CastRepo: &castDb,
+ BillingCtrl: billingController,
+ QueueRepo: queueRepo,
+ TaskRepo: taskLockingRepo,
CollectionActionsRepo: &repo.CollectionActionsRepository{DB: db},
}
@@ -575,9 +575,8 @@ func main() {
}
privateAPI.POST("/collections", collectionHandler.Create)
// Collection actions (exposed for clients to fetch suggestions/removals)
- privateAPI.GET("/collection-actions", collectionActionsHandler.List)
- // Backward alias
- privateAPI.GET("/pending-actions", collectionActionsHandler.List)
+ privateAPI.GET("/collection-actions/pending-remove", collectionActionsHandler.ListPendingRemove)
+
privateAPI.GET("/collections/:collectionID", collectionHandler.GetCollectionByID)
//lint:ignore SA1019 Deprecated API will be removed in the future
privateAPI.GET("/collections", collectionHandler.Get)
@@ -594,8 +593,8 @@ func main() {
privateAPI.POST("/collections/move-files", collectionHandler.MoveFiles)
privateAPI.POST("/collections/restore-files", collectionHandler.RestoreFiles)
- privateAPI.POST("/collections/v3/remove-files", collectionHandler.RemoveFilesV3)
- privateAPI.POST("/collections/suggest-delete", collectionHandler.SuggestDeleteInSharedCollection)
+ privateAPI.POST("/collections/v3/remove-files", collectionHandler.RemoveFilesV3)
+ privateAPI.POST("/collections/suggest-delete", collectionHandler.SuggestDeleteInSharedCollection)
privateAPI.GET("/collections/v2/diff", collectionHandler.GetDiffV2)
privateAPI.GET("/collections/file", collectionHandler.GetFile)
privateAPI.GET("/collections/sharees", collectionHandler.GetSharees)
diff --git a/server/ente/collection_action_constants.go b/server/ente/collection_action_constants.go
index 359cf76b57..e9dd9e35c0 100644
--- a/server/ente/collection_action_constants.go
+++ b/server/ente/collection_action_constants.go
@@ -2,8 +2,6 @@ package ente
// Collection action values used across server and clients. Stored as plain text in DB.
const (
- ActionRemove = "REMOVE"
- ActionDelete = "DELETE"
- ActionDeleteSuggested = "DELETE_SUGGESTED"
+ ActionRemove = "REMOVE"
+ ActionDeleteSuggested = "DELETE_SUGGESTED"
)
-
diff --git a/server/migrations/113_create_collection_actions.down.sql b/server/migrations/113_create_collection_actions.down.sql
index a0eadddbc0..623fe26d22 100644
--- a/server/migrations/113_create_collection_actions.down.sql
+++ b/server/migrations/113_create_collection_actions.down.sql
@@ -1,3 +1,4 @@
DROP INDEX IF EXISTS collection_actions_user_id_idx;
DROP INDEX IF EXISTS collection_actions_collection_id_idx;
+DROP INDEX IF EXISTS collection_actions_pending_remove_delete_user_time_idx;
DROP TABLE IF EXISTS collection_actions;
diff --git a/server/migrations/113_create_collection_actions.up.sql b/server/migrations/113_create_collection_actions.up.sql
index b59cf36d4e..c67d0fdaf1 100644
--- a/server/migrations/113_create_collection_actions.up.sql
+++ b/server/migrations/113_create_collection_actions.up.sql
@@ -17,3 +17,6 @@ CREATE TABLE IF NOT EXISTS collection_actions (
CREATE INDEX IF NOT EXISTS collection_actions_user_id_idx ON collection_actions (user_id);
CREATE INDEX IF NOT EXISTS collection_actions_collection_id_idx ON collection_actions (collection_id);
+CREATE INDEX IF NOT EXISTS collection_actions_pending_remove_delete_user_time_idx
+ ON collection_actions (user_id, updated_at)
+ WHERE action IN ('REMOVE', 'DELETE_SUGGESTED') AND is_pending = true;
diff --git a/server/pkg/api/collection.go b/server/pkg/api/collection.go
index db98a66e70..f1f00cb060 100644
--- a/server/pkg/api/collection.go
+++ b/server/pkg/api/collection.go
@@ -303,7 +303,8 @@ func (h *CollectionHandler) RemoveFilesV3(c *gin.Context) {
handler.Error(c, stacktrace.Propagate(ente.ErrBatchSizeTooLarge, ""))
return
}
- if err := h.Controller.RemoveFilesV3(c, request); err != nil {
+ actorUserID := auth.GetUserID(c.Request.Header)
+ if err := h.Controller.RemoveFilesV3(c, actorUserID, request); err != nil {
handler.Error(c, stacktrace.Propagate(err, ""))
return
}
@@ -313,20 +314,20 @@ func (h *CollectionHandler) RemoveFilesV3(c *gin.Context) {
// SuggestDeleteInSharedCollection allows collection owner or admins to suggest deletion
// of files owned by others in a shared collection. The request must exclude files owned by the actor.
func (h *CollectionHandler) SuggestDeleteInSharedCollection(c *gin.Context) {
- var request ente.SuggestDeleteRequest
- if err := c.ShouldBindJSON(&request); err != nil {
- handler.Error(c, stacktrace.Propagate(err, ""))
- return
- }
- if len(request.FileIDs) > DefaultMaxBatchSize {
- handler.Error(c, stacktrace.Propagate(ente.ErrBatchSizeTooLarge, ""))
- return
- }
- if err := h.Controller.SuggestDeleteInSharedCollection(c, request); err != nil {
- handler.Error(c, stacktrace.Propagate(err, ""))
- return
- }
- c.Status(http.StatusOK)
+ var request ente.SuggestDeleteRequest
+ if err := c.ShouldBindJSON(&request); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ if len(request.FileIDs) > DefaultMaxBatchSize {
+ handler.Error(c, stacktrace.Propagate(ente.ErrBatchSizeTooLarge, ""))
+ return
+ }
+ if err := h.Controller.SuggestDeleteInSharedCollection(c, request); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.Status(http.StatusOK)
}
// GetDiffV2 returns the diff within a collection since a timestamp
diff --git a/server/pkg/api/collection_actions.go b/server/pkg/api/collection_actions.go
index 321c8c7bb6..07ea7e7b87 100644
--- a/server/pkg/api/collection_actions.go
+++ b/server/pkg/api/collection_actions.go
@@ -1,31 +1,32 @@
package api
import (
- "net/http"
- "strconv"
+ "net/http"
+ "strconv"
- "github.com/ente-io/museum/pkg/controller"
- "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"
+ "github.com/ente-io/museum/pkg/controller"
+ "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"
)
type CollectionActionsHandler struct {
- Controller *controller.CollectionActionsController
+ Controller *controller.CollectionActionsController
}
-// List returns collection actions for the authenticated user since a timestamp
-func (h *CollectionActionsHandler) List(c *gin.Context) {
- userID := auth.GetUserID(c.Request.Header)
- since, _ := strconv.ParseInt(c.Query("sinceTime"), 10, 64)
- limit := 500
- actions, err := h.Controller.Repo.ListForUser(c, userID, since, limit)
- if err != nil {
- handler.Error(c, stacktrace.Propagate(err, ""))
- return
- }
- c.JSON(http.StatusOK, gin.H{
- "actions": actions,
- })
+const pendingRemoveLimit = 2000
+
+// ListPendingRemove returns pending REMOVE actions after the provided updatedAt timestamp
+func (h *CollectionActionsHandler) ListPendingRemove(c *gin.Context) {
+ userID := auth.GetUserID(c.Request.Header)
+ updatedAfter, _ := strconv.ParseInt(c.Query("updatedAt"), 10, 64)
+ actions, err := h.Controller.ListPendingRemoveActions(c, userID, updatedAfter, pendingRemoveLimit)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "actions": actions,
+ })
}
diff --git a/server/pkg/controller/collection_actions.go b/server/pkg/controller/collection_actions.go
index f73d2219e4..801a4c2527 100644
--- a/server/pkg/controller/collection_actions.go
+++ b/server/pkg/controller/collection_actions.go
@@ -1,9 +1,16 @@
package controller
import (
- "github.com/ente-io/museum/pkg/repo"
+ "context"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/pkg/repo"
)
type CollectionActionsController struct {
- Repo *repo.CollectionActionsRepository
+ Repo *repo.CollectionActionsRepository
+}
+
+func (c *CollectionActionsController) ListPendingRemoveActions(ctx context.Context, userID int64, updatedAfter int64, limit int) ([]ente.CollectionAction, error) {
+ return c.Repo.ListPendingRemoveActions(ctx, userID, updatedAfter, limit)
}
diff --git a/server/pkg/controller/collections/file_action.go b/server/pkg/controller/collections/file_action.go
index c6383a6da9..bc47cd70be 100644
--- a/server/pkg/controller/collections/file_action.go
+++ b/server/pkg/controller/collections/file_action.go
@@ -1,14 +1,13 @@
package collections
import (
- "fmt"
- "github.com/ente-io/museum/ente"
- "github.com/ente-io/museum/pkg/controller/access"
- "github.com/ente-io/museum/pkg/utils/auth"
- time "github.com/ente-io/museum/pkg/utils/time"
- "github.com/ente-io/stacktrace"
- "github.com/gin-gonic/gin"
- log "github.com/sirupsen/logrus"
+ "fmt"
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/pkg/controller/access"
+ "github.com/ente-io/museum/pkg/utils/auth"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+ log "github.com/sirupsen/logrus"
)
// AddFiles adds files to a collection
@@ -130,175 +129,144 @@ func (c *CollectionController) MoveFiles(ctx *gin.Context, req ente.MoveFilesReq
return stacktrace.Propagate(err, "") // return nil if err is nil
}
-// RemoveFilesV3 removes files from a collection as long as owner(s) of the file is different from collection owner
-func (c *CollectionController) RemoveFilesV3(ctx *gin.Context, req ente.RemoveFilesV3Request) error {
- actorUserID := auth.GetUserID(ctx.Request.Header)
- accessResp, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
- CollectionID: req.CollectionID,
- ActorUserID: actorUserID,
- VerifyOwner: false,
- })
- if err != nil {
- return stacktrace.Propagate(err, "failed to verify collection access")
- }
+// RemoveFilesV3 enforces all removal rules for shared collections:
+// 1. accessCtrl must confirm the actor participates in the collection;
+// 2. collaborators/viewers may only remove the files they added themselves;
+// 3. the collection owner may remove files added by others but never their own;
+// 4. admins can remove anyone's files, but a collection owner's files are only
+// queued for removal (REMOVE action + pending collection_action entry) so
+// the owner can act on them;
+// 5. once the validations pass, non-owner files are deleted immediately via
+// CollectionRepo.RemoveFilesV3.
+func (c *CollectionController) RemoveFilesV3(ctx *gin.Context, actorUserID int64, req ente.RemoveFilesV3Request) error {
+ accessResp, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
+ CollectionID: req.CollectionID,
+ ActorUserID: actorUserID,
+ VerifyOwner: false,
+ })
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to verify collection access")
+ }
+ collectionOwnerID := accessResp.Collection.Owner.ID
+ role := accessResp.Role
- collectionOwnerID := accessResp.Collection.Owner.ID
- role := accessResp.Role
+ // Partition fileIDs by owner
+ ownerToFilesMap, err := c.FileRepo.GetOwnerToFileIDsMap(ctx, req.FileIDs)
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to get owner to fileIDs map")
+ }
+ if err := c.isRemoveAllowed(ctx, actorUserID, collectionOwnerID, role, ownerToFilesMap); err != nil {
+ return stacktrace.Propagate(err, "file removal check failed for others")
+ }
+ filesOwnedByCollectionOwner := ownerToFilesMap[collectionOwnerID]
- // Partition fileIDs by owner
- ownerToFilesMap, err := c.FileRepo.GetOwnerToFileIDsMap(ctx, req.FileIDs)
- if err != nil {
- return stacktrace.Propagate(err, "failed to get owner to fileIDs map")
- }
- // Files owned by collection owner
- ownerOwned := ownerToFilesMap[collectionOwnerID]
- // Files owned by others (excluding owner)
- others := make([]int64, 0)
- for _, fid := range req.FileIDs {
- // If not in ownerOwned, it's others
- found := false
- for _, of := range ownerOwned {
- if of == fid { found = true; break }
- }
- if !found {
- others = append(others, fid)
- }
- }
+ // Files owned by others (excluding owner)
+ ownerFilesSet := make(map[int64]struct{}, len(filesOwnedByCollectionOwner))
+ for _, fid := range filesOwnedByCollectionOwner {
+ ownerFilesSet[fid] = struct{}{}
+ }
+ others := make([]int64, 0, len(req.FileIDs)-len(filesOwnedByCollectionOwner))
+ for _, fid := range req.FileIDs {
+ if _, found := ownerFilesSet[fid]; !found {
+ others = append(others, fid)
+ }
+ }
- // If admin is trying to remove owner's files
- if len(ownerOwned) > 0 && role != nil && *role == ente.ADMIN && actorUserID != collectionOwnerID {
- // Populate collection_files with action for owner's files
- if err := c.CollectionRepo.SuggestDelete(ctx, req.CollectionID, actorUserID, ownerOwned, "REMOVE"); err != nil {
- return stacktrace.Propagate(err, "failed to set remove action for owner's files")
- }
- // Create collection actions entries for owner to act (REMOVE) per file
- now := time.Microseconds()
- for i := range ownerOwned {
- fid := ownerOwned[i]
- _, err := c.CollectionActionsRepo.Create(ctx, collectionOwnerID, actorUserID, req.CollectionID, &fid, nil, "REMOVE", true, now)
- if err != nil {
- return stacktrace.Propagate(err, "failed to create collection action REMOVE")
- }
- }
- } else if len(ownerOwned) > 0 {
- // Otherwise enforce existing removal rules
- if err := c.isRemoveAllowed(ctx, actorUserID, collectionOwnerID, role, req.FileIDs); err != nil {
- return stacktrace.Propagate(err, "file removal check failed")
- }
- }
+ // If admin is trying to remove owner's files
+ if len(filesOwnedByCollectionOwner) > 0 {
+ if role != nil && *role == ente.ADMIN && actorUserID != collectionOwnerID {
+ // Populate collection_files with action for owner's files
+ if err := c.CollectionRepo.SuggestAction(ctx, req.CollectionID, actorUserID, filesOwnedByCollectionOwner, ente.ActionRemove); err != nil {
+ return stacktrace.Propagate(err, "failed to set remove action for owner's files")
+ }
+ if err := c.CollectionActionsRepo.CreateBulk(ctx, collectionOwnerID, actorUserID, req.CollectionID, filesOwnedByCollectionOwner, nil, ente.ActionRemove, true); err != nil {
+ return stacktrace.Propagate(err, "failed to create collection action REMOVE")
+ }
+ } else {
+ // unless client is buggy, we should never reach here.
+ return stacktrace.NewError(fmt.Sprintf("actor %d with role %s is not allowed to remove files owned by collectionOwner %d", actorUserID, *role, collectionOwnerID))
+ }
+ }
+ // Remove files owned by others if allowed
+ if len(others) > 0 {
+ if err := c.CollectionRepo.RemoveFilesV3(ctx, req.CollectionID, collectionOwnerID, others); err != nil {
+ return stacktrace.Propagate(err, "failed to remove files")
+ }
- // Remove files owned by others if allowed
- if len(others) > 0 {
- // Validate removal for others set
- if err := c.isRemoveAllowed(ctx, actorUserID, collectionOwnerID, role, others); err != nil {
- return stacktrace.Propagate(err, "file removal check failed for others")
- }
- if err := c.CollectionRepo.RemoveFilesV3(ctx, req.CollectionID, others); err != nil {
- return stacktrace.Propagate(err, "failed to remove files")
- }
- // Optionally, create pending actions for those owners to delete their files (DELETE_SUGGESTION)
- // Group by owner and create entries
- ownersMap, err := c.FileRepo.GetOwnerToFileIDsMap(ctx, others)
- if err == nil {
- for uid, fids := range ownersMap {
- if uid == actorUserID { continue }
- now := time.Microseconds()
- for i := range fids {
- fid := fids[i]
- _, _ = c.CollectionActionsRepo.Create(ctx, uid, actorUserID, req.CollectionID, &fid, nil, "DELETE_SUGGESTED", true, now)
- }
- }
- }
- }
- return nil
+ }
+ return nil
}
-// SuggestDeleteInSharedCollection sets DELETE_SUGGESTED action for files owned by others.
-// Only collection owner or admins can call this. Acting user cannot target their own files.
+// SuggestDeleteInSharedCollection allows collection owners/admins to nudge other
+// participants to delete their files:
+// 1. only OWNER/ADMIN roles pass the access check;
+// 2. every file ID must belong to the collection and none may belong to the acting user;
+// 3. the method internally reuses RemoveFilesV3 to enforce role-based rules and
+// to actually detach the files from the collection;
+// 4. each remote owner then receives DELETE_SUGGESTED actions so their clients
+// can surface the pending delete request.
func (c *CollectionController) SuggestDeleteInSharedCollection(ctx *gin.Context, req ente.SuggestDeleteRequest) error {
- actorUserID := auth.GetUserID(ctx.Request.Header)
- accessResp, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
- CollectionID: req.CollectionID,
- ActorUserID: actorUserID,
- VerifyOwner: false,
- })
- if err != nil {
- return stacktrace.Propagate(err, "failed to verify collection access")
- }
- // Only owner or admin can suggest
- if accessResp.Role == nil || (*accessResp.Role != ente.OWNER && *accessResp.Role != ente.ADMIN) {
- return stacktrace.Propagate(ente.ErrPermissionDenied, "role not allowed to suggest delete")
- }
- // Validate all fileIDs exist in the collection
- if err := c.CollectionRepo.VerifyAllFileIDsExistsInCollection(ctx, req.CollectionID, req.FileIDs); err != nil {
- return stacktrace.Propagate(err, "file not found in collection")
- }
- // Ensure none of the files belong to actor
- ownerMap, err := c.FileRepo.GetOwnerToFileIDsMap(ctx, req.FileIDs)
- if err != nil {
- return stacktrace.Propagate(err, "failed to get owner map")
- }
- if _, ok := ownerMap[actorUserID]; ok {
- return stacktrace.Propagate(ente.ErrPermissionDenied, "can not suggest delete for actor-owned files")
- }
- // Partition into owner-owned and others
- ownerID := accessResp.Collection.Owner.ID
- ownersMap, err := c.FileRepo.GetOwnerToFileIDsMap(ctx, req.FileIDs)
- if err != nil {
- return stacktrace.Propagate(err, "failed to get owner map")
- }
- now := time.Microseconds()
- // For owner-owned files: set collection_files actions for both REMOVE and DELETE_SUGGESTED and create pending actions
- if fids, ok := ownersMap[ownerID]; ok {
- if err := c.CollectionRepo.SuggestDelete(ctx, req.CollectionID, actorUserID, fids, "REMOVE"); err != nil {
- return stacktrace.Propagate(err, "failed to set REMOVE action for owner files")
- }
- if err := c.CollectionRepo.SuggestDelete(ctx, req.CollectionID, actorUserID, fids, "DELETE_SUGGESTED"); err != nil {
- return stacktrace.Propagate(err, "failed to set DELETE_SUGGESTED action for owner files")
- }
- for i := range fids {
- fid := fids[i]
- if _, err := c.CollectionActionsRepo.Create(ctx, ownerID, actorUserID, req.CollectionID, &fid, nil, "REMOVE", true, now); err != nil {
- return stacktrace.Propagate(err, "failed to create collection action REMOVE")
- }
- if _, err := c.CollectionActionsRepo.Create(ctx, ownerID, actorUserID, req.CollectionID, &fid, nil, "DELETE_SUGGESTED", true, now); err != nil {
- return stacktrace.Propagate(err, "failed to create collection action DELETE_SUGGESTED")
- }
- }
- }
- // For other owners: remove from collection and create DELETE_SUGGESTED pending action
- for uid, fids := range ownersMap {
- if uid == ownerID || uid == actorUserID { continue }
- if err := c.CollectionRepo.RemoveFilesV3(ctx, req.CollectionID, fids); err != nil {
- return stacktrace.Propagate(err, "failed to remove other owners' files")
- }
- for i := range fids {
- fid := fids[i]
- _, _ = c.CollectionActionsRepo.Create(ctx, uid, actorUserID, req.CollectionID, &fid, nil, "DELETE_SUGGESTED", true, now)
- }
- }
- return nil
+ actorUserID := auth.GetUserID(ctx.Request.Header)
+ accessResp, err := c.AccessCtrl.GetCollection(ctx, &access.GetCollectionParams{
+ CollectionID: req.CollectionID,
+ ActorUserID: actorUserID,
+ VerifyOwner: false,
+ })
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to verify collection access")
+ }
+ // Only owner or admin can suggest
+ if accessResp.Role == nil || (*accessResp.Role != ente.OWNER && *accessResp.Role != ente.ADMIN) {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "role not allowed to suggest delete")
+ }
+ // Validate all fileIDs exist in the collection
+ if err := c.CollectionRepo.VerifyAllFileIDsExistsInCollection(ctx, req.CollectionID, req.FileIDs); err != nil {
+ return stacktrace.Propagate(err, "file not found in collection")
+ }
+ // Ensure none of the files belong to actor
+ ownerMap, err := c.FileRepo.GetOwnerToFileIDsMap(ctx, req.FileIDs)
+ if err != nil {
+ return stacktrace.Propagate(err, "failed to get owner map")
+ }
+ if _, ok := ownerMap[actorUserID]; ok {
+ return stacktrace.Propagate(ente.ErrPermissionDenied, "can not suggest delete for actor-owned files")
+ }
+ if removeErr := c.RemoveFilesV3(ctx, actorUserID, ente.RemoveFilesV3Request{FileIDs: req.FileIDs, CollectionID: req.CollectionID}); removeErr != nil {
+ return stacktrace.Propagate(removeErr, "failed to remove files")
+ }
+
+ for uid, fids := range ownerMap {
+ if err := c.CollectionActionsRepo.CreateBulk(ctx, uid, actorUserID, req.CollectionID, fids, nil, ente.ActionDeleteSuggested, true); err != nil {
+ return stacktrace.Propagate(err, "failed to create collection actions for owner files")
+ }
+ }
+ return nil
}
// isRemoveAllowed verifies that given set of files can be removed from the collection or not
-func (c *CollectionController) isRemoveAllowed(ctx *gin.Context, actorUserID int64, collectionOwnerID int64, role *ente.CollectionParticipantRole, fileIDs []int64) error {
- ownerToFilesMap, err := c.FileRepo.GetOwnerToFileIDsMap(ctx, fileIDs)
- if err != nil {
- return stacktrace.Propagate(err, "failed to get owner to fileIDs map")
- }
+func (c *CollectionController) isRemoveAllowed(ctx *gin.Context,
+ actorUserID int64,
+ collectionOwnerID int64,
+ role *ente.CollectionParticipantRole,
+ ownerToFilesMap map[int64][]int64) error {
+
// verify that none of the file belongs to the collection owner
if _, ok := ownerToFilesMap[collectionOwnerID]; ok {
- return ente.NewBadRequestWithMessage("can not remove files owned by album owner")
+ if collectionOwnerID == actorUserID {
+ return stacktrace.Propagate(ente.NewBadRequestWithMessage("can not remove files owned collection owner, admins can perform remove suggestion"), "")
+ } else if role == nil || *role != ente.ADMIN {
+ return stacktrace.Propagate(ente.NewBadRequestWithMessage("can not remove files owned by album owner"), fmt.Sprintf("role %s", *role))
+ }
}
-
+ // allow collection owner to remove files added by others
if collectionOwnerID == actorUserID {
return nil
}
-
+ // allow admins to remove files added by anyone else.
if role != nil && *role == ente.ADMIN {
return nil
}
-
+ // for collaborators and viewers, they should be only removing files added by themselfs.
// verify that user is only trying to remove files owned by them
if len(ownerToFilesMap) > 1 {
return stacktrace.Propagate(ente.ErrPermissionDenied, "can not remove files owned by others")
diff --git a/server/pkg/controller/collections/files_diff.go b/server/pkg/controller/collections/files_diff.go
index aa86e1ada4..bdcb32caf0 100644
--- a/server/pkg/controller/collections/files_diff.go
+++ b/server/pkg/controller/collections/files_diff.go
@@ -2,6 +2,7 @@ package collections
import (
"fmt"
+
"github.com/ente-io/museum/ente"
"github.com/ente-io/museum/pkg/controller/access"
"github.com/ente-io/stacktrace"
@@ -29,32 +30,32 @@ func (c *CollectionController) GetDiffV2(ctx *gin.Context, cID int64, userID int
if err != nil {
return nil, false, stacktrace.Propagate(err, "")
}
- // hide private metadata before returning files info in diff
- for idx := range diff {
- if diff[idx].OwnerID != userID {
- diff[idx].MagicMetadata = nil
- // Strip action fields from non-owners regardless of deletion state
- diff[idx].Action = nil
- diff[idx].ActionUserID = nil
- }
- // Treat action markers as soft-deletes for non-owners
- if diff[idx].Action != nil && !diff[idx].IsDeleted {
- if *diff[idx].Action == "REMOVE" || *diff[idx].Action == "DELETE" || *diff[idx].Action == "DELETE_SUGGESTED" {
- if diff[idx].OwnerID != userID { // non-owner view: mask as deleted
- diff[idx].IsDeleted = true
- }
- }
- }
- if diff[idx].Metadata.EncryptedData == "-" && !diff[idx].IsDeleted {
- // This indicates that the file is deleted, but we still have a stale entry in the collection
- log.WithFields(log.Fields{
- "file_id": diff[idx].ID,
- "collection_id": cID,
- "updated_at": diff[idx].UpdationTime,
- }).Warning("stale collection_file found")
- diff[idx].IsDeleted = true
- }
- }
+ // hide private metadata before returning files info in diff
+ for idx := range diff {
+ // Treat action markers as soft-deletes for non-owners
+ if diff[idx].Action != nil && !diff[idx].IsDeleted {
+ if *diff[idx].Action == ente.ActionRemove || *diff[idx].Action == ente.ActionDeleteSuggested {
+ if diff[idx].OwnerID != userID { // non-owner view: mask as deleted
+ diff[idx].IsDeleted = true
+ }
+ }
+ }
+ if diff[idx].OwnerID != userID {
+ diff[idx].MagicMetadata = nil
+ diff[idx].PubicMagicMetadata = nil
+ diff[idx].Action = nil
+ diff[idx].ActionUserID = nil
+ }
+ if diff[idx].Metadata.EncryptedData == "-" && !diff[idx].IsDeleted {
+ // This indicates that the file is deleted, but we still have a stale entry in the collection
+ log.WithFields(log.Fields{
+ "file_id": diff[idx].ID,
+ "collection_id": cID,
+ "updated_at": diff[idx].UpdationTime,
+ }).Warning("stale collection_file found")
+ diff[idx].IsDeleted = true
+ }
+ }
return diff, hasMore, nil
}
diff --git a/server/pkg/repo/collection.go b/server/pkg/repo/collection.go
index aefaa4ce3d..7946a6635c 100644
--- a/server/pkg/repo/collection.go
+++ b/server/pkg/repo/collection.go
@@ -3,6 +3,7 @@ package repo
import (
"context"
"database/sql"
+ "errors"
"fmt"
"github.com/ente-io/museum/pkg/repo/public"
"strconv"
@@ -46,17 +47,17 @@ func (repo *CollectionRepository) Create(c ente.Collection) (ente.Collection, er
return ente.Collection{}, ente.ErrInvalidApp
}
- err := repo.DB.QueryRow(`INSERT INTO collections(owner_id, encrypted_key, key_decryption_nonce, name, encrypted_name, name_decryption_nonce, type, attributes, updation_time, magic_metadata, pub_magic_metadata, app)
+ err := repo.DB.QueryRow(`INSERT INTO collections(owner_id, encrypted_key, key_decryption_nonce, name, encrypted_name, name_decryption_nonce, type, attributes, updation_time, magic_metadata, pub_magic_metadata, app)
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING collection_id`,
- c.Owner.ID, c.EncryptedKey, c.KeyDecryptionNonce, c.Name, c.EncryptedName, c.NameDecryptionNonce, c.Type, c.Attributes, c.UpdationTime, c.MagicMetadata, c.PublicMagicMetadata, c.App).Scan(&c.ID)
- if err != nil {
- if err.Error() == "pq: duplicate key value violates unique constraint \"collections_favorites_constraint_index\"" ||
- err.Error() == "pq: duplicate key value violates unique constraint \"collections_favorites_constraint_index_v2\"" {
- return ente.Collection{}, ente.ErrFavoriteCollectionAlreadyExist
- } else if err.Error() == "pq: duplicate key value violates unique constraint \"collections_uncategorized_constraint_index_v2\"" {
- return ente.Collection{}, ente.ErrUncategorizeCollectionAlreadyExists
- }
- }
+ c.Owner.ID, c.EncryptedKey, c.KeyDecryptionNonce, c.Name, c.EncryptedName, c.NameDecryptionNonce, c.Type, c.Attributes, c.UpdationTime, c.MagicMetadata, c.PublicMagicMetadata, c.App).Scan(&c.ID)
+ if err != nil {
+ if err.Error() == "pq: duplicate key value violates unique constraint \"collections_favorites_constraint_index\"" ||
+ err.Error() == "pq: duplicate key value violates unique constraint \"collections_favorites_constraint_index_v2\"" {
+ return ente.Collection{}, ente.ErrFavoriteCollectionAlreadyExist
+ } else if err.Error() == "pq: duplicate key value violates unique constraint \"collections_uncategorized_constraint_index_v2\"" {
+ return ente.Collection{}, ente.ErrUncategorizeCollectionAlreadyExists
+ }
+ }
return c, stacktrace.Propagate(err, "")
}
@@ -134,7 +135,7 @@ func (repo *CollectionRepository) GetWithSharingDetailsForUser(collectionID int6
return c, nil
}
func (repo *CollectionRepository) GetCollectionByType(userID int64, collectionType string, app string) (ente.Collection, error) {
- row := repo.DB.QueryRow(`SELECT collection_id, owner_id, encrypted_key, key_decryption_nonce, name, encrypted_name, name_decryption_nonce, type, attributes, updation_time, is_deleted, magic_metadata
+ row := repo.DB.QueryRow(`SELECT collection_id, owner_id, encrypted_key, key_decryption_nonce, name, encrypted_name, name_decryption_nonce, type, attributes, updation_time, is_deleted, magic_metadata
FROM collections
WHERE owner_id = $1 and type = $2 and app = $3`, userID, collectionType, app)
var c ente.Collection
@@ -580,12 +581,12 @@ func (repo *CollectionRepository) AddFiles(
return stacktrace.Propagate(err, "")
}
for _, file := range files {
- _, err := tx.ExecContext(context, `INSERT INTO collection_files
+ _, err := tx.ExecContext(context, `INSERT INTO collection_files
(collection_id, file_id, encrypted_key, key_decryption_nonce, is_deleted, updation_time, c_owner_id, f_owner_id)
VALUES($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT ON CONSTRAINT unique_collection_files_cid_fid
DO UPDATE SET(is_deleted, updation_time, action_user, action) = ($5, $6, NULL, NULL)`, collectionID, file.ID, file.EncryptedKey,
- file.KeyDecryptionNonce, false, updationTime, collectionOwnerID, fileOwnerID)
+ file.KeyDecryptionNonce, false, updationTime, collectionOwnerID, fileOwnerID)
if err != nil {
tx.Rollback()
return stacktrace.Propagate(err, "")
@@ -622,12 +623,12 @@ func (repo *CollectionRepository) RestoreFiles(ctx context.Context, userID int64
}
for _, file := range newCollectionFiles {
- _, err := tx.ExecContext(ctx, `INSERT INTO collection_files
+ _, err := tx.ExecContext(ctx, `INSERT INTO collection_files
(collection_id, file_id, encrypted_key, key_decryption_nonce, is_deleted, updation_time, c_owner_id, f_owner_id)
VALUES($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT ON CONSTRAINT unique_collection_files_cid_fid
DO UPDATE SET(is_deleted, updation_time, action_user, action) = ($5, $6, NULL, NULL)`, collectionID, file.ID, file.EncryptedKey,
- file.KeyDecryptionNonce, false, updationTime, userID, userID)
+ file.KeyDecryptionNonce, false, updationTime, userID, userID)
if err != nil {
tx.Rollback()
return stacktrace.Propagate(err, "")
@@ -651,8 +652,19 @@ func (repo *CollectionRepository) RestoreFiles(ctx context.Context, userID int64
// RemoveFilesV3 just remove the entries from the collection. This method assume that collection owner is
// different from the file owners
-func (repo *CollectionRepository) RemoveFilesV3(context context.Context, collectionID int64, fileIDs []int64) error {
+func (repo *CollectionRepository) RemoveFilesV3(context context.Context, collectionID int64, collectionOwnerID int64, fileIDs []int64) error {
updationTime := time.Microseconds()
+ ownerToFileIDs, err := repo.FileRepo.GetOwnerToFileIDsMap(context, fileIDs)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ // verify that none of the file belongs to the collection owner
+ if _, ok := ownerToFileIDs[collectionOwnerID]; ok {
+ return errors.New("can not remove files owned by album owner")
+ }
+
+ // check if there are files owned by collection owner
+
tx, err := repo.DB.BeginTx(context, nil)
if err != nil {
return stacktrace.Propagate(err, "")
@@ -674,31 +686,31 @@ func (repo *CollectionRepository) RemoveFilesV3(context context.Context, collect
return stacktrace.Propagate(err, "")
}
-// SuggestDelete sets action markers for the given files in the collection so that
+// SuggestAction sets action markers for the given files in the collection so that
// clients can act on them. It does not mark the membership as deleted.
-func (repo *CollectionRepository) SuggestDelete(ctx context.Context, collectionID int64, actorUserID int64, fileIDs []int64, action string) error {
- if len(fileIDs) == 0 {
- return nil
- }
- updationTime := time.Microseconds()
- tx, err := repo.DB.BeginTx(ctx, nil)
- if err != nil {
- return stacktrace.Propagate(err, "")
- }
- _, err = tx.ExecContext(ctx, `UPDATE collection_files
+func (repo *CollectionRepository) SuggestAction(ctx context.Context, collectionID int64, actorUserID int64, fileIDs []int64, action string) error {
+ if len(fileIDs) == 0 {
+ return nil
+ }
+ updationTime := time.Microseconds()
+ tx, err := repo.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return stacktrace.Propagate(err, "")
+ }
+ _, err = tx.ExecContext(ctx, `UPDATE collection_files
SET action_user = $1, action = $2, updation_time = $3
WHERE collection_id = $4 AND file_id = ANY($5)`,
- actorUserID, action, updationTime, collectionID, pq.Array(fileIDs))
- if err != nil {
- tx.Rollback()
- return stacktrace.Propagate(err, "")
- }
- _, err = tx.ExecContext(ctx, `UPDATE collections SET updation_time = $1 WHERE collection_id = $2`, updationTime, collectionID)
- if err != nil {
- tx.Rollback()
- return stacktrace.Propagate(err, "")
- }
- return tx.Commit()
+ actorUserID, action, updationTime, collectionID, pq.Array(fileIDs))
+ if err != nil {
+ tx.Rollback()
+ return stacktrace.Propagate(err, "")
+ }
+ _, err = tx.ExecContext(ctx, `UPDATE collections SET updation_time = $1 WHERE collection_id = $2`, updationTime, collectionID)
+ if err != nil {
+ tx.Rollback()
+ return stacktrace.Propagate(err, "")
+ }
+ return tx.Commit()
}
// MoveFiles move files from one collection to another collection
@@ -719,12 +731,12 @@ func (repo *CollectionRepository) MoveFiles(ctx context.Context,
fileIDs := make([]int64, 0)
for _, file := range fileItems {
fileIDs = append(fileIDs, file.ID)
- _, err := tx.ExecContext(ctx, `INSERT INTO collection_files
+ _, err := tx.ExecContext(ctx, `INSERT INTO collection_files
(collection_id, file_id, encrypted_key, key_decryption_nonce, is_deleted, updation_time, c_owner_id, f_owner_id)
VALUES($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT ON CONSTRAINT unique_collection_files_cid_fid
DO UPDATE SET(is_deleted, updation_time, action_user, action) = ($5, $6, NULL, NULL)`, toCollectionID, file.ID, file.EncryptedKey,
- file.KeyDecryptionNonce, false, updationTime, collectionOwner, fileOwner)
+ file.KeyDecryptionNonce, false, updationTime, collectionOwner, fileOwner)
if err != nil {
if rollbackErr := tx.Rollback(); rollbackErr != nil {
logrus.WithError(rollbackErr).Error("transaction rollback failed")
@@ -763,7 +775,7 @@ func (repo *CollectionRepository) GetDiff(collectionID int64, sinceTime int64, l
repo.LatencyLogger.WithLabelValues("CollectionRepo.GetDiff").
Observe(float64(t.Since(startTime).Milliseconds()))
}()
- rows, err := repo.DB.Query(`
+ rows, err := repo.DB.Query(`
SELECT files.file_id, files.owner_id, collection_files.collection_id, collection_files.c_owner_id,
collection_files.encrypted_key, collection_files.key_decryption_nonce,
files.file_decryption_header, files.thumbnail_decryption_header,
@@ -775,7 +787,7 @@ func (repo *CollectionRepository) GetDiff(collectionID int64, sinceTime int64, l
AND collection_files.collection_id = $1
AND collection_files.updation_time > $2
ORDER BY collection_files.updation_time LIMIT $3`,
- collectionID, sinceTime, limit)
+ collectionID, sinceTime, limit)
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
@@ -788,7 +800,7 @@ func (repo *CollectionRepository) GetFilesWithVersion(collectionID int64, update
repo.LatencyLogger.WithLabelValues("CollectionRepo.GetFilesWithVersion").
Observe(float64(t.Since(startTime).Milliseconds()))
}()
- rows, err := repo.DB.Query(`
+ rows, err := repo.DB.Query(`
SELECT files.file_id, files.owner_id, collection_files.collection_id, collection_files.c_owner_id,
collection_files.encrypted_key, collection_files.key_decryption_nonce,
files.file_decryption_header, files.thumbnail_decryption_header,
@@ -799,7 +811,7 @@ func (repo *CollectionRepository) GetFilesWithVersion(collectionID int64, update
ON collection_files.file_id = files.file_id
AND collection_files.collection_id = $1
AND collection_files.updation_time = $2`,
- collectionID, updateAtTime)
+ collectionID, updateAtTime)
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
@@ -807,7 +819,7 @@ func (repo *CollectionRepository) GetFilesWithVersion(collectionID int64, update
}
func (repo *CollectionRepository) GetFile(collectionID int64, fileID int64) ([]ente.File, error) {
- rows, err := repo.DB.Query(`
+ rows, err := repo.DB.Query(`
SELECT files.file_id, files.owner_id, collection_files.collection_id, collection_files.c_owner_id,
collection_files.encrypted_key, collection_files.key_decryption_nonce,
files.file_decryption_header, files.thumbnail_decryption_header,
@@ -818,7 +830,7 @@ func (repo *CollectionRepository) GetFile(collectionID int64, fileID int64) ([]e
ON collection_files.file_id = files.file_id
AND collection_files.collection_id = $1
AND collection_files.file_id = $2`,
- collectionID, fileID)
+ collectionID, fileID)
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
@@ -919,7 +931,7 @@ func (repo *CollectionRepository) TrashV3(ctx context.Context, collectionID int6
return stacktrace.Propagate(err, "")
}
if count != 0 {
- removedFiles, removeErr := repo.removeAllFilesAddedByOthers(collectionID)
+ removedFiles, removeErr := repo.removeAllFilesAddedByOthers(collectionID, ownerID)
if removeErr != nil {
return stacktrace.Propagate(removeErr, "")
}
@@ -936,7 +948,7 @@ func (repo *CollectionRepository) TrashV3(ctx context.Context, collectionID int6
return nil
}
-func (repo *CollectionRepository) removeAllFilesAddedByOthers(collectionID int64) (int64, error) {
+func (repo *CollectionRepository) removeAllFilesAddedByOthers(collectionID int64, cOwnerID int64) (int64, error) {
var fileIDs []int64
rows, err := repo.DB.Query(`SELECT file_id FROM collection_files WHERE collection_id = $1 AND is_deleted=false AND f_owner_id IS NOT NULL AND c_owner_id IS NOT NULL AND f_owner_id <> c_owner_id`, collectionID)
if err != nil {
@@ -953,7 +965,7 @@ func (repo *CollectionRepository) removeAllFilesAddedByOthers(collectionID int64
if len(fileIDs) == 0 {
return 0, nil
}
- removeErr := repo.RemoveFilesV3(context.Background(), collectionID, fileIDs)
+ removeErr := repo.RemoveFilesV3(context.Background(), collectionID, cOwnerID, fileIDs)
if removeErr != nil {
return 0, stacktrace.Propagate(removeErr, "")
}
diff --git a/server/pkg/repo/collection_actions.go b/server/pkg/repo/collection_actions.go
index 30d3549aad..7966f03e86 100644
--- a/server/pkg/repo/collection_actions.go
+++ b/server/pkg/repo/collection_actions.go
@@ -1,63 +1,132 @@
package repo
import (
- "context"
- "database/sql"
- "encoding/json"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "strings"
- "github.com/ente-io/museum/ente"
- "github.com/ente-io/museum/ente/base"
- "github.com/ente-io/stacktrace"
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/ente/base"
+ "github.com/ente-io/stacktrace"
+ "github.com/lib/pq"
)
type CollectionActionsRepository struct {
- DB *sql.DB
+ DB *sql.DB
}
func (r *CollectionActionsRepository) Create(ctx context.Context, userID int64, actorUserID int64, collectionID int64, fileID *int64, data map[string]interface{}, action string, isPending bool, now int64) (string, error) {
- id := base.MustNewID("cact")
- var payload []byte
- var err error
- if data != nil {
- payload, err = json.Marshal(data)
- if err != nil {
- return "", stacktrace.Propagate(err, "failed to marshal collection action data")
- }
- }
- _, err = r.DB.ExecContext(ctx, `INSERT INTO collection_actions(id, user_id, actor_user_id, collection_id, file_id, data, action, is_pending, created_at, updated_at)
+ id := base.MustNewID("cact")
+ payload, err := marshalCollectionActionData(data)
+ if err != nil {
+ return "", err
+ }
+ _, err = r.DB.ExecContext(ctx, `INSERT INTO collection_actions(id, user_id, actor_user_id, collection_id, file_id, data, action, is_pending, created_at, updated_at)
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $9)`, id, userID, actorUserID, collectionID, fileID, payload, action, isPending, now)
- return id, stacktrace.Propagate(err, "")
+ return id, stacktrace.Propagate(err, "")
}
-func (r *CollectionActionsRepository) ListForUser(ctx context.Context, userID int64, since int64, limit int) ([]ente.CollectionAction, error) {
- rows, err := r.DB.QueryContext(ctx, `SELECT id, user_id, actor_user_id, collection_id, file_id, data, action, is_pending, created_at, updated_at
- FROM collection_actions WHERE user_id = $1 AND created_at > $2 ORDER BY created_at LIMIT $3`, userID, since, limit)
- if err != nil {
- return nil, stacktrace.Propagate(err, "")
- }
- defer rows.Close()
- result := make([]ente.CollectionAction, 0)
- for rows.Next() {
- var (
- ca ente.CollectionAction
- data []byte
- fileID sql.NullInt64
- )
- if err := rows.Scan(&ca.ID, &ca.UserID, &ca.ActorUserID, &ca.CollectionID, &fileID, &data, &ca.Action, &ca.IsPending, &ca.CreatedAt, &ca.UpdatedAt); err != nil {
- return result, stacktrace.Propagate(err, "")
- }
- if fileID.Valid {
- v := fileID.Int64
- ca.FileID = &v
- }
- if data != nil && len(data) > 0 {
- var m map[string]interface{}
- if err := json.Unmarshal(data, &m); err != nil {
- return result, stacktrace.Propagate(err, "failed to unmarshal data")
- }
- ca.Data = m
- }
- result = append(result, ca)
- }
- return result, nil
+// CreateBulk inserts multiple collection actions that only differ by fileID.
+func (r *CollectionActionsRepository) CreateBulk(ctx context.Context, userID int64, actorUserID int64, collectionID int64, fileIDs []int64, data map[string]interface{}, action string, isPending bool) error {
+ if len(fileIDs) == 0 {
+ return nil
+ }
+ if actorUserID == userID {
+ return fmt.Errorf("actor %d and target user id %d should be different", actorUserID, userID)
+ }
+ payload, err := marshalCollectionActionData(data)
+ if err != nil {
+ return err
+ }
+ valueStrings := make([]string, 0, len(fileIDs))
+ args := make([]interface{}, 0, len(fileIDs)*8)
+ for i := range fileIDs {
+ id := base.MustNewID("cact")
+ var fileID int64
+ fileID = fileIDs[i]
+ idx := i*8 + 1
+ valueStrings = append(valueStrings, fmt.Sprintf("($%d,$%d,$%d,$%d,$%d,$%d,$%d,$%d)",
+ idx, idx+1, idx+2, idx+3, idx+4, idx+5, idx+6, idx+7))
+ args = append(args, id, userID, actorUserID, collectionID, fileID, payload, action, isPending)
+ }
+ query := fmt.Sprintf(`INSERT INTO collection_actions(id, user_id, actor_user_id, collection_id, file_id, data, action, is_pending) VALUES %s`, strings.Join(valueStrings, ","))
+ _, err = r.DB.ExecContext(ctx, query, args...)
+ return stacktrace.Propagate(err, "")
+}
+
+func (r *CollectionActionsRepository) ListPendingRemoveActions(ctx context.Context, userID int64, updatedAfter int64, limit int) ([]ente.CollectionAction, error) {
+ rows, err := r.DB.QueryContext(ctx, `SELECT ca.id, ca.user_id, ca.actor_user_id, ca.collection_id, ca.file_id, ca.data, ca.action, ca.is_pending, ca.created_at, ca.updated_at,
+ (cf.collection_id IS NOT NULL) AS is_valid
+ FROM collection_actions ca
+ LEFT JOIN collection_files cf
+ ON cf.collection_id = ca.collection_id
+ AND cf.file_id = ca.file_id
+ AND cf.is_deleted = false
+ AND cf.action = $2
+ WHERE ca.user_id = $1
+ AND ca.action = $2
+ AND ca.is_pending = true
+ AND ca.updated_at > $3
+ ORDER BY ca.updated_at
+ LIMIT $4`, userID, ente.ActionRemove, updatedAfter, limit)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ defer rows.Close()
+ result := make([]ente.CollectionAction, 0)
+ staleActionIDs := make([]string, 0)
+ for rows.Next() {
+ var (
+ ca ente.CollectionAction
+ data []byte
+ fileID sql.NullInt64
+ isValid bool
+ )
+ if err := rows.Scan(&ca.ID, &ca.UserID, &ca.ActorUserID, &ca.CollectionID, &fileID, &data, &ca.Action, &ca.IsPending, &ca.CreatedAt, &ca.UpdatedAt, &isValid); err != nil {
+ return result, stacktrace.Propagate(err, "")
+ }
+ if fileID.Valid {
+ v := fileID.Int64
+ ca.FileID = &v
+ }
+ if data != nil && len(data) > 0 {
+ var m map[string]interface{}
+ if err := json.Unmarshal(data, &m); err != nil {
+ return result, stacktrace.Propagate(err, "failed to unmarshal data")
+ }
+ ca.Data = m
+ }
+ if !isValid {
+ staleActionIDs = append(staleActionIDs, ca.ID)
+ continue
+ }
+ result = append(result, ca)
+ }
+ if len(staleActionIDs) > 0 {
+ if err := r.resetPendingForActions(ctx, staleActionIDs); err != nil {
+ return result, stacktrace.Propagate(err, "failed to reset stale pending actions")
+ }
+ }
+ return result, nil
+}
+
+func (r *CollectionActionsRepository) resetPendingForActions(ctx context.Context, ids []string) error {
+ if len(ids) == 0 {
+ return nil
+ }
+ _, err := r.DB.ExecContext(ctx, `UPDATE collection_actions SET is_pending = false WHERE id = ANY($1)`, pq.Array(ids))
+ return stacktrace.Propagate(err, "")
+}
+
+func marshalCollectionActionData(data map[string]interface{}) (interface{}, error) {
+ if data == nil {
+ return nil, nil
+ }
+ payload, err := json.Marshal(data)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "failed to marshal collection action data")
+ }
+ return string(payload), nil // pq expects json inputs as text, not bytea
}
diff --git a/server/pkg/repo/collection_actions_test.go b/server/pkg/repo/collection_actions_test.go
new file mode 100644
index 0000000000..29f4ebb03a
--- /dev/null
+++ b/server/pkg/repo/collection_actions_test.go
@@ -0,0 +1,38 @@
+package repo
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestMarshalCollectionActionData(t *testing.T) {
+ payload, err := marshalCollectionActionData(nil)
+ if err != nil {
+ t.Fatalf("unexpected error for nil data: %v", err)
+ }
+ if payload != nil {
+ t.Fatalf("expected nil payload for nil data, got %v", payload)
+ }
+
+ data := map[string]interface{}{
+ "reason": "admin_remove",
+ "id": float64(42),
+ }
+ payload, err = marshalCollectionActionData(data)
+ if err != nil {
+ t.Fatalf("unexpected error for valid data: %v", err)
+ }
+
+ payloadStr, ok := payload.(string)
+ if !ok {
+ t.Fatalf("expected payload to be a string, got %T", payload)
+ }
+
+ var decoded map[string]interface{}
+ if err := json.Unmarshal([]byte(payloadStr), &decoded); err != nil {
+ t.Fatalf("payload should be valid json, got error %v", err)
+ }
+ if decoded["reason"] != data["reason"] || decoded["id"] != data["id"] {
+ t.Fatalf("decoded payload mismatch. expected %v, got %v", data, decoded)
+ }
+}