Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Add endpoints for delete-suggestions and rejecting suggestions

Neeraj Gupta4301362fc1f2
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index b8e719411b..1443f53f1e 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -576,6 +576,8 @@ func main() {
privateAPI.POST("/collections", collectionHandler.Create)
// Collection actions (exposed for clients to fetch suggestions/removals)
privateAPI.GET("/collection-actions/pending-remove", collectionActionsHandler.ListPendingRemove)
+ privateAPI.GET("/collection-actions/delete-suggestions", collectionActionsHandler.ListDeleteSuggestions)
+ privateAPI.POST("/collection-actions/reject-delete-suggestions", collectionActionsHandler.RejectDeleteSuggestions)
privateAPI.GET("/collections/:collectionID", collectionHandler.GetCollectionByID)
//lint:ignore SA1019 Deprecated API will be removed in the future
diff --git a/server/docs/collections/collections-architecture-collection-actions.md b/server/docs/collections/collections-architecture-collection-actions.md
index 4b746c6846..4056b92fea 100644
--- a/server/docs/collections/collections-architecture-collection-actions.md
+++ b/server/docs/collections/collections-architecture-collection-actions.md
@@ -5,7 +5,7 @@ This document supplements `collections-architecture.md` with admin/owner removal
## Summary
- Adds soft action markers to `collection_files` to drive client behavior: `action_user`, `action`.
-- Introduces a `collection_actions` store for per-user pending actions (`REMOVE`, `DELETE_SUGGESTED`); `/collection-actions/pending-remove` currently exposes the `REMOVE` queue.
+- Introduces a `collection_actions` store for per-user pending actions (`REMOVE`, `DELETE_SUGGESTED`); `/collection-actions/pending-remove` exposes the `REMOVE` queue and `/collection-actions/delete-suggestions` exposes the `DELETE_SUGGESTED` queue.
- Extends removal flows so admins/owners can orchestrate deletes in shared collections while preserving invariants.
## Endpoints
@@ -20,16 +20,58 @@ This document supplements `collections-architecture.md` with admin/owner removal
- Owner-owned files: set `REMOVE` marker on the membership and create two actions for the owner (`REMOVE`, `DELETE_SUGGESTED`).
- Other owners’ files: remove membership; create `DELETE_SUGGESTED` actions for the respective file owners.
-- `GET /collection-actions/pending-remove?updatedAt=...`
- - Returns pending `REMOVE` actions newer than the provided timestamp (limit 2000). Each entry includes the actor, collection, and file ID so clients can guide the owner workflow.
- - `DELETE_SUGGESTED` entries share the same table but do not have an HTTP feed yet; they are reserved for forthcoming client flows.
+- `GET /collection-actions/pending-remove?sinceTime=<int64>`
+ - Returns pending `REMOVE` actions newer than `sinceTime` (limit 2000). Each entry includes the actor, collection, and file ID so clients can guide the owner workflow.
+ - Response shape: `{ "actions": [CollectionAction...], "hasMore": boolean }`.
+- `GET /collection-actions/delete-suggestions?sinceTime=...`
+ - Returns pending `DELETE_SUGGESTED` actions newer than the provided timestamp (limit 2000, same as pending remove).
+ - Server validates that every referenced file is owned by the authenticated user; mismatches surface as 500s so we can detect data drifts early.
+ - If a referenced file already lives in trash or was permanently deleted (any non-restored trash row), the server marks the action as resolved (`is_pending=false`) and omits it from the response since the user already acted on it.
+- `POST /collection-actions/reject-delete-suggestions`
+ - Payload: `{ "fileIDs": [ ... ] }` (max 2000 IDs per request).
+ - Marks the provided delete suggestions as resolved (sets `is_pending=false`) for the authenticated user, if they were still pending.
+
+### Owner Removal Flow (explicit)
+
+- Collection owners do not use `/collections/v3/remove-files` for their own files.
+- Instead, they should relocate using `/collections/move-files` (owner-only). This inserts into the target collection and soft-deletes the membership in the source collection so the file disappears from the album while remaining owned elsewhere (see `pkg/repo/collection.go:734+`).
+
+### Suggest Delete behavior (expanded)
+
+- `POST /collections/suggest-delete` removes the memberships for all non-owner files in the target collection and generates `DELETE_SUGGESTED` actions for each remote owner (see `pkg/controller/collections/file_action.go:234–241`).
+- For album-owner-owned files, it sets a `REMOVE` action marker to let the owner handle the follow-up and also enqueues a `DELETE_SUGGESTED` for the owner.
+- Clients can fetch the suggestions feed via `GET /collection-actions/delete-suggestions?sinceTime=...`.
## Diff Semantics
- `GET /collections/v2/diff`
- - For non-owners: entries with `action in {REMOVE, DELETE_SUGGESTED}` are masked as `isDeleted=true`; `action` and `actionUser` are omitted.
- - For the file owner: `action` and `actionUser` are included to drive follow-up behavior.
-- Public and cast diffs always mask entries with actions (`REMOVE`, `DELETE_SUGGESTED`, plus legacy `DELETE`) as deleted and strip action details.
+ - Non-owners: entries with `action in {REMOVE, DELETE_SUGGESTED}` are surfaced as if deleted (`isDeleted=true`), and `action`/`actionUser`/private metadata are stripped.
+ - File owner: receives `action` and `actionUser` along with the entry; entry is not forced to deleted solely due to action markers.
+- Public and cast diffs: entries with `action in {REMOVE, DELETE_SUGGESTED, DELETE}` are always masked as deleted and action details are stripped.
+
+## Examples and Errors
+
+- Remove files v3
+ - Request
+ - `POST /collections/v3/remove-files`
+ - Body: `{ "collectionID": 123, "fileIDs": [111, 222, 333] }`
+ - Errors
+ - If the album owner attempts to remove their own files: HTTP 400 with message `"can not remove files owned collection owner, admins can perform remove suggestion"` (see `pkg/controller/collections/file_action.go`).
+ - If a non-admin attempts to remove album-owner-owned files: HTTP 400 with message `"can not remove files owned by album owner"`.
+
+- Suggest delete
+ - Request
+ - `POST /collections/suggest-delete`
+ - Body: `{ "collectionID": 123, "fileIDs": [444, 555] }`
+ - Notes
+ - The server rejects actor-owned targets; clients must not include files owned by the actor.
+ - Upon success, memberships for non-owner files are removed and delete suggestions are created for each remote owner.
+
+## Reactivation (Resurrect) Semantics
+
+- When a previously-deleted membership is reactivated via `AddFiles`, `RestoreFiles`, or `MoveFiles`:
+ - Soft action markers are cleared (`action`, `action_user` set to NULL).
+ - `created_at` is refreshed only when the row transitions from deleted→active; otherwise it remains unchanged (see `pkg/repo/collection.go` upsert in `MoveFiles`).
## Client Guidance
diff --git a/server/docs/collections/collections-architecture.md b/server/docs/collections/collections-architecture.md
index d3ebc73744..ce20df90fa 100644
--- a/server/docs/collections/collections-architecture.md
+++ b/server/docs/collections/collections-architecture.md
@@ -126,7 +126,9 @@ When a user removes their own files from a collection they own:
- Table: `collection_actions(id, user_id, actor_user_id, collection_id, file_id, data JSONB, action, is_pending, created_at, updated_at)`.
- ID uses nanoid (server/ente/base/id.go).
-- `GET /collection-actions?sinceTime=...` returns actions for the authenticated `user_id` (alias: `/pending-actions`).
+- `GET /collection-actions/pending-remove?sinceTime=<int64>` returns `REMOVE` actions for the authenticated owner so clients can guide the shared-collection workflow. Response: `{ "actions": [...], "hasMore": boolean }`.
+ - `GET /collection-actions/delete-suggestions?sinceTime=<int64>` returns `DELETE_SUGGESTED` actions; the server double-checks ownership and marks as resolved any entries whose files already exist as non-restored trash rows (either still in trash or already permanently deleted). Response: `{ "actions": [...], "hasMore": boolean }`.
+- `POST /collection-actions/reject-delete-suggestions` accepts a list of file IDs and marks the matching pending delete suggestions as resolved for the caller.
- Clients act on these locally:
- Owner processes `REMOVE` by ensuring file remains in at least one owned collection, then can finalize server-side removal.
- `DELETE_SUGGESTED` prompts file owner to delete files locally if desired.
diff --git a/server/migrations/113_create_collection_actions.down.sql b/server/migrations/113_create_collection_actions.down.sql
index 623fe26d22..632d50e1cd 100644
--- a/server/migrations/113_create_collection_actions.down.sql
+++ b/server/migrations/113_create_collection_actions.down.sql
@@ -1,3 +1,4 @@
+DROP TRIGGER IF EXISTS update_collection_actions_updated_at ON collection_actions;
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;
diff --git a/server/migrations/113_create_collection_actions.up.sql b/server/migrations/113_create_collection_actions.up.sql
index c67d0fdaf1..6aefef5d92 100644
--- a/server/migrations/113_create_collection_actions.up.sql
+++ b/server/migrations/113_create_collection_actions.up.sql
@@ -20,3 +20,8 @@ CREATE INDEX IF NOT EXISTS collection_actions_collection_id_idx ON collection_ac
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;
+
+CREATE TRIGGER update_collection_actions_updated_at
+ BEFORE UPDATE ON collection_actions
+ FOR EACH ROW
+EXECUTE PROCEDURE trigger_updated_at_microseconds_column();
diff --git a/server/pkg/api/collection_actions.go b/server/pkg/api/collection_actions.go
index af9aed4725..b634ee3471 100644
--- a/server/pkg/api/collection_actions.go
+++ b/server/pkg/api/collection_actions.go
@@ -1,9 +1,11 @@
package api
import (
+ "fmt"
"net/http"
"strconv"
+ "github.com/ente-io/museum/ente"
"github.com/ente-io/museum/pkg/controller"
"github.com/ente-io/museum/pkg/utils/auth"
"github.com/ente-io/museum/pkg/utils/handler"
@@ -15,27 +17,79 @@ type CollectionActionsHandler struct {
Controller *controller.CollectionActionsController
}
-const pendingRemoveLimit = 2000
+const collectionActionsLimit = 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 := int64(0)
- if c.Query("sinceTime") != "" {
- parseValue, err := strconv.ParseInt(c.Query("sinceTime"), 10, 64)
- if err != nil {
- handler.Error(c, stacktrace.Propagate(err, ""))
- return
- }
- updatedAfter = parseValue
- }
- actions, err := h.Controller.ListPendingRemoveActions(c, userID, updatedAfter, pendingRemoveLimit)
+ updatedAfter, err := parseSinceTime(c.Query("sinceTime"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ actions, err := h.Controller.ListPendingRemoveActions(c, userID, updatedAfter, collectionActionsLimit)
if err != nil {
handler.Error(c, stacktrace.Propagate(err, ""))
return
}
c.JSON(http.StatusOK, gin.H{
"actions": actions,
- "hasMore": len(actions) >= pendingRemoveLimit,
+ "hasMore": len(actions) >= collectionActionsLimit,
})
}
+
+// ListDeleteSuggestions returns pending DELETE_SUGGESTED actions for the actor.
+func (h *CollectionActionsHandler) ListDeleteSuggestions(c *gin.Context) {
+ userID := auth.GetUserID(c.Request.Header)
+ updatedAfter, err := parseSinceTime(c.Query("sinceTime"))
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ actions, err := h.Controller.ListPendingDeleteSuggestions(c, userID, updatedAfter, collectionActionsLimit)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, ""))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "actions": actions,
+ "hasMore": len(actions) >= collectionActionsLimit,
+ })
+}
+
+type rejectDeleteSuggestionsRequest struct {
+ FileIDs []int64 `json:"fileIDs" binding:"required"`
+}
+
+// RejectDeleteSuggestions clears pending DELETE_SUGGESTED actions for the provided file IDs.
+func (h *CollectionActionsHandler) RejectDeleteSuggestions(c *gin.Context) {
+ userID := auth.GetUserID(c.Request.Header)
+ var req rejectDeleteSuggestionsRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "invalid payload"))
+ return
+ }
+ if len(req.FileIDs) == 0 {
+ handler.Error(c, stacktrace.Propagate(ente.NewBadRequestWithMessage("fileIDs must not be empty"), ""))
+ return
+ }
+ if len(req.FileIDs) > collectionActionsLimit {
+ handler.Error(c, stacktrace.Propagate(ente.NewBadRequestWithMessage(fmt.Sprintf("can not reject more than %d items in one request", collectionActionsLimit)), ""))
+ return
+ }
+ updated, err := h.Controller.RejectDeleteSuggestions(c, userID, req.FileIDs)
+ if err != nil {
+ handler.Error(c, stacktrace.Propagate(err, "failed to reject delete suggestions"))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{
+ "updated": updated,
+ })
+}
+
+func parseSinceTime(raw string) (int64, error) {
+ if raw == "" {
+ return 0, nil
+ }
+ return strconv.ParseInt(raw, 10, 64)
+}
diff --git a/server/pkg/controller/collection_actions.go b/server/pkg/controller/collection_actions.go
index 801a4c2527..ce05bcde07 100644
--- a/server/pkg/controller/collection_actions.go
+++ b/server/pkg/controller/collection_actions.go
@@ -14,3 +14,11 @@ type CollectionActionsController struct {
func (c *CollectionActionsController) ListPendingRemoveActions(ctx context.Context, userID int64, updatedAfter int64, limit int) ([]ente.CollectionAction, error) {
return c.Repo.ListPendingRemoveActions(ctx, userID, updatedAfter, limit)
}
+
+func (c *CollectionActionsController) ListPendingDeleteSuggestions(ctx context.Context, userID int64, updatedAfter int64, limit int) ([]ente.CollectionAction, error) {
+ return c.Repo.ListPendingDeleteSuggestions(ctx, userID, updatedAfter, limit)
+}
+
+func (c *CollectionActionsController) RejectDeleteSuggestions(ctx context.Context, userID int64, fileIDs []int64) (int64, error) {
+ return c.Repo.RejectDeleteSuggestions(ctx, userID, fileIDs)
+}
diff --git a/server/pkg/controller/collections/file_action.go b/server/pkg/controller/collections/file_action.go
index bc47cd70be..6c51421ca1 100644
--- a/server/pkg/controller/collections/file_action.go
+++ b/server/pkg/controller/collections/file_action.go
@@ -150,6 +150,11 @@ func (c *CollectionController) RemoveFilesV3(ctx *gin.Context, actorUserID int64
collectionOwnerID := accessResp.Collection.Owner.ID
role := accessResp.Role
+ // Validate that all requested files exist in the target collection
+ if err := c.CollectionRepo.VerifyAllFileIDsExistsInCollection(ctx, req.CollectionID, req.FileIDs); err != nil {
+ return stacktrace.Propagate(err, "file not found in collection")
+ }
+
// Partition fileIDs by owner
ownerToFilesMap, err := c.FileRepo.GetOwnerToFileIDsMap(ctx, req.FileIDs)
if err != nil {
@@ -231,7 +236,7 @@ func (c *CollectionController) SuggestDeleteInSharedCollection(ctx *gin.Context,
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 {
+ if removeErr := c.RemoveFilesV3(ctx, actorUserID, ente.RemoveFilesV3Request(req)); removeErr != nil {
return stacktrace.Propagate(removeErr, "failed to remove files")
}
diff --git a/server/pkg/repo/collection_actions.go b/server/pkg/repo/collection_actions.go
index 7966f03e86..582a27fc01 100644
--- a/server/pkg/repo/collection_actions.go
+++ b/server/pkg/repo/collection_actions.go
@@ -44,8 +44,7 @@ func (r *CollectionActionsRepository) CreateBulk(ctx context.Context, userID int
args := make([]interface{}, 0, len(fileIDs)*8)
for i := range fileIDs {
id := base.MustNewID("cact")
- var fileID int64
- fileID = fileIDs[i]
+ 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))
@@ -91,7 +90,7 @@ func (r *CollectionActionsRepository) ListPendingRemoveActions(ctx context.Conte
v := fileID.Int64
ca.FileID = &v
}
- if data != nil && len(data) > 0 {
+ if 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")
@@ -112,6 +111,76 @@ func (r *CollectionActionsRepository) ListPendingRemoveActions(ctx context.Conte
return result, nil
}
+func (r *CollectionActionsRepository) ListPendingDeleteSuggestions(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,
+ f.owner_id,
+ (t.file_id IS NOT NULL) AS is_in_trash
+ FROM collection_actions ca
+ LEFT JOIN files f
+ ON f.file_id = ca.file_id
+ LEFT JOIN trash t
+ ON t.user_id = ca.user_id
+ AND t.file_id = ca.file_id
+ AND t.is_restored = false
+ 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.ActionDeleteSuggested, 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
+ ownerID sql.NullInt64
+ hasTrashEntry bool
+ )
+ if err := rows.Scan(&ca.ID, &ca.UserID, &ca.ActorUserID, &ca.CollectionID, &fileID, &data, &ca.Action, &ca.IsPending, &ca.CreatedAt, &ca.UpdatedAt, &ownerID, &hasTrashEntry); err != nil {
+ return result, stacktrace.Propagate(err, "")
+ }
+ if !fileID.Valid {
+ staleActionIDs = append(staleActionIDs, ca.ID)
+ continue
+ }
+ fid := fileID.Int64
+ ca.FileID = &fid
+
+ if !ownerID.Valid {
+ staleActionIDs = append(staleActionIDs, ca.ID)
+ continue
+ }
+ if ownerID.Int64 != ca.UserID {
+ return result, stacktrace.NewError(fmt.Sprintf("delete suggestion action %s references file %d owned by %d for user %d", ca.ID, fid, ownerID.Int64, ca.UserID))
+ }
+ if hasTrashEntry {
+ staleActionIDs = append(staleActionIDs, ca.ID)
+ continue
+ }
+ if 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)
+ }
+ if len(staleActionIDs) > 0 {
+ if err := r.resetPendingForActions(ctx, staleActionIDs); err != nil {
+ return result, stacktrace.Propagate(err, "failed to reset stale delete-suggested actions")
+ }
+ }
+ return result, nil
+}
+
func (r *CollectionActionsRepository) resetPendingForActions(ctx context.Context, ids []string) error {
if len(ids) == 0 {
return nil
@@ -120,6 +189,23 @@ func (r *CollectionActionsRepository) resetPendingForActions(ctx context.Context
return stacktrace.Propagate(err, "")
}
+func (r *CollectionActionsRepository) RejectDeleteSuggestions(ctx context.Context, userID int64, fileIDs []int64) (int64, error) {
+ if len(fileIDs) == 0 {
+ return 0, nil
+ }
+ res, err := r.DB.ExecContext(ctx, `UPDATE collection_actions
+ SET is_pending = false
+ WHERE user_id = $1
+ AND action = $2
+ AND is_pending = true
+ AND file_id = ANY($3)`, userID, ente.ActionDeleteSuggested, pq.Array(fileIDs))
+ if err != nil {
+ return 0, stacktrace.Propagate(err, "")
+ }
+ rowsAffected, err := res.RowsAffected()
+ return rowsAffected, stacktrace.Propagate(err, "")
+}
+
func marshalCollectionActionData(data map[string]interface{}) (interface{}, error) {
if data == nil {
return nil, nil