Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat(Upload):add-pre-upload-progress

Aswin Asok1ea7e47ef5a5
diff --git a/web/apps/photos/src/components/Upload.tsx b/web/apps/photos/src/components/Upload.tsx
index f4b49c3775..e9b57d4a5d 100644
--- a/web/apps/photos/src/components/Upload.tsx
+++ b/web/apps/photos/src/components/Upload.tsx
@@ -5,6 +5,7 @@
/* eslint-disable @typescript-eslint/no-floating-promises */
import { DefaultOptionsV2 } from "@/components/DefaultOptionsV2";
import { TakeoutOptionsV2 } from "@/components/TakeoutOptionsV2";
+import { UploadConfirmationDialog } from "@/components/UploadConfirmationDialog";
import type {
InProgressUpload,
SegregatedFinishedUploads,
@@ -16,6 +17,7 @@ import type {
import {
favoritedFilesFromUploadBatchResult,
successfulFilesFromUploadBatchResult,
+ uploadableMediaCount,
uploadManager,
} from "@/services/upload-manager";
import watcher from "@/services/watch";
@@ -175,6 +177,13 @@ interface UploadFilesOptions {
postUploadTargetCollection?: Collection;
}
+interface NewCollectionsOptions {
+ collectionName?: string;
+ includeHiddenCollections?: boolean;
+ createHidden?: boolean;
+ skipConfirmation?: boolean;
+}
+
/**
* Top level component that houses the infrastructure for handling uploads.
*/
@@ -215,6 +224,13 @@ export const Upload: React.FC<UploadProps> = ({
const [percentComplete, setPercentComplete] = useState(0);
const [hasLivePhotos, setHasLivePhotos] = useState(false);
const [prefilledNewAlbumName, setPrefilledNewAlbumName] = useState("");
+ const [uploadConfirmation, setUploadConfirmation] = useState<{
+ fileCount: number;
+ albumCount: number;
+ isTakeout: boolean;
+ importFavorites: boolean;
+ resolve: (confirmed: boolean) => void;
+ }>();
const [openCollectionMappingChoice, setOpenCollectionMappingChoice] =
useState(false);
@@ -225,6 +241,7 @@ export const Upload: React.FC<UploadProps> = ({
show: showNewAlbumNameInput,
props: newAlbumNameInputVisibilityProps,
} = useModalVisibility();
+ const didSubmitNewAlbumName = useRef(false);
/**
* {@link File}s that the user drag-dropped or selected for uploads (web).
@@ -304,6 +321,7 @@ export const Upload: React.FC<UploadProps> = ({
const currentUploadPromise = useRef<Promise<void> | undefined>(undefined);
const uploadRunning = useRef(false);
const isDragAndDrop = useRef(false);
+ const shouldImportTakeoutFavorites = useRef(true);
/**
* Used to remember a deferred "real destination" collectionf or the current upload flow.
@@ -594,14 +612,18 @@ export const Upload: React.FC<UploadProps> = ({
// Include hidden collections so watch folder syncs add
// files to existing hidden albums instead of creating new
// visible ones
- uploadFilesToNewCollections(
- "root",
- pendingDesktopUploadCollectionName.current,
- true,
- );
+ uploadFilesToNewCollections("root", {
+ collectionName:
+ pendingDesktopUploadCollectionName.current,
+ includeHiddenCollections: true,
+ skipConfirmation: true,
+ });
pendingDesktopUploadCollectionName.current = undefined;
} else {
- uploadFilesToNewCollections("parent", undefined, true);
+ uploadFilesToNewCollections("parent", {
+ includeHiddenCollections: true,
+ skipConfirmation: true,
+ });
}
return;
}
@@ -711,6 +733,8 @@ export const Upload: React.FC<UploadProps> = ({
batchResult: UploadBatchResult,
postUploadTargetCollection: Collection | undefined,
) => {
+ if (!shouldImportTakeoutFavorites.current) return;
+
// Checking if any of the uploaded items have their takeoutFavorited as true.
if (
!batchResult.itemResults.some(
@@ -783,8 +807,19 @@ export const Upload: React.FC<UploadProps> = ({
collection: Collection,
uploadItemAndPaths: UploadItemAndPath[],
) => {
- preCollectionCreationAction();
try {
+ const uploadConfirmed = await confirmUpload(
+ [uploadItemAndPaths],
+ 1,
+ );
+
+ if (!uploadConfirmed) {
+ uploadItemsAndPaths.current = [];
+ resetUploadUIState();
+ return;
+ }
+
+ preCollectionCreationAction();
const uploadCollection = canDirectlyUploadToCollection(collection)
? collection
: canAddFilesToCollection(collection)
@@ -827,11 +862,18 @@ export const Upload: React.FC<UploadProps> = ({
const uploadFilesToNewCollections = async (
mapping: CollectionMapping,
- collectionName?: string,
- includeHiddenCollections?: boolean,
- createHidden?: boolean,
+ {
+ collectionName,
+ includeHiddenCollections,
+ createHidden,
+ skipConfirmation,
+ }: NewCollectionsOptions = {},
) => {
- preCollectionCreationAction();
+ if (skipConfirmation) {
+ shouldImportTakeoutFavorites.current = true;
+ preCollectionCreationAction();
+ }
+
let uploadItemsWithCollection: UploadItemWithCollection[] = [];
let collectionNameToUploadItems = new Map<
string,
@@ -850,6 +892,21 @@ export const Upload: React.FC<UploadProps> = ({
collectionName,
);
}
+
+ const uploadConfirmed =
+ skipConfirmation ||
+ (await confirmUpload(
+ [...collectionNameToUploadItems.values()],
+ collectionNameToUploadItems.size,
+ ));
+
+ if (!uploadConfirmed) {
+ uploadItemsAndPaths.current = [];
+ resetUploadUIState();
+ return;
+ }
+
+ if (!skipConfirmation) preCollectionCreationAction();
const collections: Collection[] = [];
try {
await onRemoteFilesPull();
@@ -903,6 +960,50 @@ export const Upload: React.FC<UploadProps> = ({
uploadItemsAndPaths.current = [];
};
+ async function confirmUpload(
+ itemGroups: UploadItemAndPath[][],
+ albumCount: number,
+ ): Promise<boolean> {
+ if (!isInternalUser) {
+ shouldImportTakeoutFavorites.current = true;
+ return true;
+ }
+
+ const { count: fileCount, isTakeout } =
+ await uploadableMediaCount(itemGroups);
+ return new Promise<boolean>((resolve) => {
+ setUploadConfirmation({
+ fileCount,
+ albumCount,
+ isTakeout,
+ importFavorites: true,
+ resolve,
+ });
+ });
+ }
+
+ const closeUploadConfirmation = (confirmed: boolean) => {
+ if (!confirmed) onCloseCollectionSelector?.();
+ if (confirmed) {
+ shouldImportTakeoutFavorites.current =
+ uploadConfirmation?.importFavorites ?? true;
+ }
+ uploadConfirmation?.resolve(confirmed);
+ setUploadConfirmation(undefined);
+ };
+
+ const handleUploadConfirmation = () => closeUploadConfirmation(true);
+ const handleUploadConfirmationCancel = () => closeUploadConfirmation(false);
+ const handleImportFavoritesChange = (
+ _event: React.ChangeEvent<HTMLInputElement>,
+ checked: boolean,
+ ) =>
+ setUploadConfirmation((confirmation) =>
+ confirmation
+ ? { ...confirmation, importFavorites: checked }
+ : undefined,
+ );
+
const waitInQueueAndUploadFiles = async (
uploadItemsWithCollection: UploadItemWithCollection[],
collections: Collection[],
@@ -1053,12 +1154,20 @@ export const Upload: React.FC<UploadProps> = ({
};
const uploadToSingleNewCollection = (collectionName: string) => {
- uploadFilesToNewCollections(
- "root",
+ didSubmitNewAlbumName.current = true;
+ uploadFilesToNewCollections("root", {
collectionName,
- undefined,
- props.isInHiddenSection,
- );
+ createHidden: props.isInHiddenSection,
+ });
+ };
+
+ const handleNewAlbumNameInputClose = () => {
+ newAlbumNameInputVisibilityProps.onClose();
+ if (!didSubmitNewAlbumName.current) {
+ onCloseCollectionSelector?.();
+ handleCollectionSelectorCancel();
+ }
+ didSubmitNewAlbumName.current = false;
};
const cancelUploads = () => {
@@ -1091,13 +1200,12 @@ export const Upload: React.FC<UploadProps> = ({
};
const handleCollectionMappingSelect = (mapping: CollectionMapping) =>
- uploadFilesToNewCollections(
- mapping,
- importSuggestion.rootFolderName ||
+ uploadFilesToNewCollections(mapping, {
+ collectionName:
+ importSuggestion.rootFolderName ||
t("autogenerated_default_album_name"),
- undefined,
- props.isInHiddenSection,
- );
+ createHidden: props.isInHiddenSection,
+ });
return (
<>
@@ -1158,8 +1266,23 @@ export const Upload: React.FC<UploadProps> = ({
open={showCanvasReadbackBlockedDialog}
onClose={() => setShowCanvasReadbackBlockedDialog(false)}
/>
+ {isInternalUser && (
+ <UploadConfirmationDialog
+ open={!!uploadConfirmation}
+ isTakeout={uploadConfirmation?.isTakeout ?? false}
+ fileCount={uploadConfirmation?.fileCount ?? 0}
+ albumCount={uploadConfirmation?.albumCount ?? 0}
+ importFavorites={
+ uploadConfirmation?.importFavorites ?? true
+ }
+ onImportFavoritesChange={handleImportFavoritesChange}
+ onConfirm={handleUploadConfirmation}
+ onCancel={handleUploadConfirmationCancel}
+ />
+ )}
<SingleInputDialog
{...newAlbumNameInputVisibilityProps}
+ onClose={handleNewAlbumNameInputClose}
title={t("new_album")}
label={t("album_name")}
initialValue={prefilledNewAlbumName}
diff --git a/web/apps/photos/src/components/UploadConfirmationDialog.tsx b/web/apps/photos/src/components/UploadConfirmationDialog.tsx
new file mode 100644
index 0000000000..04efa8f533
--- /dev/null
+++ b/web/apps/photos/src/components/UploadConfirmationDialog.tsx
@@ -0,0 +1,331 @@
+import {
+ ArrowLeft02Icon,
+ Cancel01Icon,
+ StarIcon,
+ Tick02Icon,
+} from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import {
+ Box,
+ Dialog,
+ IconButton,
+ Stack,
+ Typography,
+ type Theme,
+} from "@mui/material";
+import { EnteSwitch } from "ente-base/components/EnteSwitch";
+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
+import type { ChangeEvent, ReactElement } from "react";
+
+interface UploadConfirmationDialogProps {
+ open: boolean;
+ /**
+ * `true` if the items being uploaded were detected to be a Google Takeout
+ * import (Takeout metadata JSONs were found amongst them).
+ */
+ isTakeout: boolean;
+ fileCount: number;
+ albumCount: number;
+ importFavorites: boolean;
+ onImportFavoritesChange: (
+ event: ChangeEvent<HTMLInputElement>,
+ checked: boolean,
+ ) => void;
+ onConfirm: () => void;
+ onCancel: () => void;
+}
+
+export function UploadConfirmationDialog({
+ open,
+ isTakeout,
+ fileCount,
+ albumCount,
+ importFavorites,
+ onImportFavoritesChange,
+ onConfirm,
+ onCancel,
+}: UploadConfirmationDialogProps): ReactElement {
+ return (
+ <Dialog
+ open={open}
+ onClose={onCancel}
+ maxWidth={false}
+ aria-labelledby="upload-confirmation-title"
+ slotProps={{ paper: { sx: paperSx } }}
+ >
+ <Stack sx={contentSx}>
+ <Stack direction="row" sx={headerSx}>
+ <Stack direction="row" sx={headerTitleSx}>
+ <IconButton
+ aria-label="Back"
+ onClick={onCancel}
+ sx={backButtonSx}
+ >
+ <HugeiconsIcon icon={ArrowLeft02Icon} size={24} />
+ </IconButton>
+ <Typography sx={displayTitleSx}>
+ {isTakeout
+ ? "Import from Google Photos"
+ : "Upload to Ente"}
+ </Typography>
+ </Stack>
+ <IconButton
+ aria-label="Close"
+ onClick={onCancel}
+ sx={closeButtonSx}
+ >
+ <HugeiconsIcon icon={Cancel01Icon} size={18} />
+ </IconButton>
+ </Stack>
+
+ <Stack sx={mainSx}>
+ <Stack sx={{ gap: "20px" }}>
+ <Stack sx={readySx}>
+ <Box aria-hidden sx={successIllustrationSx}>
+ <Box sx={successIconSx}>
+ <HugeiconsIcon
+ icon={Tick02Icon}
+ size={26}
+ strokeWidth={2.5}
+ />
+ </Box>
+ </Box>
+ <Typography
+ id="upload-confirmation-title"
+ component="h2"
+ sx={displayTitleSx}
+ >
+ {isTakeout
+ ? "Ready to import!"
+ : "Ready to upload!"}
+ </Typography>
+ </Stack>
+
+ <Stack direction="row" sx={statsSx}>
+ <StatCard
+ value={fileCount}
+ label="photos and videos found"
+ />
+ <StatCard value={albumCount} label="albums found" />
+ </Stack>
+ </Stack>
+
+ {isTakeout && (
+ <Stack sx={{ gap: "20px" }}>
+ <Typography component="h3" sx={sectionTitleSx}>
+ More options
+ </Typography>
+ <Stack direction="row" sx={optionSx}>
+ <Box sx={optionIconSx}>
+ <HugeiconsIcon icon={StarIcon} size={18} />
+ </Box>
+ <Stack sx={optionTextSx}>
+ <Typography sx={bodySx}>
+ Favourites
+ </Typography>
+ <Typography sx={captionSx}>
+ Carry over your favourites from Google
+ Photos
+ </Typography>
+ </Stack>
+ <EnteSwitch
+ color="accent"
+ checked={importFavorites}
+ onChange={onImportFavoritesChange}
+ slotProps={{
+ input: { "aria-label": "Favourites" },
+ }}
+ sx={switchSx}
+ />
+ </Stack>
+ </Stack>
+ )}
+ </Stack>
+
+ <FocusVisibleButton
+ fullWidth
+ color="accent"
+ onClick={onConfirm}
+ sx={confirmButtonSx}
+ >
+ {isTakeout ? "Start import" : "Start upload"}
+ </FocusVisibleButton>
+ </Stack>
+ </Dialog>
+ );
+}
+
+function StatCard({ value, label }: { value: number; label: string }) {
+ return (
+ <Stack sx={statCardSx}>
+ <Typography sx={statValueSx}>{value.toLocaleString()}</Typography>
+ <Typography sx={captionSx}>{label}</Typography>
+ </Stack>
+ );
+}
+
+/* primary/default in the design */
+const green = "#08c225";
+
+const paperSx = (theme: Theme) => ({
+ width: "min(607px, calc(100svw - 32px))",
+ maxWidth: "none",
+ border: "1px solid #e0e0e0",
+ borderRadius: "20px",
+ backgroundColor: "#f4f4f4",
+ backgroundImage: "none",
+ boxShadow: "none",
+ overflow: "hidden",
+ ...theme.applyStyles("dark", {
+ borderColor: "rgba(255 255 255 / 0.12)",
+ backgroundColor: "#1b1b1b",
+ }),
+});
+
+const contentSx = { p: "20px", gap: "36px", color: "text.base" };
+
+const headerSx = {
+ alignItems: "center",
+ justifyContent: "space-between",
+ gap: 2,
+ minWidth: 0,
+};
+
+const headerTitleSx = { alignItems: "center", gap: 1, minWidth: 0 };
+
+const backButtonSx = {
+ width: 38,
+ height: 38,
+ flexShrink: 0,
+ p: 0,
+ color: "text.base",
+};
+
+const closeButtonSx = (theme: Theme) => ({
+ width: 38,
+ height: 38,
+ flexShrink: 0,
+ p: 0,
+ color: "text.base",
+ backgroundColor: "background.paper",
+ "&:hover": { backgroundColor: "fill.faintHover" },
+ ...theme.applyStyles("dark", {
+ backgroundColor: "rgba(255 255 255 / 0.12)",
+ }),
+});
+
+const displayTitleSx = {
+ minWidth: 0,
+ fontFamily: "'Outfit', sans-serif",
+ fontSize: 24,
+ fontWeight: 600,
+ lineHeight: "32px",
+ overflowWrap: "anywhere",
+};
+
+const mainSx = { gap: 3, minWidth: 0 };
+
+const readySx = { alignItems: "center", gap: "10px", textAlign: "center" };
+
+const successIllustrationSx = (theme: Theme) => ({
+ display: "flex",
+ width: 80,
+ height: 80,
+ alignItems: "center",
+ justifyContent: "center",
+ borderRadius: "50%",
+ backgroundColor: "#ddeedf",
+ ...theme.applyStyles("dark", { backgroundColor: "rgba(8 194 37 / 0.16)" }),
+});
+
+const successIconSx = {
+ display: "flex",
+ width: 40,
+ height: 40,
+ alignItems: "center",
+ justifyContent: "center",
+ borderRadius: "50%",
+ color: "#fff",
+ backgroundColor: green,
+};
+
+const statsSx = { gap: "10px", minWidth: 0 };
+
+const statCardSx = (theme: Theme) => ({
+ flex: "1 1 0",
+ minWidth: 0,
+ px: "20px",
+ py: "12px",
+ gap: "4px",
+ borderRadius: "16px",
+ backgroundColor: "#fff",
+ ...theme.applyStyles("dark", { backgroundColor: "#282828" }),
+});
+
+const statValueSx = {
+ fontSize: 16,
+ fontWeight: 600,
+ lineHeight: "20px",
+ fontVariantNumeric: "tabular-nums",
+};
+
+const captionSx = {
+ color: "text.muted",
+ fontSize: 12,
+ fontWeight: 500,
+ lineHeight: "16px",
+};
+
+const sectionTitleSx = { fontSize: 18, fontWeight: 600, lineHeight: "24px" };
+
+const optionSx = (theme: Theme) => ({
+ minHeight: 60,
+ alignItems: "center",
+ gap: "12px",
+ pl: "12px",
+ pr: "16px",
+ py: "12px",
+ borderRadius: "20px",
+ backgroundColor: "#fff",
+ ...theme.applyStyles("dark", { backgroundColor: "#282828" }),
+});
+
+const optionIconSx = {
+ display: "flex",
+ width: 36,
+ height: 36,
+ flexShrink: 0,
+ alignItems: "center",
+ justifyContent: "center",
+ color: "text.muted",
+};
+
+const optionTextSx = { flex: 1, minWidth: 0, gap: "4px" };
+
+const switchSx = {
+ width: 36,
+ height: 21,
+ flexShrink: 0,
+ "& .MuiSwitch-switchBase": {
+ m: "2px",
+ "&.Mui-checked": { transform: "translateX(15px)" },
+ },
+ "& .MuiSwitch-thumb": { width: 17, height: 17 },
+};
+
+const bodySx = { fontSize: 14, fontWeight: 500, lineHeight: "20px" };
+
+const confirmButtonSx = {
+ minHeight: 52,
+ px: 3,
+ py: "14px",
+ borderRadius: "20px",
+ color: "#fff",
+ backgroundColor: green,
+ boxShadow: "none",
+ fontSize: 14,
+ fontWeight: 500,
+ lineHeight: "20px",
+ textTransform: "none",
+ "&:hover": { backgroundColor: "#07ad21", boxShadow: "none" },
+};
diff --git a/web/apps/photos/src/services/upload-manager.ts b/web/apps/photos/src/services/upload-manager.ts
index a2a84faf0e..d50d17fafc 100644
--- a/web/apps/photos/src/services/upload-manager.ts
+++ b/web/apps/photos/src/services/upload-manager.ts
@@ -10,7 +10,9 @@ import { ComlinkWorker } from "ente-base/worker/comlink-worker";
import {
markUploadedAndObtainProcessableItem,
shouldDisableCFUploadProxy,
+ uploadPathPrefix,
type ClusteredUploadItem,
+ type UploadItemAndPath,
type UploadPhase,
type UploadResult,
type UploadableUploadItem,
@@ -874,6 +876,47 @@ const clusterLivePhotos = async (
return result;
};
+export const uploadableMediaCount = async (
+ itemGroups: UploadItemAndPath[][],
+): Promise<{ count: number; isTakeout: boolean }> => {
+ let localID = 0;
+ const namedItems = itemGroups.flatMap((items, collectionID) =>
+ items.map(([uploadItem, path]) =>
+ makeUploadItemWithCollectionIDAndName({
+ localID: localID++,
+ collectionID,
+ uploadItem,
+ pathPrefix: uploadPathPrefix(path),
+ }),
+ ),
+ );
+ const [metadataItems, mediaItems] = splitMetadataAndMediaItems(namedItems);
+ const parsedMetadataJSONMap = new Map<string, ParsedMetadataJSON>();
+
+ for (const {
+ uploadItem,
+ pathPrefix,
+ collectionID,
+ fileName,
+ } of metadataItems) {
+ const metadataJSON = await tryParseTakeoutMetadataJSON(uploadItem!);
+ if (metadataJSON) {
+ parsedMetadataJSONMap.set(
+ metadataJSONMapKeyForJSON(pathPrefix, collectionID, fileName),
+ metadataJSON,
+ );
+ }
+ }
+
+ return {
+ count: (await clusterLivePhotos(mediaItems, parsedMetadataJSONMap))
+ .length,
+ // The presence of Takeout metadata JSONs amongst the uploaded items
+ // indicates that this is a Google Takeout import.
+ isTakeout: parsedMetadataJSONMap.size > 0,
+ };
+};
+
/**
* Add logs if our usage increases some high water mark. This is solely so that
* we have some indication in the logs if we get a user report of OOM crashes.