Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat(gallery):upload-to-shared-albums

Aswin Asok219de2d228d0
diff --git a/web/apps/photos/docs/shared-album-contributor-upload-flow.md b/web/apps/photos/docs/shared-album-contributor-upload-flow.md
new file mode 100644
index 0000000000..72e1504117
--- /dev/null
+++ b/web/apps/photos/docs/shared-album-contributor-upload-flow.md
@@ -0,0 +1,546 @@
+# Shared Album Contributor Upload on Web
+
+Status: Draft
+
+This document is the SRS and HLD for adding contributor upload support to `web/apps/photos/src` with parity to the current `mobile/apps/photos` behavior.
+
+The target feature is not "upload directly into a shared album". The target feature is:
+
+1. preserve uploader ownership,
+2. allow `OWNER` / `ADMIN` / `COLLABORATOR` add flows where mobile allows them,
+3. deny `VIEWER`,
+4. route new uploads and cross-owner copies through the user's own `uncategorized` collection when required,
+5. keep web behavior aligned with current mobile logic.
+
+## 1. Scope
+
+### In scope
+
+- Incoming shared albums where the current user is `ADMIN` or `COLLABORATOR`.
+- Owner-owned albums, which must continue to use the existing direct upload flow.
+- Adding an already uploaded Ente file to a shared album.
+- Uploading a brand-new local file to a shared album.
+- Adding an already uploaded file owned by another user to a shared album.
+- Same-hash reuse, copy-via-`uncategorized`, and duplicate suppression rules that mobile already applies.
+- All web entry points that can target an album upload/add flow.
+
+### Out of scope
+
+- Public collect links / anonymous uploads.
+- Participant management UX beyond role checks needed for upload permission.
+- Changing move semantics for shared albums.
+ Mobile explicitly treats shared album flows as "add", not "move".
+- Server-side API changes.
+ Existing server APIs already support the needed flow.
+
+## 2. Reference Implementations
+
+### Mobile reference
+
+- `mobile/apps/photos/lib/models/collection/collection.dart`
+- `mobile/apps/photos/lib/models/files_split.dart`
+- `mobile/apps/photos/lib/ui/actions/collection/collection_file_actions.dart`
+- `mobile/apps/photos/lib/services/collections_service.dart`
+- `mobile/apps/photos/lib/utils/file_uploader.dart`
+- `mobile/apps/photos/lib/gateways/collections/collection_files_gateway.dart`
+
+### Web code paths impacted
+
+- `web/apps/photos/src/components/Upload.tsx`
+- `web/apps/photos/src/services/upload-manager.ts`
+- `web/apps/photos/src/pages/gallery.tsx`
+- `web/apps/photos/src/components/FileListWithViewer.tsx`
+- `web/packages/new/photos/components/CollectionSelector.tsx`
+- `web/packages/new/photos/components/gallery/helpers.ts`
+- `web/packages/new/photos/services/collection-summary.ts`
+- `web/packages/new/photos/services/collection.ts`
+- `web/packages/media/file.ts`
+
+## 3. Domain Model and Invariants
+
+### 3.1 Collection membership vs file ownership
+
+The same uploaded file can appear in multiple collections. On web this is represented by multiple `EnteFile` rows with the same `file.id` and different `collectionID`. In other words:
+
+- mobile `uploadedFileID` == web `EnteFile.id`
+- the logical primary key for a collection-file row is `(file.id, collectionID)`
+
+This distinction matters because "add to album" usually means "create another collection membership", not "upload new bytes".
+
+### 3.2 Ownership invariant
+
+For shared album contributor flows, files added by the current user must remain owned by the current user.
+
+This is why mobile does not directly upload or directly copy into an incoming shared album when the destination is not owned by the actor. Instead it uses:
+
+1. user-owned `uncategorized`
+2. then `POST /collections/add-files`
+
+Web must preserve the same invariant.
+
+### 3.3 Server enforcement we must respect
+
+Current server constraints already align with mobile:
+
+- `POST /collections/add-files`
+ - requires `role.canAdd`
+ - requires the actor to own the file IDs being added
+- `POST /files/copy`
+ - destination must be owned by the actor
+
+Therefore:
+
+- direct add of other-owned files is invalid,
+- direct copy into an incoming shared album is invalid,
+- copy-via-`uncategorized` is required for contributor parity.
+
+### 3.4 Permission model
+
+Mobile and web already share the same effective participant roles:
+
+- `OWNER`
+- `ADMIN`
+- `COLLABORATOR`
+- `VIEWER`
+- `UNKNOWN`
+
+Upload/add permission for this feature is:
+
+- allowed: `OWNER`, `ADMIN`, `COLLABORATOR`
+- denied: `VIEWER`, deleted collection, unknown role
+
+## 4. Current State Summary
+
+### 4.1 Mobile behavior today
+
+Mobile already supports the following:
+
+| Case | File state | File owner | Destination owner | Mobile behavior |
+| --- | --- | --- | --- | --- |
+| 1 | Already uploaded | Current user | Current user | Add directly |
+| 2 | Already uploaded | Current user | Another user | Add directly |
+| 3 | Already uploaded | Another user | Current user | Reuse same-hash owned file if available, else copy directly |
+| 4 | Already uploaded | Another user | Another user | Reuse same-hash owned file if available, else copy to `uncategorized`, then add |
+| 5 | Not uploaded yet | N/A | Current user | Normal queued upload to destination |
+| 6 | Not uploaded yet | N/A | Another user | Force upload to `uncategorized`, then add |
+
+Additional mobile details that matter:
+
+- direct upload is owner-only via `CollectionsService.allowUpload(...)`
+- `_addToCollection(...)` rejects other-owned files
+- `_validateCopyInput(...)` rejects copy destinations not owned by the actor
+- `addOrCopyToCollection(...)` is the main parity primitive
+- mobile skips duplicate memberships already present in the destination
+
+### 4.2 Web behavior today
+
+Web already has some useful pieces:
+
+- participant roles including `ADMIN` are modeled and surfaced
+- incoming shared albums are already classified as viewer / collaborator / admin
+- `"add"` target selection already allows collaborator/admin incoming shared albums
+- upload service already returns useful success result types:
+ - `alreadyUploaded`
+ - `addedSymlink`
+ - `uploaded`
+ - `uploadedWithStaticThumbnail`
+- `createUncategorizedCollection()` already exists
+
+Current parity gaps:
+
+- `CollectionSelector` action `"upload"` excludes incoming shared albums because it relies on `canMoveToCollection(...)`
+- drag-and-drop auto-targeting only works when the active collection is owned by the user
+- `pages/gallery.tsx` strips non-owned files before `"add"` and warns instead of applying mobile add/copy logic
+- `performCollectionOp(...)` is explicitly owner-only for add/move parity
+- `upload-manager.uploadItems(...)` returns only a boolean, not per-item upload results
+- web has no `/files/copy` wrapper and no `addOrCopyToCollection(...)` equivalent
+- web `addToCollection(...)` is remote-only and does not locally skip already-present memberships
+- duplicate suppression after copy parity is not implemented
+
+## 5. SRS
+
+### 5.1 Product goal
+
+A web user who is an `ADMIN` or `COLLABORATOR` in an incoming shared album must be able to:
+
+- upload new local files into that album, and
+- add existing Ente files into that album
+
+with the same ownership and copy semantics as mobile.
+
+### 5.2 Supported entry points
+
+The feature must work from every web flow that can currently initiate an album-targeted add/upload:
+
+- upload button with an active album in context
+- drag-and-drop while an incoming shared album is the active album
+- collection selector action `"upload"`
+- collection selector action `"add"`
+- single-file "add to album" flow from the file viewer
+- any direct `uploadManager.uploadFile(...)` caller that targets a collection
+
+Current known direct upload callers are:
+
+- `web/apps/photos/src/components/Upload.tsx`
+- `web/apps/photos/src/components/FileListWithViewer.tsx`
+
+### 5.3 Functional requirements
+
+#### FR-1 Permission gating
+
+- `OWNER` continues to use the existing direct upload/add behavior.
+- `ADMIN` and `COLLABORATOR` may upload/add to incoming shared albums.
+- `VIEWER` must not be allowed to upload/add.
+- Shared album upload must not be exposed through move-only affordances.
+
+#### FR-2 New local file to owned album
+
+- Existing web owned-album upload behavior must remain unchanged.
+- No `uncategorized` routing is needed when the destination is owned by the current user.
+
+#### FR-3 New local file to incoming shared album
+
+When the destination is an incoming shared album and the user is an `ADMIN` or `COLLABORATOR`, web must:
+
+1. resolve or create the user's own `uncategorized` collection,
+2. upload all local items to `uncategorized`,
+3. collect only successful upload results,
+4. add those resulting user-owned files to the target shared album,
+5. refresh remote state.
+
+Web must not upload local files directly into the incoming shared album.
+
+#### FR-4 Existing uploaded file owned by current user
+
+When the selected file is already uploaded and owned by the current user, web must:
+
+- add it directly to the destination shared album using `add-files`
+- skip items already present in the destination
+
+This applies whether the destination is owned by the current user or shared with them.
+
+#### FR-5 Existing uploaded file owned by another user
+
+When the selected file is already uploaded and owned by another user, web must follow mobile parity:
+
+1. check whether the current user already owns an equivalent file with the same hash and file type
+2. if such a file exists, add that owned file instead of copying
+3. otherwise copy the other-owned file
+
+Copy rules:
+
+- if destination is owned by the current user: copy directly into destination
+- if destination is an incoming shared album: copy into user's `uncategorized`, then add the copied file to the shared album
+
+Web must not attempt to add another user's file directly to a shared album.
+
+#### FR-6 Upload result handling
+
+For stage-1 local uploads routed through `uncategorized`, the second-stage add must use all successful results of type:
+
+- `alreadyUploaded`
+- `addedSymlink`
+- `uploaded`
+- `uploadedWithStaticThumbnail`
+
+The second-stage add must ignore per-item results of type:
+
+- `blocked`
+- `failed`
+- `unsupported`
+- `zeroSize`
+- `tooLarge`
+- `largerThanAvailableStorage`
+
+#### FR-7 Idempotency and duplicate handling
+
+The web flow must:
+
+- not create duplicate collection memberships in the destination
+- dedupe repeated file IDs before `add-files`
+- dedupe repeated source file IDs per source collection before `copy`
+- tolerate the same local file appearing multiple times in one upload batch
+
+#### FR-8 UX and progress
+
+- Existing upload progress UI must remain the single progress surface for contributor uploads.
+- Partial success is allowed.
+ Successfully uploaded or copied files should still be added to the shared album even if other items fail.
+- If stage 1 succeeds for some files but stage 2 fails, the uploaded/copied files may remain in `uncategorized`.
+ This is acceptable and matches the ownership-preserving model.
+- The user must see final shared album state only after a post-operation pull.
+ No optimistic shared album insertion is required.
+
+#### FR-9 Sync and local state
+
+Web must keep its current remote-first architecture:
+
+- collection mutation helpers remain remote operations
+- local album state is reconciled by `onRemotePull(...)`
+- no mobile-style local DB event bus or optimistic collection-row insertion is required for this feature
+
+#### FR-10 Duplicate suppression parity
+
+Web should add a parity mechanism similar to mobile's shared-copy suppression so that copy-based contributor flows do not create visibly doubled files in aggregate library views.
+
+This is not a blocker for the base contributor upload flow, but it is required for full UX parity with mobile.
+
+### 5.4 Non-functional requirements
+
+- No server API changes.
+- Preserve existing E2EE rules by always re-encrypting the file key with the destination collection key at each add/copy step.
+- Reuse current upload concurrency and progress infrastructure.
+- Keep behavior deterministic across refreshes by ending every successful mutation flow with a pull.
+
+### 5.5 Acceptance criteria
+
+The feature is accepted only if all of the following pass:
+
+- contributor can upload a brand-new local file to an incoming shared album
+- contributor can add an already uploaded user-owned file to an incoming shared album
+- contributor can add an already uploaded other-owned file to an incoming shared album with same-hash reuse or copy-via-`uncategorized`
+- viewer cannot perform any of the above
+- move-to-shared-album remains unsupported
+- duplicate requests do not create duplicate memberships in the target album
+
+## 6. HLD
+
+### 6.1 Design overview
+
+The web design should mirror the mobile logic, but keep the current web architecture:
+
+- mobile style business rules
+- web style remote-first state sync
+- existing upload manager and progress UI
+
+The design has three main layers:
+
+1. capability helpers
+2. collection mutation parity helpers
+3. upload orchestration for contributor targets
+
+### 6.2 Proposed module changes
+
+| Module | Change | Why |
+| --- | --- | --- |
+| `web/packages/new/photos/services/collection-summary.ts` | Add a helper for "upload-capable destination" that includes incoming shared collaborator/admin albums. | `canMoveToCollection(...)` is the wrong predicate for upload. |
+| `web/packages/new/photos/components/CollectionSelector.tsx` | For action `"upload"`, use the new upload-capable predicate instead of move-only filtering. | Contributors must be able to pick incoming shared albums as upload targets. |
+| `web/apps/photos/src/components/Upload.tsx` | Replace owner-only active-album upload shortcut with contributor-aware routing. Add a dedicated branch for shared incoming contributor uploads. | Drag/drop and normal upload need the `uncategorized -> add` flow. |
+| `web/apps/photos/src/services/upload-manager.ts` | Return structured per-item upload results for a batch, not just a boolean. | Stage 2 needs the resulting `EnteFile`s from stage 1. |
+| `web/packages/new/photos/services/collection.ts` | Add `savedOrCreateUserUncategorizedCollection()`, `copyFiles(...)`, `addOrCopyToCollection(...)`, and duplicate filtering helpers. | This is the web equivalent of mobile `CollectionsService.addOrCopyToCollection(...)`. |
+| `web/apps/photos/src/pages/gallery.tsx` | For op `"add"`, stop dropping non-owned files; route the full selection into the new parity helper. Keep owner-only filtering for `"move"`, `"restore"`, `"unhide"` as appropriate. | Add parity for existing Ente files. |
+| `web/packages/new/photos/components/gallery/helpers.ts` | Update `performCollectionOp(...)` to use parity helpers for `"add"` and keep move semantics unchanged. | Existing helper explicitly documents the parity gap. |
+| `web/apps/photos/src/components/FileListWithViewer.tsx` | Reuse the same contributor upload routing helper for any direct collection-targeted upload path. | Avoid leaving edited-file or single-file upload flows inconsistent. |
+
+### 6.3 Proposed helper contracts
+
+The exact names can change, but the design should introduce primitives with these responsibilities:
+
+```ts
+canUploadToCollectionSummary(summary: CollectionSummary): boolean
+```
+
+- true for owner-owned uploadable collections
+- true for incoming shared `ADMIN` / `COLLABORATOR`
+- false for incoming shared `VIEWER`
+
+```ts
+savedOrCreateUserUncategorizedCollection(): Promise<Collection>
+```
+
+- returns the locally known user-owned `uncategorized` if present
+- otherwise creates it remotely and returns the created collection
+
+```ts
+copyFiles(
+ dstCollection: Collection,
+ files: EnteFile[],
+): Promise<EnteFile[]>
+```
+
+- groups input by `srcCollectionID`
+- re-encrypts file keys with `dstCollection.key`
+- calls `POST /files/copy`
+- returns copied `EnteFile`s with:
+ - new `file.id`
+ - `ownerID = currentUser.id`
+ - `collectionID = dstCollection.id`
+
+```ts
+addOrCopyToCollection(
+ dstCollection: Collection,
+ files: EnteFile[],
+): Promise<void>
+```
+
+- split into current-user-owned vs other-owned
+- skip items already present in destination
+- for other-owned:
+ - same-hash owned reuse if available
+ - otherwise copy directly or via `uncategorized` depending on destination ownership
+
+### 6.4 Upload batch result contract
+
+`upload-manager` needs to expose the actual `UploadResult` per item. The simplest shape is:
+
+```ts
+type UploadBatchItemResult = {
+ localID: number;
+ requestedCollectionID: number;
+ result: UploadResult;
+};
+
+type UploadBatchResult = {
+ processedAny: boolean;
+ itemResults: UploadBatchItemResult[];
+};
+```
+
+Key requirement:
+
+- `itemResults` must include `alreadyUploaded`
+- `itemResults` must include `addedSymlink`
+- the caller must be able to recover the resulting `EnteFile` for every successful item
+
+This is the main missing primitive needed for the two-stage contributor upload flow.
+
+### 6.5 Detailed flow A: new local upload to incoming shared album
+
+1. User selects files while an incoming shared album is the target.
+2. `Upload.tsx` detects that the target is contributor-uploadable but not owned by the current user.
+3. `Upload.tsx` resolves `savedOrCreateUserUncategorizedCollection()`.
+4. `Upload.tsx` rewrites the upload batch so stage 1 uploads into `uncategorized`.
+5. `uploadManager.uploadItems(...)` returns structured per-item results.
+6. `Upload.tsx` collects the successful `EnteFile`s from those results.
+7. `Upload.tsx` calls `addOrCopyToCollection(targetSharedAlbum, stage1Files)`.
+ In practice these files are already user-owned, so this becomes add-only.
+8. `Upload.tsx` performs `onRemotePull()` once the workflow completes.
+
+Why this matches mobile:
+
+- ownership is preserved
+- no direct upload into an incoming shared album
+- same UI progress surface remains in place
+
+### 6.6 Detailed flow B: add existing uploaded files to incoming shared album
+
+1. User selects files and chooses `"add to album"`.
+2. `pages/gallery.tsx` passes the full selected set for op `"add"`.
+3. `performCollectionOp("add", ...)` calls `addOrCopyToCollection(target, files)`.
+4. `addOrCopyToCollection(...)`:
+ - adds current-user-owned files directly
+ - for other-owned files:
+ - reuses same-hash owned files where possible
+ - otherwise copies via `uncategorized`
+5. Caller performs `remotePull({ silent: true })`.
+
+Why `pages/gallery.tsx` must change:
+
+- current code drops non-owned files before `"add"`
+- that behavior is the exact parity gap this feature needs to remove
+
+### 6.7 Detailed flow C: copy of other-owned files
+
+1. Group input files by `collectionID`.
+2. For each source collection:
+ - remove duplicate `file.id`s
+ - encrypt the file key with destination collection key
+ - call `/files/copy` with:
+ - `dstCollectionID`
+ - `srcCollectionID`
+ - `files`
+3. Rewrite local in-memory `EnteFile` copies using `oldToNewFileIDMap`.
+4. If the final target is an incoming shared album, call `addToCollection(...)` with the copied files after the copy-to-`uncategorized` step.
+
+### 6.8 Duplicate and lookup strategy
+
+For parity with mobile, the helper layer should:
+
+- build a set of file IDs already present in the destination collection
+- skip direct adds for those IDs
+- find current-user-owned same-hash equivalents using locally saved collection files
+- require same hash and same file type before reusing
+
+Recommended local sources:
+
+- `savedCollectionFiles()`
+- `savedNormalCollections()` / `savedAllCollections()`
+- `metadataHash(file.metadata)`
+
+### 6.9 State and sync model
+
+The design intentionally keeps web remote-first:
+
+- `addToCollection(...)` remains remote-only
+- `copyFiles(...)` can also remain remote-only from the perspective of persistent local state
+- all UI correctness after mutation comes from `remotePull`
+
+This is different from mobile, which updates local DB rows eagerly, but it fits existing web architecture and reduces risk.
+
+### 6.10 Error handling
+
+- Stage 1 upload errors remain handled by existing upload UI and notifications.
+- Stage 2 add/copy errors use existing generic error handling.
+- If only some items succeed in stage 1, only those items advance to stage 2.
+- If stage 2 fails after stage 1 succeeded, no rollback is required.
+ Successfully uploaded/copied files may remain in `uncategorized`.
+
+### 6.11 Test matrix
+
+#### Role matrix
+
+- owner of destination album: allowed
+- incoming shared admin: allowed
+- incoming shared collaborator: allowed
+- incoming shared viewer: denied
+
+#### File-state matrix
+
+- new local file -> owned album
+- new local file -> incoming shared album
+- existing uploaded user-owned file -> incoming shared album
+- existing uploaded other-owned file -> owned album
+- existing uploaded other-owned file -> incoming shared album
+
+#### Duplicate matrix
+
+- file already exists in target shared album
+- current user already owns same-hash equivalent in another collection
+- current user does not own same-hash equivalent and copy is required
+- same source file selected twice in one batch
+
+#### UX/state matrix
+
+- upload button path with active shared album
+- drag/drop path with active shared album
+- collection selector upload path
+- multi-select add-to-album path
+- single-file add-to-album path
+- partial success across stage 1 and stage 2
+
+### 6.12 Rollout order
+
+Recommended implementation order:
+
+1. add upload-capable destination helper and update `CollectionSelector`
+2. add structured upload batch results to `upload-manager`
+3. implement `savedOrCreateUserUncategorizedCollection()` and contributor upload routing in `Upload.tsx`
+4. implement `copyFiles(...)` and `addOrCopyToCollection(...)` in `collection.ts`
+5. switch `"add"` flows in `pages/gallery.tsx` and `gallery/helpers.ts` to the parity helper
+6. audit any direct `uploadManager.uploadFile(...)` callers
+7. add duplicate suppression parity in aggregate views
+
+## 7. Final Design Decision
+
+The web implementation must follow the mobile model exactly:
+
+- upload directly only when the target collection is owned by the actor
+- add directly only when the file is owned by the actor
+- copy only into a collection owned by the actor
+- for incoming shared contributor albums, use the actor's `uncategorized` collection as the bridge whenever direct upload/copy is invalid
+
+That is the correct design because it matches:
+
+- current mobile behavior,
+- current server constraints,
+- current ownership invariants.
diff --git a/web/apps/photos/src/components/FileListWithViewer.tsx b/web/apps/photos/src/components/FileListWithViewer.tsx
index 5dd07d3aeb..186e46e046 100644
--- a/web/apps/photos/src/components/FileListWithViewer.tsx
+++ b/web/apps/photos/src/components/FileListWithViewer.tsx
@@ -16,14 +16,23 @@ import type { Collection } from "ente-media/collection";
import type { EnteFile } from "ente-media/file";
import { fileCreationTime, fileFileName } from "ente-media/file-metadata";
import { useSettingsSnapshot } from "ente-new/photos/components/utils/use-snapshot";
-import { moveToTrash } from "ente-new/photos/services/collection";
+import {
+ addOrCopyToCollection,
+ canDirectlyUploadToCollection,
+ canUploadToCollection,
+ moveToTrash,
+ savedOrCreateUserUncategorizedCollection,
+} from "ente-new/photos/services/collection";
import type { CollectionSummary } from "ente-new/photos/services/collection-summary";
import { PseudoCollectionID } from "ente-new/photos/services/collection-summary";
import { updateMapEnabled } from "ente-new/photos/services/settings";
import { t } from "i18next";
import { useCallback, useEffect, useMemo, useState } from "react";
import AutoSizer from "react-virtualized-auto-sizer";
-import { uploadManager } from "services/upload-manager";
+import {
+ successfulFilesFromUploadBatchResult,
+ uploadManager,
+} from "services/upload-manager";
import {
FileList,
type FileListAnnotatedFile,
@@ -271,16 +280,60 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
const handleSaveEditedImageCopy = useMemo(() => {
if (!enableImageEditing) return undefined;
- return (
+ return async (
editedFile: File,
collection: Collection,
enteFile: EnteFile,
) => {
- uploadManager.prepareForNewUpload();
- uploadManager.showUploadProgressDialog();
- void uploadManager.uploadFile(editedFile, collection, enteFile);
+ let processedAny = false;
+ try {
+ await uploadManager.waitUntilIdle();
+ await onRemotePull();
+ uploadManager.prepareForNewUpload();
+ uploadManager.showUploadProgressDialog();
+
+ const uploadCollection = canDirectlyUploadToCollection(
+ collection,
+ )
+ ? collection
+ : canUploadToCollection(collection)
+ ? await savedOrCreateUserUncategorizedCollection()
+ : undefined;
+
+ if (!uploadCollection) {
+ throw new Error(
+ "Upload not allowed for the selected collection",
+ );
+ }
+
+ const batchResult = await uploadManager.uploadFile(
+ editedFile,
+ uploadCollection,
+ enteFile,
+ );
+ processedAny = batchResult.processedAny;
+ if (!processedAny) {
+ uploadManager.hideUploadProgressDialog();
+ return;
+ }
+
+ if (uploadCollection.id != collection.id) {
+ const uploadedFiles =
+ successfulFilesFromUploadBatchResult(batchResult);
+ if (uploadedFiles.length) {
+ await addOrCopyToCollection(collection, uploadedFiles);
+ }
+ }
+ await onRemotePull();
+ } catch (e) {
+ if (processedAny) {
+ await onRemotePull().catch(() => undefined);
+ }
+ uploadManager.hideUploadProgressDialog();
+ onGenericError(e);
+ }
};
- }, [enableImageEditing]);
+ }, [enableImageEditing, onGenericError, onRemotePull]);
const shouldShowMapButton =
modePlus !== "search" &&
diff --git a/web/apps/photos/src/components/Upload.tsx b/web/apps/photos/src/components/Upload.tsx
index 2a5b4ba2ef..d29f9ef441 100644
--- a/web/apps/photos/src/components/Upload.tsx
+++ b/web/apps/photos/src/components/Upload.tsx
@@ -58,12 +58,16 @@ import type { RemotePullOpts } from "ente-new/photos/components/gallery";
import { downloadAppDialogAttributes } from "ente-new/photos/components/utils/download";
import { suppressAutoLockOnBlurForTrustedPrompt } from "ente-new/photos/services/app-lock";
import {
+ addOrCopyToCollection,
+ canDirectlyUploadToCollection,
+ canUploadToCollection,
createAlbum,
createHiddenAlbum,
isHiddenCollection,
savedAllCollections,
savedHiddenCollections,
savedNormalCollections,
+ savedOrCreateUserUncategorizedCollection,
} from "ente-new/photos/services/collection";
import { redirectToCustomerPortal } from "ente-new/photos/services/user-details";
import { usePhotosAppContext } from "ente-new/photos/types/context";
@@ -73,11 +77,15 @@ import React, { useCallback, useEffect, useRef, useState } from "react";
import type {
InProgressUpload,
SegregatedFinishedUploads,
+ UploadBatchResult,
UploadCounter,
UploadFileNames,
UploadItemWithCollection,
} from "services/upload-manager";
-import { uploadManager } from "services/upload-manager";
+import {
+ successfulFilesFromUploadBatchResult,
+ uploadManager,
+} from "services/upload-manager";
import watcher from "services/watch";
import { hasReliableCanvasReadback } from "utils/upload/canvas-integrity";
import { CanvasReadbackBlockedDialog } from "./CanvasReadbackBlockedDialog";
@@ -270,6 +278,9 @@ export const Upload: React.FC<UploadProps> = ({
const currentUploadPromise = useRef<Promise<void> | undefined>(undefined);
const uploadRunning = useRef(false);
const isDragAndDrop = useRef(false);
+ const retrySharedAlbumUploadTarget = useRef<Collection | undefined>(
+ undefined,
+ );
/**
* `true` if we've activated one hidden {@link Inputs} that allow the user
@@ -340,6 +351,7 @@ export const Upload: React.FC<UploadProps> = ({
const handleCollectionSelectorCancel = () => {
uploadRunning.current = false;
+ retrySharedAlbumUploadTarget.current = undefined;
};
useEffect(() => {
@@ -545,7 +557,7 @@ export const Upload: React.FC<UploadProps> = ({
isDragAndDrop.current = false;
if (
props.activeCollection &&
- props.activeCollection.owner.id == user?.id
+ canUploadToCollection(props.activeCollection)
) {
uploadFilesToExistingCollection(props.activeCollection);
return;
@@ -580,20 +592,62 @@ export const Upload: React.FC<UploadProps> = ({
uploadManager.showUploadProgressDialog();
};
+ const handlePostUploadBatchResult = async (
+ batchResult: UploadBatchResult,
+ targetCollection: Collection | undefined,
+ ) => {
+ if (!targetCollection) return;
+
+ const uploadedFiles = successfulFilesFromUploadBatchResult(batchResult);
+ if (!uploadedFiles.length) return;
+
+ await addOrCopyToCollection(targetCollection, uploadedFiles);
+ };
+
+ const resetUploadUIState = () => {
+ props.setShouldDisableDropzone(false);
+ uploadRunning.current = false;
+ };
+
const uploadFilesToExistingCollection = async (collection: Collection) => {
preCollectionCreationAction();
- const uploadItemsWithCollection = uploadItemsAndPaths.current.map(
- ([uploadItem, path], index) => ({
- uploadItem,
- pathPrefix: uploadPathPrefix(path),
- localID: index,
- collectionID: collection.id,
- }),
- );
- await waitInQueueAndUploadFiles(uploadItemsWithCollection, [
- collection,
- ]);
- uploadItemsAndPaths.current = [];
+ try {
+ const uploadCollection = canDirectlyUploadToCollection(collection)
+ ? collection
+ : canUploadToCollection(collection)
+ ? await savedOrCreateUserUncategorizedCollection()
+ : undefined;
+
+ if (!uploadCollection) {
+ throw new Error("Upload not allowed for the selected album");
+ }
+
+ const uploadItemsWithCollection = uploadItemsAndPaths.current.map(
+ ([uploadItem, path], index) => ({
+ uploadItem,
+ pathPrefix: uploadPathPrefix(path),
+ localID: index,
+ collectionID: uploadCollection.id,
+ }),
+ );
+ await waitInQueueAndUploadFiles(
+ uploadItemsWithCollection,
+ [uploadCollection],
+ {
+ persistPendingUploads: uploadCollection.id == collection.id,
+ postUploadTargetCollection:
+ uploadCollection.id == collection.id
+ ? undefined
+ : collection,
+ },
+ );
+ uploadItemsAndPaths.current = [];
+ } catch (e) {
+ retrySharedAlbumUploadTarget.current = undefined;
+ closeUploadProgress();
+ resetUploadUIState();
+ onGenericError(e);
+ }
};
const uploadFilesToNewCollections = async (
@@ -657,22 +711,31 @@ export const Upload: React.FC<UploadProps> = ({
];
}
} catch (e) {
+ retrySharedAlbumUploadTarget.current = undefined;
closeUploadProgress();
+ resetUploadUIState();
onGenericError(e);
return;
}
- await waitInQueueAndUploadFiles(uploadItemsWithCollection, collections);
+ await waitInQueueAndUploadFiles(uploadItemsWithCollection, collections, {
+ persistPendingUploads: true,
+ postUploadTargetCollection: undefined,
+ });
uploadItemsAndPaths.current = [];
};
const waitInQueueAndUploadFiles = async (
uploadItemsWithCollection: UploadItemWithCollection[],
collections: Collection[],
+ opts?: {
+ persistPendingUploads?: boolean;
+ postUploadTargetCollection?: Collection;
+ },
) => {
const currentPromise = currentUploadPromise.current;
currentUploadPromise.current = (async () => {
if (currentPromise) await currentPromise;
- return uploadFiles(uploadItemsWithCollection, collections);
+ return uploadFiles(uploadItemsWithCollection, collections, opts);
})();
await currentUploadPromise.current;
};
@@ -686,18 +749,24 @@ export const Upload: React.FC<UploadProps> = ({
};
function postUploadAction() {
- props.setShouldDisableDropzone(false);
- uploadRunning.current = false;
+ resetUploadUIState();
void onRemotePull();
}
const uploadFiles = async (
uploadItemsWithCollection: UploadItemWithCollection[],
collections: Collection[],
+ opts?: {
+ persistPendingUploads?: boolean;
+ postUploadTargetCollection?: Collection;
+ },
) => {
try {
- preUploadAction();
+ retrySharedAlbumUploadTarget.current =
+ opts?.postUploadTargetCollection;
+ await preUploadAction();
if (
+ opts?.persistPendingUploads &&
electron &&
!isPendingDesktopUpload.current &&
!watcher.isUploadRunning()
@@ -710,11 +779,15 @@ export const Upload: React.FC<UploadProps> = ({
.filter((x) => x !== undefined),
);
}
- const wereFilesProcessed = await uploadManager.uploadItems(
+ const batchResult = await uploadManager.uploadItems(
uploadItemsWithCollection,
collections,
);
- if (!wereFilesProcessed) closeUploadProgress();
+ if (!batchResult.processedAny) closeUploadProgress();
+ await handlePostUploadBatchResult(
+ batchResult,
+ opts?.postUploadTargetCollection,
+ );
if (isDesktop) {
if (watcher.isUploadRunning()) {
await watcher.allFileUploadsDone(uploadItemsWithCollection);
@@ -739,7 +812,15 @@ export const Upload: React.FC<UploadProps> = ({
const { items, collections, parsedMetadataJSONMap } =
uploadManager.failedItemState();
await preUploadAction(parsedMetadataJSONMap);
- await uploadManager.uploadItems(items, collections);
+ const batchResult = await uploadManager.uploadItems(
+ items,
+ collections,
+ );
+ if (!batchResult.processedAny) closeUploadProgress();
+ await handlePostUploadBatchResult(
+ batchResult,
+ retrySharedAlbumUploadTarget.current,
+ );
} catch (e) {
log.error("Retrying failed uploads failed", e);
closeUploadProgress();
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index cdcdfce5fd..dfa059d340 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -971,17 +971,21 @@ const Page: React.FC = () => {
// If a selection is happening, there must be a user.
(f) => f.ownerID == user!.id,
);
+ const filesToProcess =
+ op == "add" ? selectedFiles : userFiles;
const sourceCollectionID = selected.collectionID;
- if (userFiles.length > 0) {
+ if (filesToProcess.length > 0) {
await performCollectionOp(
op,
selectedCollection,
- userFiles,
+ filesToProcess,
sourceCollectionID,
);
}
- // See: [Note: Add and move of non-user files]
- if (userFiles.length != selectedFiles.length) {
+ if (
+ op != "add" &&
+ userFiles.length != selectedFiles.length
+ ) {
showMiniDialog(notifyOthersFilesDialogAttributes());
}
clearSelection();
@@ -1006,13 +1010,14 @@ const Page: React.FC = () => {
async (name: string) => {
try {
const collection = await createAlbum(name);
+ const pendingSingleFile = pendingSingleFileAdd.current;
- if (pendingSingleFileAdd.current) {
+ if (pendingSingleFile) {
await performCollectionOp(
"add",
collection,
- [pendingSingleFileAdd.current.file],
- pendingSingleFileAdd.current.sourceCollectionSummaryID,
+ [pendingSingleFile.file],
+ pendingSingleFile.sourceCollectionSummaryID,
);
await remotePull({ silent: true });
@@ -1023,6 +1028,8 @@ const Page: React.FC = () => {
albumId: collection.id,
albumName: collection.name,
});
+ setPostCreateAlbumOp(undefined);
+ return;
}
setPostCreateAlbumOp((postCreateAlbumOp) => {
diff --git a/web/apps/photos/src/services/upload-manager.ts b/web/apps/photos/src/services/upload-manager.ts
index da05315a18..0edcc159fe 100644
--- a/web/apps/photos/src/services/upload-manager.ts
+++ b/web/apps/photos/src/services/upload-manager.ts
@@ -73,6 +73,32 @@ export type FinishedUploads = Map<FileID, FinishedUploadType>;
export type SegregatedFinishedUploads = Map<FinishedUploadType, FileID[]>;
+export interface UploadBatchItemResult {
+ localID: number;
+ requestedCollectionID: number;
+ result: UploadResult;
+}
+
+export interface UploadBatchResult {
+ processedAny: boolean;
+ itemResults: UploadBatchItemResult[];
+}
+
+export const successfulFilesFromUploadBatchResult = (
+ batchResult: UploadBatchResult,
+) =>
+ batchResult.itemResults.flatMap(({ result }) => {
+ switch (result.type) {
+ case "alreadyUploaded":
+ case "addedSymlink":
+ case "uploaded":
+ case "uploadedWithStaticThumbnail":
+ return [result.file];
+ default:
+ return [];
+ }
+ });
+
export interface ProgressUpdater {
setPercentComplete: React.Dispatch<React.SetStateAction<number>>;
setUploadCounter: React.Dispatch<React.SetStateAction<UploadCounter>>;
@@ -258,6 +284,7 @@ class UploadManager {
private itemsToBeUploaded: ClusteredUploadItem[] = [];
private failedItems: ClusteredUploadItem[] = [];
private existingFiles: EnteFile[] = [];
+ private itemResults: UploadBatchItemResult[] = [];
private onUploadFile: ((file: EnteFile) => void) | undefined;
private collections = new Map<number, Collection>();
private uploadInProgress = false;
@@ -293,6 +320,7 @@ class UploadManager {
) {
this.itemsToBeUploaded = [];
this.failedItems = [];
+ this.itemResults = [];
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.parsedMetadataJSONMap = parsedMetadataJSONMap ?? new Map();
this.shouldUploadBeCancelled = false;
@@ -326,12 +354,13 @@ class UploadManager {
* These are not all the user's collections - these are just the collections
* mentioned by one or more {@link itemsWithCollection}.
*
- * @returns `true` if at least one file was processed
+ * @returns A summary of the completed batch and the per-item upload
+ * results for the files that were attempted.
*/
public async uploadItems(
itemsWithCollection: UploadItemWithCollection[],
collections: Collection[],
- ) {
+ ): Promise<UploadBatchResult> {
if (this.uploadInProgress)
throw new Error("Cannot run multiple uploads at once");
@@ -390,7 +419,10 @@ class UploadManager {
clearInterval(logInterval);
}
- return this.uiService.hasFilesInResultList();
+ return {
+ processedAny: this.uiService.hasFilesInResultList(),
+ itemResults: [...this.itemResults],
+ };
}
/**
@@ -409,7 +441,7 @@ class UploadManager {
file: File,
collection: Collection,
sourceEnteFile: EnteFile,
- ) {
+ ): Promise<UploadBatchResult> {
const timestamp = fileCreationTime(sourceEnteFile);
const dateTime = sourceEnteFile.pubMagicMetadata?.data.dateTime;
const offset = sourceEnteFile.pubMagicMetadata?.data.offsetTime;
@@ -528,6 +560,11 @@ class UploadManager {
worker,
uploadContext,
);
+ this.itemResults.push({
+ localID,
+ requestedCollectionID: collectionID,
+ result: uploadResult,
+ });
const finishedUploadType = await this.postUploadTask(
uploadableItem,
@@ -603,6 +640,10 @@ class UploadManager {
};
}
+ public waitUntilIdle = async () => {
+ while (this.isUploadInProgress()) await wait(100);
+ };
+
private updateExistingFiles(file: EnteFile) {
this.existingFiles.push(file);
this.onUploadFile!(file);
diff --git a/web/packages/new/photos/components/CollectionSelector.tsx b/web/packages/new/photos/components/CollectionSelector.tsx
index fd6734a897..398f8757c6 100644
--- a/web/packages/new/photos/components/CollectionSelector.tsx
+++ b/web/packages/new/photos/components/CollectionSelector.tsx
@@ -29,6 +29,7 @@ import {
import {
canAddToCollection,
canMoveToCollection,
+ canUploadToCollection,
collectionsSortBy,
sortCollectionSummaries,
type CollectionsSortBy,
@@ -167,7 +168,7 @@ export const CollectionSelector: React.FC<CollectionSelectorProps> = ({
return canAddToCollection(cs) && cs.type != "userFavorites";
} else if (attributes.action == "upload") {
return (
- (canMoveToCollection(cs) ||
+ (canUploadToCollection(cs) ||
cs.type == "uncategorized") &&
cs.type != "userFavorites"
);
@@ -265,7 +266,7 @@ export const CollectionSelector: React.FC<CollectionSelectorProps> = ({
<Stack sx={{ flex: 1 }}>
<Box>
<Typography variant="h5">
- {titleForAction(action)}
+ {titleForAction(action)}dd
</Typography>
<Typography
variant="small"
diff --git a/web/packages/new/photos/components/gallery/helpers.ts b/web/packages/new/photos/components/gallery/helpers.ts
index 749393ad08..2af67edd10 100644
--- a/web/packages/new/photos/components/gallery/helpers.ts
+++ b/web/packages/new/photos/components/gallery/helpers.ts
@@ -16,7 +16,7 @@ import { type Collection } from "ente-media/collection";
import { type EnteFile } from "ente-media/file";
import { type CollectionOp } from "ente-new/photos/components/SelectedFileOptions";
import {
- addToCollection,
+ addOrCopyToCollection,
moveFromCollection,
moveToCollection,
restoreToCollection,
@@ -75,9 +75,8 @@ export const findCollectionCreatingUncategorizedIfNeeded = async (
* @param selectedCollection The existing or new collection selected by the
* user. This serves as the target of the operation.
*
- * @param selectedUserFiles The files selected by the user, on which the
- * operation should be performed. Currently these need to all belong to the
- * user.
+ * @param selectedFiles The files selected by the user, on which the operation
+ * should be performed.
*
* @param sourceCollectionID In the case of a "move", the operation is always
* expected to happen in the context of an existing collection, which serves as
@@ -87,38 +86,40 @@ export const findCollectionCreatingUncategorizedIfNeeded = async (
*
* [Note: Add and move of non-user files]
*
- * Currently, all {@link selectedUserFiles} need to belong to the user. This is
- * because adds and move cannot be performed on remote across ownership
- * boundaries directly.
+ * Adds can now operate on both owned and non-owned files using the same parity
+ * semantics as mobile:
*
- * Enhancement: The mobile client has support for adding and moving such files.
- * It does so by creating a copy, but using hash checks to avoid a copy if not
- * needed. Implement these. This is a bit non-trivial since the mobile client
- * then also adds various heuristics to omit the display of the "doubled" files
- * in the all section etc.
+ * - current-user-owned files are added directly,
+ * - other-owned files reuse a same-hash owned file when available,
+ * - otherwise they are copied directly or via uncategorized depending on the
+ * destination ownership.
+ *
+ * Move semantics remain owner-only. Remote does not support cross-ownership
+ * moves, and mobile also models shared-album contributor flows as adds, not
+ * moves.
*/
export const performCollectionOp = async (
op: CollectionOp,
selectedCollection: Collection,
- selectedUserFiles: EnteFile[],
+ selectedFiles: EnteFile[],
sourceCollectionID: number | undefined,
): Promise<void> => {
switch (op) {
case "add":
- await addToCollection(selectedCollection, selectedUserFiles);
+ await addOrCopyToCollection(selectedCollection, selectedFiles);
break;
case "move":
await moveFromCollection(
sourceCollectionID!,
selectedCollection,
- selectedUserFiles,
+ selectedFiles,
);
break;
case "restore":
- await restoreToCollection(selectedCollection, selectedUserFiles);
+ await restoreToCollection(selectedCollection, selectedFiles);
break;
case "unhide":
- await moveToCollection(selectedCollection, selectedUserFiles);
+ await moveToCollection(selectedCollection, selectedFiles);
break;
}
};
diff --git a/web/packages/new/photos/components/gallery/reducer.ts b/web/packages/new/photos/components/gallery/reducer.ts
index dddbaf75bd..4c0d174beb 100644
--- a/web/packages/new/photos/components/gallery/reducer.ts
+++ b/web/packages/new/photos/components/gallery/reducer.ts
@@ -12,6 +12,7 @@ import {
import type { EnteFile } from "ente-media/file";
import {
isArchivedFile,
+ metadataHash,
type FilePrivateMagicMetadataData,
} from "ente-media/file-metadata";
import type { MagicMetadata } from "ente-media/magic-metadata";
@@ -1858,12 +1859,17 @@ const stateForUpdatedCollectionFiles = (
const stateByUpdatingFilteredFiles = (state: GalleryState) => {
if (state.isInSearchMode) {
const searchFiles = state.searchResults ?? state.filteredFiles;
+ const visibleSearchFiles = suppressSharedFilesSavedByUser(
+ searchFiles,
+ state.user?.id,
+ state.view?.type == "albums" ? state.view.activeCollection : undefined,
+ );
// Only apply time-based sorting if user explicitly selected a sort order.
// When undefined, keep original order (preserves CLIP relevance sorting).
const filteredFiles =
state.searchSortAsc !== undefined
- ? sortFiles([...searchFiles], state.searchSortAsc)
- : searchFiles;
+ ? sortFiles([...visibleSearchFiles], state.searchSortAsc)
+ : visibleSearchFiles;
return { ...state, filteredFiles };
} else if (
state.view?.type == "albums" ||
@@ -1879,6 +1885,7 @@ const stateByUpdatingFilteredFiles = (state: GalleryState) => {
state.tempDeletedFileIDs,
state.tempHiddenFileIDs,
state.view,
+ state.user?.id,
);
return { ...state, filteredFiles };
} else if (state.view?.type == "people") {
@@ -1886,6 +1893,7 @@ const stateByUpdatingFilteredFiles = (state: GalleryState) => {
state.collectionFiles,
state.hiddenFileIDs,
state.view,
+ state.user?.id,
);
return { ...state, filteredFiles };
} else {
@@ -1907,6 +1915,7 @@ const deriveAlbumsOrHiddenAlbumsFilteredFiles = (
tempDeletedFileIDs: GalleryState["tempDeletedFileIDs"],
tempHiddenFileIDs: GalleryState["tempHiddenFileIDs"],
view: Extract<GalleryView, { type: "albums" | "hidden-albums" }>,
+ currentUserID: number | undefined,
) => {
const activeCollectionSummaryID = view.activeCollectionSummaryID;
@@ -1980,7 +1989,11 @@ const deriveAlbumsOrHiddenAlbumsFilteredFiles = (
return activeCollectionSummaryID == file.collectionID;
});
- return sortAndUniqueFilteredFiles(filteredFiles, view.activeCollection);
+ return sortAndUniqueFilteredFiles(
+ filteredFiles,
+ view.activeCollection,
+ currentUserID,
+ );
};
/**
@@ -1994,12 +2007,42 @@ const deriveAlbumsOrHiddenAlbumsFilteredFiles = (
const sortAndUniqueFilteredFiles = (
files: EnteFile[],
activeCollection: Collection | undefined,
+ currentUserID: number | undefined,
) => {
- const uniqueFiles = uniqueFilesByID(files);
+ const uniqueFiles = uniqueFilesByID(
+ suppressSharedFilesSavedByUser(files, currentUserID, activeCollection),
+ );
const sortAsc = activeCollection?.pubMagicMetadata?.data.asc ?? false;
return sortAsc ? sortFiles(uniqueFiles, true) : uniqueFiles;
};
+const suppressSharedFilesSavedByUser = (
+ files: EnteFile[],
+ currentUserID: number | undefined,
+ activeCollection: Collection | undefined,
+) => {
+ if (!currentUserID || activeCollection) return files;
+
+ const ownedFileKeys = new Set<string>();
+ for (const file of files) {
+ if (file.ownerID != currentUserID) continue;
+ const hash = metadataHash(file.metadata);
+ if (!hash) continue;
+ ownedFileKeys.add(`${hash}:${file.metadata.fileType}`);
+ }
+
+ if (!ownedFileKeys.size) return files;
+
+ return files.filter((file) => {
+ if (file.ownerID == currentUserID) return true;
+
+ const hash = metadataHash(file.metadata);
+ if (!hash) return true;
+
+ return !ownedFileKeys.has(`${hash}:${file.metadata.fileType}`);
+ });
+};
+
/**
* Compute the sorted list of files to show when we're in the "people" view and
* the dependencies change.
@@ -2008,14 +2051,19 @@ const derivePeopleFilteredFiles = (
collectionFiles: GalleryState["collectionFiles"],
hiddenFileIDs: GalleryState["hiddenFileIDs"],
view: Extract<GalleryView, { type: "people" }>,
+ currentUserID: number | undefined,
) => {
const pfSet = new Set(view.activePerson?.fileIDs ?? []);
return uniqueFilesByID(
- collectionFiles.filter((f) => {
- if (!pfSet.has(f.id)) return false;
- if (hiddenFileIDs.has(f.id)) return false;
- return true;
- }),
+ suppressSharedFilesSavedByUser(
+ collectionFiles.filter((f) => {
+ if (!pfSet.has(f.id)) return false;
+ if (hiddenFileIDs.has(f.id)) return false;
+ return true;
+ }),
+ currentUserID,
+ undefined,
+ ),
);
};
diff --git a/web/packages/new/photos/services/collection-summary.ts b/web/packages/new/photos/services/collection-summary.ts
index 0ce77e61ca..090d300fc7 100644
--- a/web/packages/new/photos/services/collection-summary.ts
+++ b/web/packages/new/photos/services/collection-summary.ts
@@ -224,6 +224,9 @@ export const haveOnlySystemCollections = (
export const canAddToCollection = ({ attributes }: CollectionSummary) =>
!attributes.has("system") && !attributes.has("sharedIncomingViewer");
+export const canUploadToCollection = (summary: CollectionSummary) =>
+ canAddToCollection(summary);
+
export const canMoveToCollection = ({ attributes }: CollectionSummary) =>
!attributes.has("system") && !attributes.has("sharedIncoming");
diff --git a/web/packages/new/photos/services/collection.ts b/web/packages/new/photos/services/collection.ts
index 69bf36ca54..74e249bcaa 100644
--- a/web/packages/new/photos/services/collection.ts
+++ b/web/packages/new/photos/services/collection.ts
@@ -549,6 +549,29 @@ interface CollectionFileItem {
keyDecryptionNonce: string;
}
+const CopyFilesResponse = z.object({
+ oldToNewFileIDMap: z.record(z.string(), z.number()),
+});
+
+const currentUserRoleInCollection = (collection: Collection) => {
+ const userID = ensureLocalUser().id;
+ if (collection.owner.id == userID) return "OWNER";
+ return collection.sharees.find((sharee) => sharee.id == userID)?.role;
+};
+
+export const canAddFilesToCollection = (collection: Collection) => {
+ const role = currentUserRoleInCollection(collection);
+ return (
+ role == "OWNER" || role == "ADMIN" || role == "COLLABORATOR"
+ );
+};
+
+export const canUploadToCollection = (collection: Collection) =>
+ canAddFilesToCollection(collection);
+
+export const canDirectlyUploadToCollection = (collection: Collection) =>
+ collection.owner.id == ensureLocalUser().id;
+
/**
* Make a remote request to add the given {@link files} to the given
* {@link collection}.
@@ -654,6 +677,221 @@ export const moveFromCollection = async (
);
});
+const uniqueFilesByID = (files: EnteFile[]) => {
+ const seen = new Set<number>();
+ const uniqueFiles: EnteFile[] = [];
+
+ for (const file of files) {
+ if (seen.has(file.id)) continue;
+ seen.add(file.id);
+ uniqueFiles.push(file);
+ }
+
+ return uniqueFiles;
+};
+
+const fileIDsInCollection = (
+ collectionID: number,
+ collectionFiles: EnteFile[],
+): Set<number> =>
+ new Set(
+ collectionFiles
+ .filter((file) => file.collectionID == collectionID)
+ .map((file) => file.id),
+ );
+
+const hashAndTypeKey = (file: EnteFile) => {
+ const hash = metadataHash(file.metadata);
+ if (!hash) return undefined;
+ return `${hash}:${file.metadata.fileType}`;
+};
+
+const userOwnedEquivalentFilesByHashAndType = (
+ files: EnteFile[],
+ currentUserID: number,
+) => {
+ const equivalents = new Map<string, EnteFile>();
+
+ for (const file of files) {
+ if (file.ownerID != currentUserID) continue;
+
+ const key = hashAndTypeKey(file);
+ if (!key || equivalents.has(key)) continue;
+ equivalents.set(key, file);
+ }
+
+ return equivalents;
+};
+
+export const copyFiles = async (
+ dstCollection: Collection,
+ files: EnteFile[],
+): Promise<EnteFile[]> => {
+ if (!files.length) return [];
+
+ const currentUserID = ensureLocalUser().id;
+ if (dstCollection.owner.id != currentUserID) {
+ throw new Error("Destination collection must be owned by the actor");
+ }
+
+ const uniqueFiles = uniqueFilesByID(files);
+ const copiedFiles: EnteFile[] = [];
+
+ for (const [srcCollectionID, sourceFiles] of groupFilesByCollectionID(
+ uniqueFiles,
+ ).entries()) {
+ await batched(sourceFiles, async (batchFiles) => {
+ if (
+ batchFiles.some(
+ (file) =>
+ file.ownerID == currentUserID ||
+ file.collectionID != srcCollectionID,
+ )
+ ) {
+ throw new Error(
+ "Can only copy files owned by other users from the source collection",
+ );
+ }
+
+ const encryptedFileKeys = await encryptWithCollectionKey(
+ dstCollection,
+ batchFiles,
+ );
+ const res = await fetch(await apiURL("/files/copy"), {
+ method: "POST",
+ headers: await authenticatedRequestHeaders(),
+ body: JSON.stringify({
+ dstCollectionID: dstCollection.id,
+ srcCollectionID,
+ files: encryptedFileKeys,
+ }),
+ });
+ ensureOk(res);
+
+ const { oldToNewFileIDMap } = CopyFilesResponse.parse(
+ await res.json(),
+ );
+
+ for (const file of batchFiles) {
+ const copiedFileID = oldToNewFileIDMap[file.id.toString()];
+ if (!copiedFileID) {
+ throw new Error(`Failed to copy file ${file.id}`);
+ }
+
+ copiedFiles.push({
+ ...file,
+ id: copiedFileID,
+ ownerID: currentUserID,
+ collectionID: dstCollection.id,
+ });
+ }
+ });
+ }
+
+ return copiedFiles;
+};
+
+export const savedUserUncategorizedCollection = async () => {
+ const userID = ensureLocalUser().id;
+ return (await savedCollections()).find(
+ (collection) =>
+ collection.type == "uncategorized" && collection.owner.id == userID,
+ );
+};
+
+export const savedOrCreateUserUncategorizedCollection = async () =>
+ (await savedUserUncategorizedCollection()) ??
+ createUncategorizedCollection();
+
+export const addOrCopyToCollection = async (
+ dstCollection: Collection,
+ files: EnteFile[],
+) => {
+ if (!files.length) return;
+ if (!canAddFilesToCollection(dstCollection)) {
+ throw new Error("Current user cannot add files to this collection");
+ }
+
+ const currentUserID = ensureLocalUser().id;
+ const collectionFiles = await savedCollectionFiles();
+ const destinationFileIDs = fileIDsInCollection(
+ dstCollection.id,
+ collectionFiles,
+ );
+ const filesMissingFromDestination = uniqueFilesByID(files).filter(
+ (file) => !destinationFileIDs.has(file.id),
+ );
+
+ if (!filesMissingFromDestination.length) return;
+
+ const [ownedFiles, otherOwnedFiles] = splitByPredicate(
+ filesMissingFromDestination,
+ (file) => file.ownerID == currentUserID,
+ );
+
+ if (ownedFiles.length) {
+ await addToCollection(dstCollection, ownedFiles);
+ ownedFiles.forEach((file) => destinationFileIDs.add(file.id));
+ }
+
+ if (!otherOwnedFiles.length) return;
+
+ const userOwnedFilesByHashAndType = userOwnedEquivalentFilesByHashAndType(
+ collectionFiles,
+ currentUserID,
+ );
+
+ const filesToAdd: EnteFile[] = [];
+ const filesToCopy: EnteFile[] = [];
+ const seenAddFileIDs = new Set<number>();
+ const seenCopyFileIDs = new Set<number>();
+
+ for (const file of otherOwnedFiles) {
+ const fileHashAndTypeKey = hashAndTypeKey(file);
+ const userOwnedEquivalent = fileHashAndTypeKey
+ ? userOwnedFilesByHashAndType.get(fileHashAndTypeKey)
+ : undefined;
+ const shouldAddOwnedEquivalent = !!userOwnedEquivalent;
+
+ if (shouldAddOwnedEquivalent) {
+ if (!seenAddFileIDs.has(userOwnedEquivalent.id)) {
+ seenAddFileIDs.add(userOwnedEquivalent.id);
+ filesToAdd.push(userOwnedEquivalent);
+ }
+ } else if (!seenCopyFileIDs.has(file.id)) {
+ seenCopyFileIDs.add(file.id);
+ filesToCopy.push(file);
+ }
+ }
+
+ const reusableOwnedFiles = uniqueFilesByID(filesToAdd).filter(
+ (file) => !destinationFileIDs.has(file.id),
+ );
+ if (reusableOwnedFiles.length) {
+ await addToCollection(dstCollection, reusableOwnedFiles);
+ reusableOwnedFiles.forEach((file) => destinationFileIDs.add(file.id));
+ }
+
+ if (!filesToCopy.length) return;
+
+ const copyDestination = canDirectlyUploadToCollection(dstCollection)
+ ? dstCollection
+ : await savedOrCreateUserUncategorizedCollection();
+ const copiedFiles = await copyFiles(copyDestination, filesToCopy);
+
+ if (copyDestination.id != dstCollection.id) {
+ const filesToAddAfterCopy = uniqueFilesByID(copiedFiles).filter(
+ (file) => !destinationFileIDs.has(file.id),
+ );
+ if (filesToAddAfterCopy.length) {
+ await addToCollection(dstCollection, filesToAddAfterCopy);
+ filesToAddAfterCopy.forEach((file) =>
+ destinationFileIDs.add(file.id),
+ );
+ }
+ }
+};
+
/**
* Return an array of {@link CollectionFileItem}s, one for each file in
* {@link files}, containing the corresponding file' ID and keys, but this time