Skip to content

armgit / ente

Public Imported from GitHub
0

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

[server] Allow admins and owners to remove & suggest file deletions

Neeraj Guptad8ef4676cf8a
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index 60e6098c1c..268cf18041 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -326,6 +326,15 @@ func main() {
BillingCtrl: billingController,
QueueRepo: queueRepo,
TaskRepo: taskLockingRepo,
+ CollectionActionsRepo: &repo.CollectionActionsRepository{DB: db},
+ }
+
+ // Pending actions controller/handler
+ collectionActionsController := &controller.CollectionActionsController{
+ Repo: &repo.CollectionActionsRepository{DB: db},
+ }
+ collectionActionsHandler := &api.CollectionActionsHandler{
+ Controller: collectionActionsController,
}
userController := user.NewUserController(
@@ -565,6 +574,10 @@ func main() {
Controller: collectionController,
}
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("/collections/:collectionID", collectionHandler.GetCollectionByID)
//lint:ignore SA1019 Deprecated API will be removed in the future
privateAPI.GET("/collections", collectionHandler.Get)
@@ -581,7 +594,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/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.go b/server/ente/collection.go
index 25470d72fd..3fe50c1e68 100644
--- a/server/ente/collection.go
+++ b/server/ente/collection.go
@@ -131,9 +131,16 @@ type RemoveFilesRequest struct {
// If collection owner wants to remove files owned by them, the client should move those files to other collections
// owned by the collection user. Also, See [Collection Delete Versions] for additional context.
type RemoveFilesV3Request struct {
- CollectionID int64 `json:"collectionID" binding:"required"`
- // OtherFileIDs represents the files which don't belong the user trying to remove files
- FileIDs []int64 `json:"fileIDs" binding:"required"`
+ CollectionID int64 `json:"collectionID" binding:"required"`
+ // OtherFileIDs represents the files which don't belong the user trying to remove files
+ FileIDs []int64 `json:"fileIDs" binding:"required"`
+}
+
+// SuggestDeleteRequest represents a request to suggest deletion of files in a shared collection.
+// Only collection owner or admins can suggest deletion for files owned by others (not the acting user).
+type SuggestDeleteRequest struct {
+ CollectionID int64 `json:"collectionID" binding:"required"`
+ FileIDs []int64 `json:"fileIDs" binding:"required"`
}
type RenameRequest struct {
diff --git a/server/ente/collection_action.go b/server/ente/collection_action.go
new file mode 100644
index 0000000000..d914e74a43
--- /dev/null
+++ b/server/ente/collection_action.go
@@ -0,0 +1,14 @@
+package ente
+
+type CollectionAction struct {
+ ID string `json:"id"`
+ UserID int64 `json:"userID"`
+ ActorUserID int64 `json:"actorUserID"`
+ CollectionID int64 `json:"collectionID"`
+ FileID *int64 `json:"fileID,omitempty"`
+ Action string `json:"action"`
+ IsPending bool `json:"isPending"`
+ Data map[string]interface{} `json:"data,omitempty"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+}
diff --git a/server/ente/file.go b/server/ente/file.go
index 00b5488def..3a603773a6 100644
--- a/server/ente/file.go
+++ b/server/ente/file.go
@@ -9,21 +9,24 @@ import (
// File represents an encrypted file in the system
type File struct {
- ID int64 `json:"id"`
- OwnerID int64 `json:"ownerID"`
- CollectionID int64 `json:"collectionID"`
- CollectionOwnerID *int64 `json:"collectionOwnerID"`
- EncryptedKey string `json:"encryptedKey"`
- KeyDecryptionNonce string `json:"keyDecryptionNonce"`
- File FileAttributes `json:"file" binding:"required"`
- Thumbnail FileAttributes `json:"thumbnail" binding:"required"`
- Metadata FileAttributes `json:"metadata" binding:"required"`
- // IsDeleted is True when the file ID is removed from the CollectionID
- IsDeleted bool `json:"isDeleted"`
- UpdationTime int64 `json:"updationTime"`
- MagicMetadata *MagicMetadata `json:"magicMetadata,omitempty"`
- PubicMagicMetadata *MagicMetadata `json:"pubMagicMetadata,omitempty"`
- Info *FileInfo `json:"info,omitempty"`
+ ID int64 `json:"id"`
+ OwnerID int64 `json:"ownerID"`
+ CollectionID int64 `json:"collectionID"`
+ CollectionOwnerID *int64 `json:"collectionOwnerID"`
+ EncryptedKey string `json:"encryptedKey"`
+ KeyDecryptionNonce string `json:"keyDecryptionNonce"`
+ File FileAttributes `json:"file" binding:"required"`
+ Thumbnail FileAttributes `json:"thumbnail" binding:"required"`
+ Metadata FileAttributes `json:"metadata" binding:"required"`
+ // IsDeleted is True when the file ID is removed from the CollectionID
+ IsDeleted bool `json:"isDeleted"`
+ UpdationTime int64 `json:"updationTime"`
+ MagicMetadata *MagicMetadata `json:"magicMetadata,omitempty"`
+ PubicMagicMetadata *MagicMetadata `json:"pubMagicMetadata,omitempty"`
+ Info *FileInfo `json:"info,omitempty"`
+ // Action and ActionUser are optionally set to drive client-side behavior during diffs
+ Action *string `json:"action,omitempty"`
+ ActionUserID *int64 `json:"actionUser,omitempty"`
}
type MetaFile struct {
diff --git a/server/migrations/112_add_action_columns_cf.down.sql b/server/migrations/112_add_action_columns_cf.down.sql
new file mode 100644
index 0000000000..8b14896cd5
--- /dev/null
+++ b/server/migrations/112_add_action_columns_cf.down.sql
@@ -0,0 +1,4 @@
+ALTER TABLE collection_files
+ DROP COLUMN IF EXISTS action_user,
+ DROP COLUMN IF EXISTS action;
+
diff --git a/server/migrations/112_add_action_columns_cf.up.sql b/server/migrations/112_add_action_columns_cf.up.sql
new file mode 100644
index 0000000000..98f5c046c1
--- /dev/null
+++ b/server/migrations/112_add_action_columns_cf.up.sql
@@ -0,0 +1,7 @@
+-- Add action markers to collection_files to drive client behavior during diffs
+-- action_user: user who initiated the action
+-- action: opaque text value, initially expected to be 'REMOVE' or 'DELETE'
+ALTER TABLE collection_files
+ ADD COLUMN IF NOT EXISTS action_user bigint,
+ ADD COLUMN IF NOT EXISTS action text;
+
diff --git a/server/migrations/113_create_collection_actions.down.sql b/server/migrations/113_create_collection_actions.down.sql
new file mode 100644
index 0000000000..a0eadddbc0
--- /dev/null
+++ b/server/migrations/113_create_collection_actions.down.sql
@@ -0,0 +1,3 @@
+DROP INDEX IF EXISTS collection_actions_user_id_idx;
+DROP INDEX IF EXISTS collection_actions_collection_id_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
new file mode 100644
index 0000000000..b59cf36d4e
--- /dev/null
+++ b/server/migrations/113_create_collection_actions.up.sql
@@ -0,0 +1,19 @@
+CREATE TABLE IF NOT EXISTS collection_actions (
+ id TEXT PRIMARY KEY,
+ user_id BIGINT NOT NULL,
+ actor_user_id BIGINT NOT NULL,
+ collection_id BIGINT NOT NULL,
+ file_id BIGINT,
+ data JSONB,
+ action TEXT NOT NULL,
+ is_pending BOOLEAN NOT NULL DEFAULT TRUE,
+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
+ CONSTRAINT collection_actions_file_required CHECK (
+ (action IN ('REMOVE','DELETE_SUGGESTED') AND file_id IS NOT NULL)
+ OR (action NOT IN ('REMOVE','DELETE_SUGGESTED'))
+ )
+);
+
+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);
diff --git a/server/pkg/api/collection.go b/server/pkg/api/collection.go
index 6c198652c7..db98a66e70 100644
--- a/server/pkg/api/collection.go
+++ b/server/pkg/api/collection.go
@@ -310,6 +310,25 @@ func (h *CollectionHandler) RemoveFilesV3(c *gin.Context) {
c.Status(http.StatusOK)
}
+// 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)
+}
+
// GetDiffV2 returns the diff within a collection since a timestamp
func (h *CollectionHandler) GetDiffV2(c *gin.Context) {
userID := auth.GetUserID(c.Request.Header)
diff --git a/server/pkg/api/collection_actions.go b/server/pkg/api/collection_actions.go
new file mode 100644
index 0000000000..321c8c7bb6
--- /dev/null
+++ b/server/pkg/api/collection_actions.go
@@ -0,0 +1,31 @@
+package api
+
+import (
+ "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"
+)
+
+type CollectionActionsHandler struct {
+ 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,
+ })
+}
diff --git a/server/pkg/controller/collection_actions.go b/server/pkg/controller/collection_actions.go
new file mode 100644
index 0000000000..f73d2219e4
--- /dev/null
+++ b/server/pkg/controller/collection_actions.go
@@ -0,0 +1,9 @@
+package controller
+
+import (
+ "github.com/ente-io/museum/pkg/repo"
+)
+
+type CollectionActionsController struct {
+ Repo *repo.CollectionActionsRepository
+}
diff --git a/server/pkg/controller/collections/cast.go b/server/pkg/controller/collections/cast.go
index e29452e2fb..d02f99bd34 100644
--- a/server/pkg/controller/collections/cast.go
+++ b/server/pkg/controller/collections/cast.go
@@ -34,11 +34,19 @@ func (c *CollectionController) GetCastDiff(ctx *gin.Context, sinceTime int64) ([
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].MagicMetadata != nil {
- diff[idx].MagicMetadata = nil
- }
- }
+ // hide private metadata before returning files info in diff
+ for idx := range diff {
+ if diff[idx].MagicMetadata != nil {
+ diff[idx].MagicMetadata = nil
+ }
+ // For cast diffs, treat action markers as deleted and strip action details
+ if diff[idx].Action != nil && !diff[idx].IsDeleted {
+ if *diff[idx].Action == "REMOVE" || *diff[idx].Action == "DELETE" || *diff[idx].Action == "DELETE_SUGGESTED" {
+ diff[idx].IsDeleted = true
+ }
+ }
+ diff[idx].Action = nil
+ diff[idx].ActionUserID = nil
+ }
return diff, hasMore, nil
}
diff --git a/server/pkg/controller/collections/collection.go b/server/pkg/controller/collections/collection.go
index 5a2586c055..b61f21466f 100644
--- a/server/pkg/controller/collections/collection.go
+++ b/server/pkg/controller/collections/collection.go
@@ -33,8 +33,9 @@ type CollectionController struct {
UserRepo *repo.UserRepository
FileRepo *repo.FileRepository
QueueRepo *repo.QueueRepository
- CastRepo *cast.Repository
- TaskRepo *repo.TaskLockRepository
+ CastRepo *cast.Repository
+ TaskRepo *repo.TaskLockRepository
+ CollectionActionsRepo *repo.CollectionActionsRepository
}
// Create creates a collection
diff --git a/server/pkg/controller/collections/file_action.go b/server/pkg/controller/collections/file_action.go
index 90a3213ca8..34a04a01f9 100644
--- a/server/pkg/controller/collections/file_action.go
+++ b/server/pkg/controller/collections/file_action.go
@@ -1,13 +1,14 @@
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"
- "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"
+ time "github.com/ente-io/museum/pkg/utils/time"
+ "github.com/ente-io/stacktrace"
+ "github.com/gin-gonic/gin"
+ log "github.com/sirupsen/logrus"
)
// AddFiles adds files to a collection
@@ -123,24 +124,152 @@ func (c *CollectionController) MoveFiles(ctx *gin.Context, req ente.MoveFilesReq
// 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)
- resp, 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")
- }
- err = c.isRemoveAllowed(ctx, actorUserID, resp.Collection.Owner.ID, resp.Role, req.FileIDs)
- if err != nil {
- return stacktrace.Propagate(err, "file removal check failed")
- }
- err = c.CollectionRepo.RemoveFilesV3(ctx, req.CollectionID, req.FileIDs)
- if err != nil {
- return stacktrace.Propagate(err, "failed to remove files")
- }
- 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")
+ }
+
+ 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")
+ }
+ // 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)
+ }
+ }
+
+ // 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")
+ }
+ }
+
+ // 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
+}
+
+// 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.
+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
}
// isRemoveAllowed verifies that given set of files can be removed from the collection or not
diff --git a/server/pkg/controller/collections/files_diff.go b/server/pkg/controller/collections/files_diff.go
index 8d2215df47..aa86e1ada4 100644
--- a/server/pkg/controller/collections/files_diff.go
+++ b/server/pkg/controller/collections/files_diff.go
@@ -29,21 +29,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
- }
- 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 {
+ 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
+ }
+ }
return diff, hasMore, nil
}
diff --git a/server/pkg/controller/collections/share.go b/server/pkg/controller/collections/share.go
index c64fe9d0c0..9dae3742d2 100644
--- a/server/pkg/controller/collections/share.go
+++ b/server/pkg/controller/collections/share.go
@@ -287,11 +287,19 @@ func (c *CollectionController) GetPublicDiff(ctx *gin.Context, sinceTime int64)
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].MagicMetadata != nil {
- diff[idx].MagicMetadata = nil
- }
- }
+ // hide private metadata before returning files info in diff
+ for idx := range diff {
+ if diff[idx].MagicMetadata != nil {
+ diff[idx].MagicMetadata = nil
+ }
+ // For public diffs, treat action markers as deleted and strip action details
+ if diff[idx].Action != nil && !diff[idx].IsDeleted {
+ if *diff[idx].Action == "REMOVE" || *diff[idx].Action == "DELETE" || *diff[idx].Action == "DELETE_SUGGESTED" {
+ diff[idx].IsDeleted = true
+ }
+ }
+ diff[idx].Action = nil
+ diff[idx].ActionUserID = nil
+ }
return diff, hasMore, nil
}
diff --git a/server/pkg/repo/collection.go b/server/pkg/repo/collection.go
index dff5fd729d..aefaa4ce3d 100644
--- a/server/pkg/repo/collection.go
+++ b/server/pkg/repo/collection.go
@@ -580,12 +580,12 @@ func (repo *CollectionRepository) AddFiles(
return stacktrace.Propagate(err, "")
}
for _, file := range 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) = ($5, $6)`, collectionID, file.ID, file.EncryptedKey,
- file.KeyDecryptionNonce, false, updationTime, collectionOwnerID, fileOwnerID)
+ _, 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)
if err != nil {
tx.Rollback()
return stacktrace.Propagate(err, "")
@@ -622,12 +622,12 @@ func (repo *CollectionRepository) RestoreFiles(ctx context.Context, userID int64
}
for _, file := range newCollectionFiles {
- _, 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) = ($5, $6)`, collectionID, file.ID, file.EncryptedKey,
- file.KeyDecryptionNonce, false, updationTime, userID, userID)
+ _, 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)
if err != nil {
tx.Rollback()
return stacktrace.Propagate(err, "")
@@ -674,6 +674,33 @@ 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
+// 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
+ 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()
+}
+
// MoveFiles move files from one collection to another collection
func (repo *CollectionRepository) MoveFiles(ctx context.Context,
toCollectionID int64, fromCollectionID int64,
@@ -692,12 +719,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
- (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) = ($5, $6)`, toCollectionID, file.ID, file.EncryptedKey,
- file.KeyDecryptionNonce, false, updationTime, collectionOwner, fileOwner)
+ _, 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)
if err != nil {
if rollbackErr := tx.Rollback(); rollbackErr != nil {
logrus.WithError(rollbackErr).Error("transaction rollback failed")
@@ -736,19 +763,19 @@ 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(`
- 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,
- files.metadata_decryption_header, files.encrypted_metadata, files.magic_metadata, files.pub_magic_metadata,
- files.info, collection_files.is_deleted, collection_files.updation_time
- FROM files
- INNER JOIN collection_files
- ON collection_files.file_id = files.file_id
- AND collection_files.collection_id = $1
- AND collection_files.updation_time > $2
- ORDER BY collection_files.updation_time LIMIT $3`,
- collectionID, sinceTime, limit)
+ 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,
+ files.metadata_decryption_header, files.encrypted_metadata, files.magic_metadata, files.pub_magic_metadata,
+ files.info, collection_files.action_user, collection_files.action, collection_files.is_deleted, collection_files.updation_time
+ FROM files
+ INNER JOIN collection_files
+ ON collection_files.file_id = files.file_id
+ AND collection_files.collection_id = $1
+ AND collection_files.updation_time > $2
+ ORDER BY collection_files.updation_time LIMIT $3`,
+ collectionID, sinceTime, limit)
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
@@ -761,18 +788,18 @@ func (repo *CollectionRepository) GetFilesWithVersion(collectionID int64, update
repo.LatencyLogger.WithLabelValues("CollectionRepo.GetFilesWithVersion").
Observe(float64(t.Since(startTime).Milliseconds()))
}()
- 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,
- files.metadata_decryption_header, files.encrypted_metadata, files.magic_metadata, files.pub_magic_metadata,
- files.info, collection_files.is_deleted, collection_files.updation_time
- FROM files
- INNER JOIN collection_files
- ON collection_files.file_id = files.file_id
- AND collection_files.collection_id = $1
- AND collection_files.updation_time = $2`,
- collectionID, updateAtTime)
+ 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,
+ files.metadata_decryption_header, files.encrypted_metadata, files.magic_metadata, files.pub_magic_metadata,
+ files.info, collection_files.action_user, collection_files.action, collection_files.is_deleted, collection_files.updation_time
+ FROM files
+ INNER JOIN collection_files
+ ON collection_files.file_id = files.file_id
+ AND collection_files.collection_id = $1
+ AND collection_files.updation_time = $2`,
+ collectionID, updateAtTime)
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
@@ -780,18 +807,18 @@ func (repo *CollectionRepository) GetFilesWithVersion(collectionID int64, update
}
func (repo *CollectionRepository) GetFile(collectionID int64, fileID int64) ([]ente.File, error) {
- 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,
- files.metadata_decryption_header, files.encrypted_metadata, files.magic_metadata, files.pub_magic_metadata,
- files.info, collection_files.is_deleted, collection_files.updation_time
- FROM files
- INNER JOIN collection_files
- ON collection_files.file_id = files.file_id
- AND collection_files.collection_id = $1
- AND collection_files.file_id = $2`,
- collectionID, fileID)
+ 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,
+ files.metadata_decryption_header, files.encrypted_metadata, files.magic_metadata, files.pub_magic_metadata,
+ files.info, collection_files.action_user, collection_files.action, collection_files.is_deleted, collection_files.updation_time
+ FROM files
+ INNER JOIN collection_files
+ ON collection_files.file_id = files.file_id
+ AND collection_files.collection_id = $1
+ AND collection_files.file_id = $2`,
+ collectionID, fileID)
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
diff --git a/server/pkg/repo/collection_actions.go b/server/pkg/repo/collection_actions.go
new file mode 100644
index 0000000000..30d3549aad
--- /dev/null
+++ b/server/pkg/repo/collection_actions.go
@@ -0,0 +1,63 @@
+package repo
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+
+ "github.com/ente-io/museum/ente"
+ "github.com/ente-io/museum/ente/base"
+ "github.com/ente-io/stacktrace"
+)
+
+type CollectionActionsRepository struct {
+ 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)
+ 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, "")
+}
+
+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
+}
diff --git a/server/pkg/repo/file.go b/server/pkg/repo/file.go
index cda49599cc..7d0cb3475a 100644
--- a/server/pkg/repo/file.go
+++ b/server/pkg/repo/file.go
@@ -1,12 +1,12 @@
package repo
import (
- "context"
- "database/sql"
- "errors"
- "fmt"
- "strconv"
- "strings"
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
"github.com/ente-io/stacktrace"
log "github.com/sirupsen/logrus"
@@ -814,26 +814,36 @@ func (repo *FileRepository) GetTotalFileCount() (int64, error) {
}
func convertRowsToFiles(rows *sql.Rows) ([]ente.File, error) {
- defer rows.Close()
- files := make([]ente.File, 0)
- for rows.Next() {
- var (
- file ente.File
- updationTime float64
- )
- err := rows.Scan(&file.ID, &file.OwnerID, &file.CollectionID, &file.CollectionOwnerID,
- &file.EncryptedKey, &file.KeyDecryptionNonce,
- &file.File.DecryptionHeader, &file.Thumbnail.DecryptionHeader,
- &file.Metadata.DecryptionHeader,
- &file.Metadata.EncryptedData, &file.MagicMetadata, &file.PubicMagicMetadata,
- &file.Info, &file.IsDeleted, &updationTime)
- if err != nil {
- return files, stacktrace.Propagate(err, "")
- }
- file.UpdationTime = int64(updationTime)
- files = append(files, file)
- }
- return files, nil
+ defer rows.Close()
+ files := make([]ente.File, 0)
+ for rows.Next() {
+ var (
+ file ente.File
+ updationTime float64
+ actionUser sql.NullInt64
+ action sql.NullString
+ )
+ err := rows.Scan(&file.ID, &file.OwnerID, &file.CollectionID, &file.CollectionOwnerID,
+ &file.EncryptedKey, &file.KeyDecryptionNonce,
+ &file.File.DecryptionHeader, &file.Thumbnail.DecryptionHeader,
+ &file.Metadata.DecryptionHeader,
+ &file.Metadata.EncryptedData, &file.MagicMetadata, &file.PubicMagicMetadata,
+ &file.Info, &actionUser, &action, &file.IsDeleted, &updationTime)
+ if err != nil {
+ return files, stacktrace.Propagate(err, "")
+ }
+ if actionUser.Valid {
+ v := actionUser.Int64
+ file.ActionUserID = &v
+ }
+ if action.Valid {
+ v := action.String
+ file.Action = &v
+ }
+ file.UpdationTime = int64(updationTime)
+ files = append(files, file)
+ }
+ return files, nil
}
// scheduleDeletion added a list of files's object ids to delete queue for deletion from datastore