Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

feat(retry):download-album-retry-added

Aswin Asokfe169356ac72
diff --git a/web/apps/photos/src/components/DownloadStatusNotifications.tsx b/web/apps/photos/src/components/DownloadStatusNotifications.tsx
index 2546a43aa6..c7626a1daf 100644
--- a/web/apps/photos/src/components/DownloadStatusNotifications.tsx
+++ b/web/apps/photos/src/components/DownloadStatusNotifications.tsx
@@ -4,6 +4,7 @@ import {
isSaveCompleteWithErrors,
type SaveGroup,
} from "ente-gallery/components/utils/save-groups";
+import ReplayIcon from "@mui/icons-material/Replay";
import { Notification } from "ente-new/photos/components/Notification";
import { t } from "i18next";
@@ -86,31 +87,40 @@ export const DownloadStatusNotifications: React.FC<
}
};
- return saveGroups.map((group, index) => (
- <Notification
- key={group.id}
- horizontal="left"
- sx={{ "&&": { bottom: `${index * 80 + 20}px` } }}
- open={true}
- onClose={createOnClose(group)}
- keepOpenOnClick
- attributes={{
- color: isSaveCompleteWithErrors(group)
- ? "critical"
- : "secondary",
- title: isSaveCompleteWithErrors(group)
- ? t("download_failed")
- : isSaveComplete(group)
- ? t("download_complete")
- : t("downloading_album", { name: group.title }),
- caption: isSaveComplete(group)
- ? group.title
- : t("download_progress", {
- count: group.success + group.failed,
- total: group.total,
- }),
- onClick: createOnClick(group),
- }}
- />
- ));
+ return saveGroups.map((group, index) => {
+ const hasErrors = isSaveCompleteWithErrors(group);
+ const canRetry = hasErrors && !!group.retry;
+
+ return (
+ <Notification
+ key={group.id}
+ horizontal="left"
+ sx={{ "&&": { bottom: `${index * 80 + 20}px` } }}
+ open={true}
+ onClose={createOnClose(group)}
+ keepOpenOnClick
+ attributes={{
+ color: hasErrors ? "critical" : "secondary",
+ title: hasErrors
+ ? t("download_failed")
+ : isSaveComplete(group)
+ ? t("download_complete")
+ : t("downloading_album", { name: group.title }),
+ caption: isSaveComplete(group)
+ ? group.title
+ : t("download_progress", {
+ count: group.success + group.failed,
+ total: group.total,
+ }),
+ onClick: createOnClick(group),
+ endIcon: canRetry ? (
+ <ReplayIcon titleAccess={t("retry")} />
+ ) : undefined,
+ onEndIconClick: canRetry
+ ? () => group.retry?.()
+ : undefined,
+ }}
+ />
+ );
+ });
};
diff --git a/web/packages/gallery/components/utils/save-groups.ts b/web/packages/gallery/components/utils/save-groups.ts
index ace1c98b8b..e944685282 100644
--- a/web/packages/gallery/components/utils/save-groups.ts
+++ b/web/packages/gallery/components/utils/save-groups.ts
@@ -20,6 +20,10 @@ export interface SaveGroup {
* A randomly generated unique identifier of this set of saves.
*/
id: number;
+ /**
+ * A callback to retry the download that created this save group.
+ */
+ retry?: () => void;
/**
* The user visible title of the save group.
*
@@ -106,6 +110,7 @@ export type AddSaveGroup = (
| "downloadDirPath"
| "total"
| "canceller"
+ | "retry"
>,
) => UpdateSaveGroup;
diff --git a/web/packages/gallery/services/save.md b/web/packages/gallery/services/save.md
new file mode 100644
index 0000000000..e1cd90925f
--- /dev/null
+++ b/web/packages/gallery/services/save.md
@@ -0,0 +1,45 @@
+# `save.ts` download and save flow
+
+Line-by-line detail of `downloadFiles` and its helpers (line numbers from `web/packages/gallery/services/save.ts`).
+
+## Entry wrappers
+
+- L42-L46 `downloadAndSaveFiles`: exported helper; takes `files`, `title`, and `onAddSaveGroup`, and delegates to `downloadAndSave` with no collection context.
+- L64-L78 `downloadAndSaveCollectionFiles`: collects collection name/ID/hidden flag, then calls `downloadAndSave` with those so the desktop path can nest exports under a collection-named folder.
+
+## Core orchestrator: `downloadAndSave` (L83-L175)
+
+- L91 grabs `globalThis.electron` to detect desktop vs web.
+- L93 captures `total` count; L94-L98 aborts with `assertionFailed()` if no files.
+- L100-L114 desktop-only setup: asks the user to pick a directory; if they cancel, exits; if a collection name is provided, creates a safe subfolder via `mkdirCollectionDownloadFolder` and uses that path for saves.
+- L116-L119 allocates shared state: an `AbortController`, `failedFiles` list, `isDownloading` guard, and a placeholder `updateSaveGroup`.
+- L121-L156 defines `downloadFiles(filesToDownload, resetFailedCount = false)`:
+ - L125 short-circuits when nothing to do or a download is already running.
+ - L127 sets the running guard; L128-L130 **if `resetFailedCount` is `true`**, the UI’s `failed` count is reset to `0` via `updateSaveGroup`. This flag is only set when retrying after prior failures so the user sees a fresh failed-counter for that retry attempt.
+ - L131 clears previous failures.
+ - L134-L148 loops each file; L135 stops early if aborted.
+ - L137-L141 chooses desktop writer (`saveFileDesktop`) when electron/dir are present, otherwise browser writer (`saveAsFile`).
+ - L142 increments UI success count on completion.
+ - L144-L147 logs failures, records the file for retry, and increments UI failed count.
+ - L150-L152 clears the UI `retry` action when there were no failures.
+ - L153-L155 finally-block drops the running guard so retries can proceed.
+- L158-L162 defines `retry`: if there are failures, no active download, and not aborted, it clones `failedFiles` and calls `downloadFiles` with `resetFailedCount = true`.
+- L164-L172 registers the save-group notification via `onAddSaveGroup`, passing title/collection info, chosen directory, total count, the `canceller`, and `retry`; stores the returned `updateSaveGroup` setter.
+- L174-L175 kicks off the initial pass by awaiting `downloadFiles(files)`.
+
+## Browser save path
+
+- L180-L196 `saveAsFile(file)`: fetches blob data via `downloadManager.fileBlob`; resolves a download name with `fileFileName`. For live photos (L183 check), decodes into image/video parts with `decodeLivePhoto`, saves the image first (L187), waits 300 ms to appease Safari’s multiple-download quirk (L189-L192), then saves the video (L192). Non-live saves the single blob (L194).
+- L201-L204 `saveBlobPartAsFile(blobPart, fileName)`: builds a typed object URL via `createTypedObjectURL`, then hands it to `saveAsFileAndRevokeObjectURL` so the browser downloads it and the URL is revoked afterward.
+- L206-L210 `createTypedObjectURL(blobPart, fileName)`: normalizes the part into a `Blob`, detects MIME using `detectFileTypeInfo` on a temporary `File`, and returns an object URL built with that MIME type.
+
+## Desktop save path
+
+- L220-L236 `mkdirCollectionDownloadFolder({ fs }, downloadDirPath, collectionName)`: generates a collision-safe folder name with `safeDirectoryName`, joins it to the chosen directory, creates it with `fs.mkdirIfNeeded`, and returns the resulting path.
+- L254-L289 `saveFileDesktop(electron, file, directoryPath)`: writes directly to disk.
+ - L259 caches `fs` from electron.
+ - L261-L262 `createExportName` uses `safeFileName` to avoid name collisions in `directoryPath`.
+ - L264-L267 `writeStreamToFile` writes a stream to `directoryPath/exportName` via `writeStream`.
+ - L269 pulls a streaming response for the file via `downloadManager.fileStream`; L270 resolves the export name with `fileFileName`.
+ - L272-L285 live photo branch: decodes to image/video; writes the image first (L275-L276). The video write (L278-L281) is wrapped in try/catch; on failure, the already-written image is removed (L283) before rethrowing (L284).
+ - L286-L288 non-live branch: writes the single stream to disk with a collision-safe name.
diff --git a/web/packages/gallery/services/save.ts b/web/packages/gallery/services/save.ts
index 72cf8cd021..a5d15d1339 100644
--- a/web/packages/gallery/services/save.ts
+++ b/web/packages/gallery/services/save.ts
@@ -15,7 +15,10 @@ import {
safeFileName,
} from "ente-new/photos/utils/native-fs";
import { wait } from "ente-utils/promise";
-import type { AddSaveGroup } from "../components/utils/save-groups";
+import type {
+ AddSaveGroup,
+ UpdateSaveGroup,
+} from "../components/utils/save-groups";
/**
* Save the given {@link files} to the user's device.
@@ -111,30 +114,64 @@ const downloadAndSave = async (
}
const canceller = new AbortController();
+ const failedFiles: EnteFile[] = [];
+ let isDownloading = false;
+ let updateSaveGroup: UpdateSaveGroup = () => undefined;
- const updateSaveGroup = onAddSaveGroup({
+ const downloadFiles = async (
+ filesToDownload: EnteFile[],
+ resetFailedCount = false,
+ ) => {
+ if (!filesToDownload.length || isDownloading) return;
+
+ isDownloading = true;
+ if (resetFailedCount) {
+ updateSaveGroup((g) => ({ ...g, failed: 0 }));
+ }
+ failedFiles.length = 0;
+
+ try {
+ for (const file of filesToDownload) {
+ if (canceller.signal.aborted) break;
+ try {
+ if (electron && downloadDirPath) {
+ await saveFileDesktop(electron, file, downloadDirPath);
+ } else {
+ await saveAsFile(file);
+ }
+ updateSaveGroup((g) => ({ ...g, success: g.success + 1 }));
+ } catch (e) {
+ log.error("File download failed", e);
+ failedFiles.push(file);
+ updateSaveGroup((g) => ({ ...g, failed: g.failed + 1 }));
+ }
+ }
+
+ if (!failedFiles.length) {
+ updateSaveGroup((g) => ({ ...g, retry: undefined }));
+ }
+ } finally {
+ isDownloading = false;
+ }
+ };
+
+ const retry = () => {
+ if (!failedFiles.length || isDownloading || canceller.signal.aborted)
+ return;
+ void downloadFiles([...failedFiles], true);
+ };
+
+ updateSaveGroup = onAddSaveGroup({
title,
collectionSummaryID,
isHiddenCollectionSummary,
downloadDirPath,
total,
canceller,
+ retry,
});
- for (const file of files) {
- if (canceller.signal.aborted) break;
- try {
- if (electron && downloadDirPath) {
- await saveFileDesktop(electron, file, downloadDirPath);
- } else {
- await saveAsFile(file);
- }
- updateSaveGroup((g) => ({ ...g, success: g.success + 1 }));
- } catch (e) {
- log.error("File download failed", e);
- updateSaveGroup((g) => ({ ...g, failed: g.failed + 1 }));
- }
- }
+ await downloadFiles(files);
};
/**
diff --git a/web/packages/new/photos/components/Notification.tsx b/web/packages/new/photos/components/Notification.tsx
index 5b59331474..26ecfc7db0 100644
--- a/web/packages/new/photos/components/Notification.tsx
+++ b/web/packages/new/photos/components/Notification.tsx
@@ -65,6 +65,13 @@ export interface NotificationAttributes {
* button in this position).
*/
endIcon?: React.ReactNode;
+ /**
+ * Optional handler when {@link endIcon} is clicked.
+ *
+ * If not provided, clicks on the end icon behave the same as clicking the
+ * notification body.
+ */
+ onEndIconClick?: () => void;
}
type NotificationProps = ModalVisibilityProps & {
@@ -120,8 +127,16 @@ export const Notification: React.FC<NotificationProps> = ({
}) => {
if (!attributes) return <></>;
- const { captionFirst, color, startIcon, title, caption, endIcon, onClick } =
- attributes;
+ const {
+ captionFirst,
+ color,
+ startIcon,
+ title,
+ caption,
+ endIcon,
+ onClick,
+ onEndIconClick,
+ } = attributes;
const handleClose: React.MouseEventHandler = (event) => {
onClose();
@@ -133,6 +148,15 @@ export const Notification: React.FC<NotificationProps> = ({
if (!keepOpenOnClick) onClose();
};
+ const handleEndIconClick: React.MouseEventHandler = (event) => {
+ event.stopPropagation();
+ if (onEndIconClick) {
+ onEndIconClick();
+ } else {
+ handleClick();
+ }
+ };
+
return (
<Snackbar
open={open}
@@ -214,6 +238,7 @@ export const Notification: React.FC<NotificationProps> = ({
{endIcon ? (
<IconButton
component="div"
+ onClick={handleEndIconClick}
sx={{ fontSize: "36px", bgcolor: "fill.faint" }}
>
{endIcon}