Skip to content

armgit / ente

Public Imported from GitHub
0

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

refacator: imports

httpjamesm48fc246062bb
diff --git a/apps/cast/src/constants/ffmpeg.ts b/apps/cast/src/constants/ffmpeg.ts
new file mode 100644
index 0000000000..008b09784e
--- /dev/null
+++ b/apps/cast/src/constants/ffmpeg.ts
@@ -0,0 +1,3 @@
+export const INPUT_PATH_PLACEHOLDER = 'INPUT';
+export const FFMPEG_PLACEHOLDER = 'FFMPEG';
+export const OUTPUT_PATH_PLACEHOLDER = 'OUTPUT';
diff --git a/apps/cast/src/pages/_app.tsx b/apps/cast/src/pages/_app.tsx
index e614a74d18..29ae42c3b7 100644
--- a/apps/cast/src/pages/_app.tsx
+++ b/apps/cast/src/pages/_app.tsx
@@ -1,4 +1,3 @@
-import '/styles/globals.css';
import type { AppProps } from 'next/app';
export default function App({ Component, pageProps }: AppProps) {
diff --git a/apps/cast/src/pages/index.tsx b/apps/cast/src/pages/index.tsx
index 43d85eb36b..a5fd1705d9 100644
--- a/apps/cast/src/pages/index.tsx
+++ b/apps/cast/src/pages/index.tsx
@@ -1,118 +1,10 @@
-import Head from 'next/head';
-import Image from 'next/image';
-import { Inter } from 'next/font/google';
-import styles from '/styles/Home.module.css';
+// import { Inter } from 'next/font/google';
+// import { useEffect } from 'react';
+// import { syncCollections } from 'services/collectionService';
+// import { syncFiles } from 'services/fileService';
-const inter = Inter({ subsets: ['latin'] });
+// const inter = Inter({ subsets: ['latin'] });
export default function Home() {
- return (
- <>
- <Head>
- <title>Create Next App</title>
- <meta
- name="description"
- content="Generated by create next app"
- />
- <meta
- name="viewport"
- content="width=device-width, initial-scale=1"
- />
- <link rel="icon" href="/favicon.ico" />
- </Head>
- <main className={`${styles.main} ${inter.className}`}>
- <div className={styles.description}>
- <p>
- Get started by editing&nbsp;
- <code className={styles.code}>src/pages/index.tsx</code>
- </p>
- <div>
- <a
- href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
- target="_blank"
- rel="noopener noreferrer">
- By{' '}
- <Image
- src="/vercel.svg"
- alt="Vercel Logo"
- className={styles.vercelLogo}
- width={100}
- height={24}
- priority
- />
- </a>
- </div>
- </div>
-
- <div className={styles.center}>
- <Image
- className={styles.logo}
- src="/next.svg"
- alt="Next.js Logo"
- width={180}
- height={37}
- priority
- />
- </div>
-
- <div className={styles.grid}>
- <a
- href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
- className={styles.card}
- target="_blank"
- rel="noopener noreferrer">
- <h2>
- Docs <span>-&gt;</span>
- </h2>
- <p>
- Find in-depth information about Next.js features
- and&nbsp;API.
- </p>
- </a>
-
- <a
- href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
- className={styles.card}
- target="_blank"
- rel="noopener noreferrer">
- <h2>
- Learn <span>-&gt;</span>
- </h2>
- <p>
- Learn about Next.js in an interactive course
- with&nbsp;quizzes!
- </p>
- </a>
-
- <a
- href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
- className={styles.card}
- target="_blank"
- rel="noopener noreferrer">
- <h2>
- Templates <span>-&gt;</span>
- </h2>
- <p>
- Discover and deploy boilerplate example
- Next.js&nbsp;projects.
- </p>
- </a>
-
- <a
- href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
- className={styles.card}
- target="_blank"
- rel="noopener noreferrer">
- <h2>
- Deploy <span>-&gt;</span>
- </h2>
- <p>
- Instantly deploy your Next.js site to a shareable
- URL with&nbsp;Vercel.
- </p>
- </a>
- </div>
- </main>
- </>
- );
+ return <></>;
}
diff --git a/apps/cast/src/services/cache/cacheStorageFactory.ts b/apps/cast/src/services/cache/cacheStorageFactory.ts
new file mode 100644
index 0000000000..bb007977c7
--- /dev/null
+++ b/apps/cast/src/services/cache/cacheStorageFactory.ts
@@ -0,0 +1,41 @@
+import { LimitedCacheStorage } from 'types/cache/index';
+// import { ElectronCacheStorage } from 'services/electron/cache';
+// import { runningInElectron, runningInWorker } from 'utils/common';
+// import { WorkerElectronCacheStorageService } from 'services/workerElectronCache/service';
+
+class cacheStorageFactory {
+ // workerElectronCacheStorageServiceInstance: WorkerElectronCacheStorageService;
+ getCacheStorage(): LimitedCacheStorage {
+ // if (runningInElectron()) {
+ // if (runningInWorker()) {
+ // if (!this.workerElectronCacheStorageServiceInstance) {
+ // // this.workerElectronCacheStorageServiceInstance =
+ // // new WorkerElectronCacheStorageService();
+ // }
+ // return this.workerElectronCacheStorageServiceInstance;
+ // } else {
+ // // return ElectronCacheStorage;
+ // }
+ // } else {
+ return transformBrowserCacheStorageToLimitedCacheStorage(caches);
+ // }
+ }
+}
+
+export const CacheStorageFactory = new cacheStorageFactory();
+
+function transformBrowserCacheStorageToLimitedCacheStorage(
+ caches: CacheStorage
+): LimitedCacheStorage {
+ return {
+ async open(cacheName) {
+ const cache = await caches.open(cacheName);
+ return {
+ match: cache.match.bind(cache),
+ put: cache.put.bind(cache),
+ delete: cache.delete.bind(cache),
+ };
+ },
+ delete: caches.delete.bind(caches),
+ };
+}
diff --git a/apps/cast/src/services/cache/cacheStorageService.ts b/apps/cast/src/services/cache/cacheStorageService.ts
new file mode 100644
index 0000000000..adb9731dd9
--- /dev/null
+++ b/apps/cast/src/services/cache/cacheStorageService.ts
@@ -0,0 +1,33 @@
+import { logError } from 'utils/sentry';
+import { CacheStorageFactory } from './cacheStorageFactory';
+
+const SecurityError = 'SecurityError';
+const INSECURE_OPERATION = 'The operation is insecure.';
+async function openCache(cacheName: string) {
+ try {
+ return await CacheStorageFactory.getCacheStorage().open(cacheName);
+ } catch (e) {
+ // ignoring insecure operation error, as it is thrown in incognito mode in firefox
+ if (e.name === SecurityError && e.message === INSECURE_OPERATION) {
+ // no-op
+ } else {
+ // log and ignore, we don't want to break the caller flow, when cache is not available
+ logError(e, 'openCache failed');
+ }
+ }
+}
+async function deleteCache(cacheName: string) {
+ try {
+ return await CacheStorageFactory.getCacheStorage().delete(cacheName);
+ } catch (e) {
+ // ignoring insecure operation error, as it is thrown in incognito mode in firefox
+ if (e.name === SecurityError && e.message === INSECURE_OPERATION) {
+ // no-op
+ } else {
+ // log and ignore, we don't want to break the caller flow, when cache is not available
+ logError(e, 'deleteCache failed');
+ }
+ }
+}
+
+export const CacheStorageService = { open: openCache, delete: deleteCache };
diff --git a/apps/cast/src/services/downloadManager.ts b/apps/cast/src/services/downloadManager.ts
new file mode 100644
index 0000000000..b7d269e41d
--- /dev/null
+++ b/apps/cast/src/services/downloadManager.ts
@@ -0,0 +1,415 @@
+import { getToken } from 'utils/common/key';
+import { getFileURL, getThumbnailURL } from 'utils/common/apiUtil';
+import {
+ generateStreamFromArrayBuffer,
+ getRenderableFileURL,
+ createTypedObjectURL,
+} from 'utils/file';
+import HTTPService from './HTTPService';
+import { EnteFile } from 'types/file';
+
+import { logError } from 'utils/sentry';
+import { FILE_TYPE } from 'constants/file';
+import { CustomError } from 'utils/error';
+import ComlinkCryptoWorker from 'utils/comlink/ComlinkCryptoWorker';
+import { CacheStorageService } from './cache/cacheStorageService';
+import { CACHES } from 'constants/cache';
+import { Remote } from 'comlink';
+import { DedicatedCryptoWorker } from 'worker/crypto.worker';
+import { LimitedCache } from 'types/cache';
+import { retryAsyncFunction } from 'utils/network';
+import { addLogLine } from 'utils/logging';
+
+class DownloadManager {
+ private fileObjectURLPromise = new Map<
+ string,
+ Promise<{ original: string[]; converted: string[] }>
+ >();
+ private thumbnailObjectURLPromise = new Map<number, Promise<string>>();
+
+ private fileDownloadProgress = new Map<number, number>();
+
+ private progressUpdater: (value: Map<number, number>) => void = () => {};
+
+ private thumbnailCache: LimitedCache;
+
+ setProgressUpdater(progressUpdater: (value: Map<number, number>) => void) {
+ this.progressUpdater = progressUpdater;
+ }
+
+ private async getThumbnailCache() {
+ try {
+ if (!this.thumbnailCache) {
+ this.thumbnailCache = await CacheStorageService.open(
+ CACHES.THUMBS
+ );
+ }
+ return this.thumbnailCache;
+ } catch (e) {
+ return null;
+ // ignore
+ }
+ }
+
+ public async getCachedThumbnail(file: EnteFile) {
+ try {
+ const thumbnailCache = await this.getThumbnailCache();
+ const cacheResp: Response = await thumbnailCache?.match(
+ file.id.toString()
+ );
+
+ if (cacheResp) {
+ return URL.createObjectURL(await cacheResp.blob());
+ }
+ return null;
+ } catch (e) {
+ logError(e, 'failed to get cached thumbnail');
+ throw e;
+ }
+ }
+
+ public async getThumbnail(
+ file: EnteFile,
+ tokenOverride?: string,
+ usingWorker?: Remote<DedicatedCryptoWorker>,
+ timeout?: number
+ ) {
+ try {
+ const token = tokenOverride || getToken();
+ if (!token) {
+ return null;
+ }
+ if (!this.thumbnailObjectURLPromise.has(file.id)) {
+ const downloadPromise = async () => {
+ const thumbnailCache = await this.getThumbnailCache();
+ const cachedThumb = await this.getCachedThumbnail(file);
+ if (cachedThumb) {
+ return cachedThumb;
+ }
+ const thumb = await this.downloadThumb(
+ token,
+ file,
+ usingWorker,
+ timeout
+ );
+ const thumbBlob = new Blob([thumb]);
+
+ thumbnailCache
+ ?.put(file.id.toString(), new Response(thumbBlob))
+ .catch((e) => {
+ logError(e, 'cache put failed');
+ // TODO: handle storage full exception.
+ });
+ return URL.createObjectURL(thumbBlob);
+ };
+ this.thumbnailObjectURLPromise.set(file.id, downloadPromise());
+ }
+
+ return await this.thumbnailObjectURLPromise.get(file.id);
+ } catch (e) {
+ this.thumbnailObjectURLPromise.delete(file.id);
+ logError(e, 'get DownloadManager preview Failed');
+ throw e;
+ }
+ }
+
+ downloadThumb = async (
+ token: string,
+ file: EnteFile,
+ usingWorker?: Remote<DedicatedCryptoWorker>,
+ timeout?: number
+ ) => {
+ const resp = await HTTPService.get(
+ getThumbnailURL(file.id),
+ null,
+ { 'X-Auth-Token': token },
+ { responseType: 'arraybuffer', timeout }
+ );
+ if (typeof resp.data === 'undefined') {
+ throw Error(CustomError.REQUEST_FAILED);
+ }
+ const cryptoWorker =
+ usingWorker || (await ComlinkCryptoWorker.getInstance());
+ const decrypted = await cryptoWorker.decryptThumbnail(
+ new Uint8Array(resp.data),
+ await cryptoWorker.fromB64(file.thumbnail.decryptionHeader),
+ file.key
+ );
+ return decrypted;
+ };
+
+ getFile = async (file: EnteFile, forPreview = false) => {
+ const fileKey = forPreview ? `${file.id}_preview` : `${file.id}`;
+ try {
+ const getFilePromise = async () => {
+ const fileStream = await this.downloadFile(file);
+ const fileBlob = await new Response(fileStream).blob();
+ if (forPreview) {
+ return await getRenderableFileURL(file, fileBlob);
+ } else {
+ const fileURL = await createTypedObjectURL(
+ fileBlob,
+ file.metadata.title
+ );
+ return { converted: [fileURL], original: [fileURL] };
+ }
+ };
+ if (!this.fileObjectURLPromise.get(fileKey)) {
+ this.fileObjectURLPromise.set(fileKey, getFilePromise());
+ }
+ const fileURLs = await this.fileObjectURLPromise.get(fileKey);
+ return fileURLs;
+ } catch (e) {
+ this.fileObjectURLPromise.delete(fileKey);
+ logError(e, 'download manager Failed to get File');
+ throw e;
+ }
+ };
+
+ public async getCachedOriginalFile(file: EnteFile) {
+ return (await this.fileObjectURLPromise.get(file.id.toString()))
+ ?.original;
+ }
+
+ async downloadFile(
+ file: EnteFile,
+ tokenOverride?: string,
+ usingWorker?: Remote<DedicatedCryptoWorker>,
+ timeout?: number
+ ) {
+ try {
+ const cryptoWorker =
+ usingWorker || (await ComlinkCryptoWorker.getInstance());
+ const token = tokenOverride || getToken();
+ if (!token) {
+ return null;
+ }
+ const onDownloadProgress = this.trackDownloadProgress(
+ file.id,
+ file.info?.fileSize
+ );
+ if (
+ file.metadata.fileType === FILE_TYPE.IMAGE ||
+ file.metadata.fileType === FILE_TYPE.LIVE_PHOTO
+ ) {
+ const resp = await retryAsyncFunction(() =>
+ HTTPService.get(
+ getFileURL(file.id),
+ null,
+ { 'X-Auth-Token': token },
+ {
+ responseType: 'arraybuffer',
+ timeout,
+ onDownloadProgress,
+ }
+ )
+ );
+ this.clearDownloadProgress(file.id);
+ if (typeof resp.data === 'undefined') {
+ throw Error(CustomError.REQUEST_FAILED);
+ }
+ try {
+ const decrypted = await cryptoWorker.decryptFile(
+ new Uint8Array(resp.data),
+ await cryptoWorker.fromB64(file.file.decryptionHeader),
+ file.key
+ );
+ return generateStreamFromArrayBuffer(decrypted);
+ } catch (e) {
+ if (e.message === CustomError.PROCESSING_FAILED) {
+ logError(e, 'Failed to process file', {
+ fileID: file.id,
+ fromMobile:
+ !!file.metadata.localID ||
+ !!file.metadata.deviceFolder ||
+ !!file.metadata.version,
+ });
+ addLogLine(
+ `Failed to process file with fileID:${file.id}, localID: ${file.metadata.localID}, version: ${file.metadata.version}, deviceFolder:${file.metadata.deviceFolder} with error: ${e.message}`
+ );
+ }
+ throw e;
+ }
+ }
+ const resp = await retryAsyncFunction(() =>
+ fetch(getFileURL(file.id), {
+ headers: {
+ 'X-Auth-Token': token,
+ },
+ })
+ );
+ const reader = resp.body.getReader();
+
+ const contentLength = +resp.headers.get('Content-Length') ?? 0;
+ let downloadedBytes = 0;
+
+ const stream = new ReadableStream({
+ async start(controller) {
+ try {
+ const decryptionHeader = await cryptoWorker.fromB64(
+ file.file.decryptionHeader
+ );
+ const fileKey = await cryptoWorker.fromB64(file.key);
+ const { pullState, decryptionChunkSize } =
+ await cryptoWorker.initChunkDecryption(
+ decryptionHeader,
+ fileKey
+ );
+ let data = new Uint8Array();
+ // The following function handles each data chunk
+ const push = () => {
+ // "done" is a Boolean and value a "Uint8Array"
+ reader.read().then(async ({ done, value }) => {
+ try {
+ // Is there more data to read?
+ if (!done) {
+ downloadedBytes += value.byteLength;
+ onDownloadProgress({
+ loaded: downloadedBytes,
+ total: contentLength,
+ });
+ const buffer = new Uint8Array(
+ data.byteLength + value.byteLength
+ );
+ buffer.set(new Uint8Array(data), 0);
+ buffer.set(
+ new Uint8Array(value),
+ data.byteLength
+ );
+ if (
+ buffer.length > decryptionChunkSize
+ ) {
+ const fileData = buffer.slice(
+ 0,
+ decryptionChunkSize
+ );
+ try {
+ const { decryptedData } =
+ await cryptoWorker.decryptFileChunk(
+ fileData,
+ pullState
+ );
+ controller.enqueue(
+ decryptedData
+ );
+ data =
+ buffer.slice(
+ decryptionChunkSize
+ );
+ } catch (e) {
+ if (
+ e.message ===
+ CustomError.PROCESSING_FAILED
+ ) {
+ logError(
+ e,
+ 'Failed to process file',
+ {
+ fileID: file.id,
+ fromMobile:
+ !!file.metadata
+ .localID ||
+ !!file.metadata
+ .deviceFolder ||
+ !!file.metadata
+ .version,
+ }
+ );
+ addLogLine(
+ `Failed to process file ${file.id} from localID: ${file.metadata.localID} version: ${file.metadata.version} deviceFolder:${file.metadata.deviceFolder} with error: ${e.message}`
+ );
+ }
+ throw e;
+ }
+ } else {
+ data = buffer;
+ }
+ push();
+ } else {
+ if (data) {
+ try {
+ const { decryptedData } =
+ await cryptoWorker.decryptFileChunk(
+ data,
+ pullState
+ );
+ controller.enqueue(
+ decryptedData
+ );
+ data = null;
+ } catch (e) {
+ if (
+ e.message ===
+ CustomError.PROCESSING_FAILED
+ ) {
+ logError(
+ e,
+ 'Failed to process file',
+ {
+ fileID: file.id,
+ fromMobile:
+ !!file.metadata
+ .localID ||
+ !!file.metadata
+ .deviceFolder ||
+ !!file.metadata
+ .version,
+ }
+ );
+ addLogLine(
+ `Failed to process file ${file.id} from localID: ${file.metadata.localID} version: ${file.metadata.version} deviceFolder:${file.metadata.deviceFolder} with error: ${e.message}`
+ );
+ }
+ throw e;
+ }
+ }
+ controller.close();
+ }
+ } catch (e) {
+ logError(e, 'Failed to process file chunk');
+ controller.error(e);
+ }
+ });
+ };
+
+ push();
+ } catch (e) {
+ logError(e, 'Failed to process file stream');
+ controller.error(e);
+ }
+ },
+ });
+ return stream;
+ } catch (e) {
+ logError(e, 'Failed to download file');
+ throw e;
+ }
+ }
+
+ trackDownloadProgress = (fileID: number, fileSize: number) => {
+ return (event: { loaded: number; total: number }) => {
+ if (isNaN(event.total) || event.total === 0) {
+ if (!fileSize) {
+ return;
+ }
+ event.total = fileSize;
+ }
+ if (event.loaded === event.total) {
+ this.fileDownloadProgress.delete(fileID);
+ } else {
+ this.fileDownloadProgress.set(
+ fileID,
+ Math.round((event.loaded * 100) / event.total)
+ );
+ }
+ this.progressUpdater(new Map(this.fileDownloadProgress));
+ };
+ };
+
+ clearDownloadProgress = (fileID: number) => {
+ this.fileDownloadProgress.delete(fileID);
+ this.progressUpdater(new Map(this.fileDownloadProgress));
+ };
+}
+
+export default new DownloadManager();
diff --git a/apps/cast/src/services/ffmpeg/ffmpegFactory.ts b/apps/cast/src/services/ffmpeg/ffmpegFactory.ts
new file mode 100644
index 0000000000..eca7287c60
--- /dev/null
+++ b/apps/cast/src/services/ffmpeg/ffmpegFactory.ts
@@ -0,0 +1,29 @@
+// import isElectron from 'is-electron';
+// import { ElectronFFmpeg } from 'services/electron/ffmpeg';
+import { ElectronFile } from 'types/upload';
+import ComlinkFFmpegWorker from 'utils/comlink/ComlinkFFmpegWorker';
+
+export interface IFFmpeg {
+ run: (
+ cmd: string[],
+ inputFile: File | ElectronFile,
+ outputFilename: string,
+ dontTimeout?: boolean
+ ) => Promise<File | ElectronFile>;
+}
+
+class FFmpegFactory {
+ private client: IFFmpeg;
+ async getFFmpegClient() {
+ if (!this.client) {
+ // if (isElectron()) {
+ // this.client = new ElectronFFmpeg();
+ // } else {
+ this.client = await ComlinkFFmpegWorker.getInstance();
+ // }
+ }
+ return this.client;
+ }
+}
+
+export default new FFmpegFactory();
diff --git a/apps/cast/src/services/ffmpeg/ffmpegService.ts b/apps/cast/src/services/ffmpeg/ffmpegService.ts
new file mode 100644
index 0000000000..4a0148194d
--- /dev/null
+++ b/apps/cast/src/services/ffmpeg/ffmpegService.ts
@@ -0,0 +1,100 @@
+import {
+ FFMPEG_PLACEHOLDER,
+ INPUT_PATH_PLACEHOLDER,
+ OUTPUT_PATH_PLACEHOLDER,
+} from 'constants/ffmpeg';
+import { ElectronFile } from 'types/upload';
+import { parseFFmpegExtractedMetadata } from 'utils/ffmpeg';
+import { logError } from 'utils/sentry';
+import ffmpegFactory from './ffmpegFactory';
+
+export async function generateVideoThumbnail(
+ file: File | ElectronFile
+): Promise<File | ElectronFile> {
+ try {
+ let seekTime = 1;
+ const ffmpegClient = await ffmpegFactory.getFFmpegClient();
+ while (seekTime >= 0) {
+ try {
+ return await ffmpegClient.run(
+ [
+ FFMPEG_PLACEHOLDER,
+ '-i',
+ INPUT_PATH_PLACEHOLDER,
+ '-ss',
+ `00:00:0${seekTime}`,
+ '-vframes',
+ '1',
+ '-vf',
+ 'scale=-1:720',
+ OUTPUT_PATH_PLACEHOLDER,
+ ],
+ file,
+ 'thumb.jpeg'
+ );
+ } catch (e) {
+ if (seekTime === 0) {
+ throw e;
+ }
+ }
+ seekTime--;
+ }
+ } catch (e) {
+ logError(e, 'ffmpeg generateVideoThumbnail failed');
+ throw e;
+ }
+}
+
+export async function extractVideoMetadata(file: File | ElectronFile) {
+ try {
+ const ffmpegClient = await ffmpegFactory.getFFmpegClient();
+ // https://stackoverflow.com/questions/9464617/retrieving-and-saving-media-metadata-using-ffmpeg
+ // -c [short for codex] copy[(stream_specifier)[ffmpeg.org/ffmpeg.html#Stream-specifiers]] => copies all the stream without re-encoding
+ // -map_metadata [http://ffmpeg.org/ffmpeg.html#Advanced-options search for map_metadata] => copies all stream metadata to the out
+ // -f ffmetadata [https://ffmpeg.org/ffmpeg-formats.html#Metadata-1] => dump metadata from media files into a simple UTF-8-encoded INI-like text file
+ const metadata = await ffmpegClient.run(
+ [
+ FFMPEG_PLACEHOLDER,
+ '-i',
+ INPUT_PATH_PLACEHOLDER,
+ '-c',
+ 'copy',
+ '-map_metadata',
+ '0',
+ '-f',
+ 'ffmetadata',
+ OUTPUT_PATH_PLACEHOLDER,
+ ],
+ file,
+ `metadata.txt`
+ );
+ return parseFFmpegExtractedMetadata(
+ new Uint8Array(await metadata.arrayBuffer())
+ );
+ } catch (e) {
+ logError(e, 'ffmpeg extractVideoMetadata failed');
+ throw e;
+ }
+}
+
+export async function convertToMP4(file: File | ElectronFile) {
+ try {
+ const ffmpegClient = await ffmpegFactory.getFFmpegClient();
+ return await ffmpegClient.run(
+ [
+ FFMPEG_PLACEHOLDER,
+ '-i',
+ INPUT_PATH_PLACEHOLDER,
+ '-preset',
+ 'ultrafast',
+ OUTPUT_PATH_PLACEHOLDER,
+ ],
+ file,
+ 'output.mp4',
+ true
+ );
+ } catch (e) {
+ logError(e, 'ffmpeg convertToMP4 failed');
+ throw e;
+ }
+}
diff --git a/apps/cast/src/services/heicConversionService.ts b/apps/cast/src/services/heicConversionService.ts
new file mode 100644
index 0000000000..64efb87da3
--- /dev/null
+++ b/apps/cast/src/services/heicConversionService.ts
@@ -0,0 +1,14 @@
+import { logError } from 'utils/sentry';
+import WasmHEICConverterService from './wasmHeicConverter/wasmHEICConverterService';
+
+class HeicConversionService {
+ async convert(heicFileData: Blob): Promise<Blob> {
+ try {
+ return await WasmHEICConverterService.convert(heicFileData);
+ } catch (e) {
+ logError(e, 'failed to convert heic file');
+ throw e;
+ }
+ }
+}
+export default new HeicConversionService();
diff --git a/apps/cast/src/services/livePhotoService.ts b/apps/cast/src/services/livePhotoService.ts
new file mode 100644
index 0000000000..613d2861ec
--- /dev/null
+++ b/apps/cast/src/services/livePhotoService.ts
@@ -0,0 +1,45 @@
+import JSZip from 'jszip';
+import { EnteFile } from 'types/file';
+import {
+ getFileExtensionWithDot,
+ getFileNameWithoutExtension,
+} from 'utils/file';
+
+class LivePhoto {
+ image: Uint8Array;
+ video: Uint8Array;
+ imageNameTitle: string;
+ videoNameTitle: string;
+}
+
+export const decodeLivePhoto = async (file: EnteFile, zipBlob: Blob) => {
+ const originalName = getFileNameWithoutExtension(file.metadata.title);
+ const zip = await JSZip.loadAsync(zipBlob, { createFolders: true });
+
+ const livePhoto = new LivePhoto();
+ for (const zipFilename in zip.files) {
+ if (zipFilename.startsWith('image')) {
+ livePhoto.imageNameTitle =
+ originalName + getFileExtensionWithDot(zipFilename);
+ livePhoto.image = await zip.files[zipFilename].async('uint8array');
+ } else if (zipFilename.startsWith('video')) {
+ livePhoto.videoNameTitle =
+ originalName + getFileExtensionWithDot(zipFilename);
+ livePhoto.video = await zip.files[zipFilename].async('uint8array');
+ }
+ }
+ return livePhoto;
+};
+
+export const encodeLivePhoto = async (livePhoto: LivePhoto) => {
+ const zip = new JSZip();
+ zip.file(
+ 'image' + getFileExtensionWithDot(livePhoto.imageNameTitle),
+ livePhoto.image
+ );
+ zip.file(
+ 'video' + getFileExtensionWithDot(livePhoto.videoNameTitle),
+ livePhoto.video
+ );
+ return await zip.generateAsync({ type: 'uint8array' });
+};
diff --git a/apps/cast/src/services/publicCollectionDownloadManager.ts b/apps/cast/src/services/publicCollectionDownloadManager.ts
new file mode 100644
index 0000000000..a5a19082c4
--- /dev/null
+++ b/apps/cast/src/services/publicCollectionDownloadManager.ts
@@ -0,0 +1,314 @@
+import {
+ getPublicCollectionFileURL,
+ getPublicCollectionThumbnailURL,
+} from 'utils/common/apiUtil';
+import {
+ generateStreamFromArrayBuffer,
+ getRenderableFileURL,
+ createTypedObjectURL,
+} from 'utils/file';
+import HTTPService from './HTTPService';
+import { EnteFile } from 'types/file';
+
+import { logError } from 'utils/sentry';
+import { FILE_TYPE } from 'constants/file';
+import { CustomError } from 'utils/error';
+import ComlinkCryptoWorker from 'utils/comlink/ComlinkCryptoWorker';
+import { CACHES } from 'constants/cache';
+import { CacheStorageService } from './cache/cacheStorageService';
+import { LimitedCache } from 'types/cache';
+
+class PublicCollectionDownloadManager {
+ private fileObjectURLPromise = new Map<
+ string,
+ Promise<{ original: string[]; converted: string[] }>
+ >();
+ private thumbnailObjectURLPromise = new Map<number, Promise<string>>();
+
+ private fileDownloadProgress = new Map<number, number>();
+
+ private progressUpdater: (value: Map<number, number>) => void;
+
+ setProgressUpdater(progressUpdater: (value: Map<number, number>) => void) {
+ this.progressUpdater = progressUpdater;
+ }
+
+ private async getThumbnailCache() {
+ try {
+ const thumbnailCache = await CacheStorageService.open(
+ CACHES.THUMBS
+ );
+ return thumbnailCache;
+ } catch (e) {
+ return null;
+ // ignore
+ }
+ }
+
+ public async getCachedThumbnail(
+ file: EnteFile,
+ thumbnailCache?: LimitedCache
+ ) {
+ try {
+ if (!thumbnailCache) {
+ thumbnailCache = await this.getThumbnailCache();
+ }
+ const cacheResp: Response = await thumbnailCache?.match(
+ file.id.toString()
+ );
+
+ if (cacheResp) {
+ return URL.createObjectURL(await cacheResp.blob());
+ }
+ return null;
+ } catch (e) {
+ logError(e, 'failed to get cached thumbnail');
+ throw e;
+ }
+ }
+
+ public async getThumbnail(
+ file: EnteFile,
+ token: string,
+ passwordToken: string
+ ) {
+ try {
+ if (!token) {
+ return null;
+ }
+
+ if (!this.thumbnailObjectURLPromise.has(file.id)) {
+ const downloadPromise = async () => {
+ const thumbnailCache = await this.getThumbnailCache();
+ const cachedThumb = await this.getCachedThumbnail(
+ file,
+ thumbnailCache
+ );
+ if (cachedThumb) {
+ return cachedThumb;
+ }
+
+ const thumb = await this.downloadThumb(
+ token,
+ passwordToken,
+ file
+ );
+ const thumbBlob = new Blob([thumb]);
+ try {
+ await thumbnailCache?.put(
+ file.id.toString(),
+ new Response(thumbBlob)
+ );
+ } catch (e) {
+ // TODO: handle storage full exception.
+ }
+ return URL.createObjectURL(thumbBlob);
+ };
+ this.thumbnailObjectURLPromise.set(file.id, downloadPromise());
+ }
+
+ return await this.thumbnailObjectURLPromise.get(file.id);
+ } catch (e) {
+ this.thumbnailObjectURLPromise.delete(file.id);
+ logError(e, 'get publicDownloadManger preview Failed');
+ throw e;
+ }
+ }
+
+ private downloadThumb = async (
+ token: string,
+ passwordToken: string,
+ file: EnteFile
+ ) => {
+ const resp = await HTTPService.get(
+ getPublicCollectionThumbnailURL(file.id),
+ null,
+ {
+ 'X-Auth-Access-Token': token,
+ ...(passwordToken && {
+ 'X-Auth-Access-Token-JWT': passwordToken,
+ }),
+ },
+ { responseType: 'arraybuffer' }
+ );
+ if (typeof resp.data === 'undefined') {
+ throw Error(CustomError.REQUEST_FAILED);
+ }
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ const decrypted = await cryptoWorker.decryptThumbnail(
+ new Uint8Array(resp.data),
+ await cryptoWorker.fromB64(file.thumbnail.decryptionHeader),
+ file.key
+ );
+ return decrypted;
+ };
+
+ getFile = async (
+ file: EnteFile,
+ token: string,
+ passwordToken: string,
+ forPreview = false
+ ) => {
+ const fileKey = forPreview ? `${file.id}_preview` : `${file.id}`;
+ try {
+ const getFilePromise = async () => {
+ const fileStream = await this.downloadFile(
+ token,
+ passwordToken,
+ file
+ );
+ const fileBlob = await new Response(fileStream).blob();
+ if (forPreview) {
+ return await getRenderableFileURL(file, fileBlob);
+ } else {
+ const fileURL = await createTypedObjectURL(
+ fileBlob,
+ file.metadata.title
+ );
+ return { converted: [fileURL], original: [fileURL] };
+ }
+ };
+
+ if (!this.fileObjectURLPromise.get(fileKey)) {
+ this.fileObjectURLPromise.set(fileKey, getFilePromise());
+ }
+ const fileURLs = await this.fileObjectURLPromise.get(fileKey);
+ return fileURLs;
+ } catch (e) {
+ this.fileObjectURLPromise.delete(fileKey);
+ logError(e, 'public download manager Failed to get File');
+ throw e;
+ }
+ };
+
+ public async getCachedOriginalFile(file: EnteFile) {
+ return await this.fileObjectURLPromise.get(file.id.toString());
+ }
+
+ async downloadFile(token: string, passwordToken: string, file: EnteFile) {
+ const cryptoWorker = await ComlinkCryptoWorker.getInstance();
+ if (!token) {
+ return null;
+ }
+ const onDownloadProgress = this.trackDownloadProgress(file.id);
+
+ if (
+ file.metadata.fileType === FILE_TYPE.IMAGE ||
+ file.metadata.fileType === FILE_TYPE.LIVE_PHOTO
+ ) {
+ const resp = await HTTPService.get(
+ getPublicCollectionFileURL(file.id),
+ null,
+ {
+ 'X-Auth-Access-Token': token,
+ ...(passwordToken && {
+ 'X-Auth-Access-Token-JWT': passwordToken,
+ onDownloadProgress,
+ }),
+ },
+ { responseType: 'arraybuffer' }
+ );
+ if (typeof resp.data === 'undefined') {
+ throw Error(CustomError.REQUEST_FAILED);
+ }
+ const decrypted = await cryptoWorker.decryptFile(
+ new Uint8Array(resp.data),
+ await cryptoWorker.fromB64(file.file.decryptionHeader),
+ file.key
+ );
+ return generateStreamFromArrayBuffer(decrypted);
+ }
+ const resp = await fetch(getPublicCollectionFileURL(file.id), {
+ headers: {
+ 'X-Auth-Access-Token': token,
+ ...(passwordToken && {
+ 'X-Auth-Access-Token-JWT': passwordToken,
+ }),
+ },
+ });
+ const reader = resp.body.getReader();
+
+ const contentLength = +resp.headers.get('Content-Length');
+ let downloadedBytes = 0;
+
+ const stream = new ReadableStream({
+ async start(controller) {
+ const decryptionHeader = await cryptoWorker.fromB64(
+ file.file.decryptionHeader
+ );
+ const fileKey = await cryptoWorker.fromB64(file.key);
+ const { pullState, decryptionChunkSize } =
+ await cryptoWorker.initChunkDecryption(
+ decryptionHeader,
+ fileKey
+ );
+ let data = new Uint8Array();
+ // The following function handles each data chunk
+ function push() {
+ // "done" is a Boolean and value a "Uint8Array"
+ reader.read().then(async ({ done, value }) => {
+ // Is there more data to read?
+ if (!done) {
+ downloadedBytes += value.byteLength;
+ onDownloadProgress({
+ loaded: downloadedBytes,
+ total: contentLength,
+ });
+ const buffer = new Uint8Array(
+ data.byteLength + value.byteLength
+ );
+ buffer.set(new Uint8Array(data), 0);
+ buffer.set(new Uint8Array(value), data.byteLength);
+ if (buffer.length > decryptionChunkSize) {
+ const fileData = buffer.slice(
+ 0,
+ decryptionChunkSize
+ );
+ const { decryptedData } =
+ await cryptoWorker.decryptFileChunk(
+ fileData,
+ pullState
+ );
+ controller.enqueue(decryptedData);
+ data = buffer.slice(decryptionChunkSize);
+ } else {
+ data = buffer;
+ }
+ push();
+ } else {
+ if (data) {
+ const { decryptedData } =
+ await cryptoWorker.decryptFileChunk(
+ data,
+ pullState
+ );
+ controller.enqueue(decryptedData);
+ data = null;
+ }
+ controller.close();
+ }
+ });
+ }
+
+ push();
+ },
+ });
+ return stream;
+ }
+
+ trackDownloadProgress = (fileID: number) => {
+ return (event: { loaded: number; total: number }) => {
+ if (event.loaded === event.total) {
+ this.fileDownloadProgress.delete(fileID);
+ } else {
+ this.fileDownloadProgress.set(
+ fileID,
+ Math.round((event.loaded * 100) / event.total)
+ );
+ }
+ this.progressUpdater(new Map(this.fileDownloadProgress));
+ };
+ };
+}
+
+export default new PublicCollectionDownloadManager();
diff --git a/apps/cast/src/services/queueProcessor.ts b/apps/cast/src/services/queueProcessor.ts
new file mode 100644
index 0000000000..6071556a15
--- /dev/null
+++ b/apps/cast/src/services/queueProcessor.ts
@@ -0,0 +1,86 @@
+import { CustomError } from 'utils/error';
+
+interface RequestQueueItem {
+ request: (canceller?: RequestCanceller) => Promise<any>;
+ successCallback: (response: any) => void;
+ failureCallback: (error: Error) => void;
+ isCanceled: { status: boolean };
+ canceller: { exec: () => void };
+}
+
+export enum PROCESSING_STRATEGY {
+ FIFO,
+ LIFO,
+}
+
+export interface RequestCanceller {
+ exec: () => void;
+}
+
+export interface CancellationStatus {
+ status: boolean;
+}
+
+export default class QueueProcessor<T> {
+ private requestQueue: RequestQueueItem[] = [];
+
+ private requestInProcessing = 0;
+
+ constructor(
+ private maxParallelProcesses: number,
+ private processingStrategy = PROCESSING_STRATEGY.FIFO
+ ) {}
+
+ public queueUpRequest(
+ request: (canceller?: RequestCanceller) => Promise<T>
+ ) {
+ const isCanceled: CancellationStatus = { status: false };
+ const canceller: RequestCanceller = {
+ exec: () => {
+ isCanceled.status = true;
+ },
+ };
+
+ const promise = new Promise<T>((resolve, reject) => {
+ this.requestQueue.push({
+ request,
+ successCallback: resolve,
+ failureCallback: reject,
+ isCanceled,
+ canceller,
+ });
+ this.pollQueue();
+ });
+
+ return { promise, canceller };
+ }
+
+ private async pollQueue() {
+ if (this.requestInProcessing < this.maxParallelProcesses) {
+ this.requestInProcessing++;
+ this.processQueue();
+ }
+ }
+
+ private async processQueue() {
+ while (this.requestQueue.length > 0) {
+ const queueItem =
+ this.processingStrategy === PROCESSING_STRATEGY.LIFO
+ ? this.requestQueue.pop()
+ : this.requestQueue.shift();
+ let response = null;
+
+ if (queueItem.isCanceled.status) {
+ queueItem.failureCallback(Error(CustomError.REQUEST_CANCELLED));
+ } else {
+ try {
+ response = await queueItem.request(queueItem.canceller);
+ queueItem.successCallback(response);
+ } catch (e) {
+ queueItem.failureCallback(e);
+ }
+ }
+ }
+ this.requestInProcessing--;
+ }
+}
diff --git a/apps/cast/src/services/readerService.ts b/apps/cast/src/services/readerService.ts
new file mode 100644
index 0000000000..c351225977
--- /dev/null
+++ b/apps/cast/src/services/readerService.ts
@@ -0,0 +1,93 @@
+import { ElectronFile } from 'types/upload';
+import { convertBytesToHumanReadable } from 'utils/file/size';
+import { logError } from 'utils/sentry';
+
+export async function getUint8ArrayView(
+ file: Blob | ElectronFile
+): Promise<Uint8Array> {
+ try {
+ return new Uint8Array(await file.arrayBuffer());
+ } catch (e) {
+ logError(e, 'reading file blob failed', {
+ fileSize: convertBytesToHumanReadable(file.size),
+ });
+ throw e;
+ }
+}
+
+export function getFileStream(file: File, chunkSize: number) {
+ const fileChunkReader = fileChunkReaderMaker(file, chunkSize);
+
+ const stream = new ReadableStream<Uint8Array>({
+ async pull(controller: ReadableStreamDefaultController) {
+ const chunk = await fileChunkReader.next();
+ if (chunk.done) {
+ controller.close();
+ } else {
+ controller.enqueue(chunk.value);
+ }
+ },
+ });
+ const chunkCount = Math.ceil(file.size / chunkSize);
+ return {
+ stream,
+ chunkCount,
+ };
+}
+
+export async function getElectronFileStream(
+ file: ElectronFile,
+ chunkSize: number
+) {
+ const chunkCount = Math.ceil(file.size / chunkSize);
+ return {
+ stream: await file.stream(),
+ chunkCount,
+ };
+}
+
+async function* fileChunkReaderMaker(file: File, chunkSize: number) {
+ let offset = 0;
+ while (offset < file.size) {
+ const blob = file.slice(offset, chunkSize + offset);
+ const fileChunk = await getUint8ArrayView(blob);
+ yield fileChunk;
+ offset += chunkSize;
+ }
+ return null;
+}
+
+// depreciated
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+async function getUint8ArrayViewOld(
+ reader: FileReader,
+ file: Blob
+): Promise<Uint8Array> {
+ return await new Promise((resolve, reject) => {
+ reader.onabort = () =>
+ reject(
+ Error(
+ `file reading was aborted, file size= ${convertBytesToHumanReadable(
+ file.size
+ )}`
+ )
+ );
+ reader.onerror = () =>
+ reject(
+ Error(
+ `file reading has failed, file size= ${convertBytesToHumanReadable(
+ file.size
+ )} , reason= ${reader.error}`
+ )
+ );
+ reader.onload = () => {
+ // Do whatever you want with the file contents
+ const result =
+ typeof reader.result === 'string'
+ ? new TextEncoder().encode(reader.result)
+ : new Uint8Array(reader.result);
+ resolve(result);
+ };
+ reader.readAsArrayBuffer(file);
+ });
+}
diff --git a/apps/cast/src/services/typeDetectionService.ts b/apps/cast/src/services/typeDetectionService.ts
new file mode 100644
index 0000000000..889ee29903
--- /dev/null
+++ b/apps/cast/src/services/typeDetectionService.ts
@@ -0,0 +1,108 @@
+import { FILE_TYPE } from 'constants/file';
+import { ElectronFile, FileTypeInfo } from 'types/upload';
+import {
+ WHITELISTED_FILE_FORMATS,
+ KNOWN_NON_MEDIA_FORMATS,
+} from 'constants/upload';
+import { CustomError } from 'utils/error';
+import { getFileExtension } from 'utils/file';
+import { logError } from 'utils/sentry';
+import { getUint8ArrayView } from './readerService';
+import FileType, { FileTypeResult } from 'file-type';
+import { convertBytesToHumanReadable } from 'utils/file/size';
+
+function getFileSize(file: File | ElectronFile) {
+ return file.size;
+}
+
+const TYPE_VIDEO = 'video';
+const TYPE_IMAGE = 'image';
+const CHUNK_SIZE_FOR_TYPE_DETECTION = 4100;
+
+export async function getFileType(
+ receivedFile: File | ElectronFile
+): Promise<FileTypeInfo> {
+ try {
+ let fileType: FILE_TYPE;
+ let typeResult: FileTypeResult;
+
+ if (receivedFile instanceof File) {
+ typeResult = await extractFileType(receivedFile);
+ } else {
+ typeResult = await extractElectronFileType(receivedFile);
+ }
+
+ const mimTypeParts: string[] = typeResult.mime?.split('/');
+
+ if (mimTypeParts?.length !== 2) {
+ throw Error(CustomError.INVALID_MIME_TYPE(typeResult.mime));
+ }
+ switch (mimTypeParts[0]) {
+ case TYPE_IMAGE:
+ fileType = FILE_TYPE.IMAGE;
+ break;
+ case TYPE_VIDEO:
+ fileType = FILE_TYPE.VIDEO;
+ break;
+ default:
+ throw Error(CustomError.NON_MEDIA_FILE);
+ }
+ return {
+ fileType,
+ exactType: typeResult.ext,
+ mimeType: typeResult.mime,
+ };
+ } catch (e) {
+ const fileFormat = getFileExtension(receivedFile.name);
+ const fileSize = convertBytesToHumanReadable(getFileSize(receivedFile));
+ const whiteListedFormat = WHITELISTED_FILE_FORMATS.find(
+ (a) => a.exactType === fileFormat
+ );
+ if (whiteListedFormat) {
+ return whiteListedFormat;
+ }
+ if (KNOWN_NON_MEDIA_FORMATS.includes(fileFormat)) {
+ throw Error(CustomError.UNSUPPORTED_FILE_FORMAT);
+ }
+ if (e.message === CustomError.NON_MEDIA_FILE) {
+ logError(e, 'unsupported file format', {
+ fileFormat,
+ fileSize,
+ });
+ throw Error(CustomError.UNSUPPORTED_FILE_FORMAT);
+ }
+ logError(e, 'type detection failed', {
+ fileFormat,
+ fileSize,
+ });
+ throw Error(CustomError.TYPE_DETECTION_FAILED(fileFormat));
+ }
+}
+
+async function extractFileType(file: File) {
+ const fileBlobChunk = file.slice(0, CHUNK_SIZE_FOR_TYPE_DETECTION);
+ const fileDataChunk = await getUint8ArrayView(fileBlobChunk);
+ return getFileTypeFromBuffer(fileDataChunk);
+}
+
+async function extractElectronFileType(file: ElectronFile) {
+ const stream = await file.stream();
+ const reader = stream.getReader();
+ const { value: fileDataChunk } = await reader.read();
+ await reader.cancel();
+ return getFileTypeFromBuffer(fileDataChunk);
+}
+
+async function getFileTypeFromBuffer(buffer: Uint8Array) {
+ const result = await FileType.fromBuffer(buffer);
+ if (!result?.mime) {
+ let logableInfo = '';
+ try {
+ logableInfo = `result: ${JSON.stringify(result)}`;
+ } catch (e) {
+ logableInfo = 'failed to stringify result';
+ }
+ throw Error(`mimetype missing from file type result - ${logableInfo}`);
+ }
+ return result;
+}
diff --git a/apps/cast/src/services/upload/exifService.ts b/apps/cast/src/services/upload/exifService.ts
new file mode 100644
index 0000000000..8e191665ba
--- /dev/null
+++ b/apps/cast/src/services/upload/exifService.ts
@@ -0,0 +1,373 @@
+import { EXIFLESS_FORMATS, NULL_LOCATION } from 'constants/upload';
+import { Location } from 'types/upload';
+import exifr from 'exifr';
+import piexif from 'piexifjs';
+import { FileTypeInfo } from 'types/upload';
+import { logError } from 'utils/sentry';
+import { validateAndGetCreationUnixTimeInMicroSeconds } from 'utils/time';
+import { CustomError } from 'utils/error';
+
+const EXIFR_UNSUPPORTED_FILE_FORMAT_MESSAGE = 'Unknown file format';
+
+type ParsedEXIFData = Record<string, any> &
+ Partial<{
+ DateTimeOriginal: Date;
+ CreateDate: Date;
+ ModifyDate: Date;
+ DateCreated: Date;
+ MetadataDate: Date;
+ latitude: number;
+ longitude: number;
+ imageWidth: number;
+ imageHeight: number;
+ }>;
+
+type RawEXIFData = Record<string, any> &
+ Partial<{
+ DateTimeOriginal: string;
+ CreateDate: string;
+ ModifyDate: string;
+ DateCreated: string;
+ MetadataDate: string;
+ GPSLatitude: number[];
+ GPSLongitude: number[];
+ GPSLatitudeRef: string;
+ GPSLongitudeRef: string;
+ ImageWidth: number;
+ ImageHeight: number;
+ }>;
+
+export async function getParsedExifData(
+ receivedFile: File,
+ fileTypeInfo: FileTypeInfo,
+ tags?: string[]
+): Promise<ParsedEXIFData> {
+ try {
+ if (EXIFLESS_FORMATS.includes(fileTypeInfo.exactType)) {
+ return null;
+ }
+ const exifData: RawEXIFData = await exifr.parse(receivedFile, {
+ reviveValues: false,
+ tiff: true,
+ xmp: true,
+ icc: true,
+ iptc: true,
+ jfif: true,
+ ihdr: true,
+ });
+ if (!exifData) {
+ return null;
+ }
+ const filteredExifData = tags
+ ? Object.fromEntries(
+ Object.entries(exifData).filter(([key]) => tags.includes(key))
+ )
+ : exifData;
+ return parseExifData(filteredExifData);
+ } catch (e) {
+ if (e.message === EXIFR_UNSUPPORTED_FILE_FORMAT_MESSAGE) {
+ logError(e, 'exif library unsupported format', {
+ fileType: fileTypeInfo.exactType,
+ });
+ } else {
+ logError(e, 'get parsed exif data failed', {
+ fileType: fileTypeInfo.exactType,
+ });
+ throw e;
+ }
+ }
+}
+
+function parseExifData(exifData: RawEXIFData): ParsedEXIFData {
+ if (!exifData) {
+ return null;
+ }
+ const {
+ DateTimeOriginal,
+ CreateDate,
+ ModifyDate,
+ DateCreated,
+ ImageHeight,
+ ImageWidth,
+ ExifImageHeight,
+ ExifImageWidth,
+ PixelXDimension,
+ PixelYDimension,
+ MetadataDate,
+ ...rest
+ } = exifData;
+ const parsedExif: ParsedEXIFData = { ...rest };
+ if (DateTimeOriginal) {
+ parsedExif.DateTimeOriginal = parseEXIFDate(exifData.DateTimeOriginal);
+ }
+ if (CreateDate) {
+ parsedExif.CreateDate = parseEXIFDate(exifData.CreateDate);
+ }
+ if (ModifyDate) {
+ parsedExif.ModifyDate = parseEXIFDate(exifData.ModifyDate);
+ }
+ if (DateCreated) {
+ parsedExif.DateCreated = parseEXIFDate(exifData.DateCreated);
+ }
+ if (MetadataDate) {
+ parsedExif.MetadataDate = parseEXIFDate(exifData.MetadataDate);
+ }
+ if (exifData.GPSLatitude && exifData.GPSLongitude) {
+ const parsedLocation = parseEXIFLocation(
+ exifData.GPSLatitude,
+ exifData.GPSLatitudeRef,
+ exifData.GPSLongitude,
+ exifData.GPSLongitudeRef
+ );
+ parsedExif.latitude = parsedLocation.latitude;
+ parsedExif.longitude = parsedLocation.longitude;
+ }
+ if (ImageWidth && ImageHeight) {
+ if (typeof ImageWidth === 'number' && typeof ImageHeight === 'number') {
+ parsedExif.imageWidth = ImageWidth;
+ parsedExif.imageHeight = ImageHeight;
+ } else {
+ logError(
+ new Error('ImageWidth or ImageHeight is not a number'),
+ 'Image dimension parsing failed',
+ {
+ ImageWidth,
+ ImageHeight,
+ }
+ );
+ }
+ } else if (ExifImageWidth && ExifImageHeight) {
+ if (
+ typeof ExifImageWidth === 'number' &&
+ typeof ExifImageHeight === 'number'
+ ) {
+ parsedExif.imageWidth = ExifImageWidth;
+ parsedExif.imageHeight = ExifImageHeight;
+ } else {
+ logError(
+ new Error('ExifImageWidth or ExifImageHeight is not a number'),
+ 'Image dimension parsing failed',
+ {
+ ExifImageWidth,
+ ExifImageHeight,
+ }
+ );
+ }
+ } else if (PixelXDimension && PixelYDimension) {
+ if (
+ typeof PixelXDimension === 'number' &&
+ typeof PixelYDimension === 'number'
+ ) {
+ parsedExif.imageWidth = PixelXDimension;
+ parsedExif.imageHeight = PixelYDimension;
+ } else {
+ logError(
+ new Error('PixelXDimension or PixelYDimension is not a number'),
+ 'Image dimension parsing failed',
+ {
+ PixelXDimension,
+ PixelYDimension,
+ }
+ );
+ }
+ }
+ return parsedExif;
+}
+
+function parseEXIFDate(dateTimeString: string) {
+ try {
+ if (typeof dateTimeString !== 'string' || dateTimeString === '') {
+ throw Error(CustomError.NOT_A_DATE);
+ }
+
+ // Check and parse date in the format YYYYMMDD
+ if (dateTimeString.length === 8) {
+ const year = Number(dateTimeString.slice(0, 4));
+ const month = Number(dateTimeString.slice(4, 6));
+ const day = Number(dateTimeString.slice(6, 8));
+ if (
+ !Number.isNaN(year) &&
+ !Number.isNaN(month) &&
+ !Number.isNaN(day)
+ ) {
+ const date = new Date(year, month - 1, day);
+ if (!Number.isNaN(+date)) {
+ return date;
+ }
+ }
+ }
+ const [year, month, day, hour, minute, second] = dateTimeString
+ .match(/\d+/g)
+ .map(Number);
+
+ if (
+ typeof year === 'undefined' ||
+ Number.isNaN(year) ||
+ typeof month === 'undefined' ||
+ Number.isNaN(month) ||
+ typeof day === 'undefined' ||
+ Number.isNaN(day)
+ ) {
+ throw Error(CustomError.NOT_A_DATE);
+ }
+ let date: Date;
+ if (
+ typeof hour === 'undefined' ||
+ Number.isNaN(hour) ||
+ typeof minute === 'undefined' ||
+ Number.isNaN(minute) ||
+ typeof second === 'undefined' ||
+ Number.isNaN(second)
+ ) {
+ date = new Date(year, month - 1, day);
+ } else {
+ date = new Date(year, month - 1, day, hour, minute, second);
+ }
+ if (Number.isNaN(+date)) {
+ throw Error(CustomError.NOT_A_DATE);
+ }
+ return date;
+ } catch (e) {
+ logError(e, 'parseEXIFDate failed', {
+ dateTimeString,
+ });
+ return null;
+ }
+}
+
+export function parseEXIFLocation(
+ gpsLatitude: number[],
+ gpsLatitudeRef: string,
+ gpsLongitude: number[],
+ gpsLongitudeRef: string
+) {
+ try {
+ if (
+ !Array.isArray(gpsLatitude) ||
+ !Array.isArray(gpsLongitude) ||
+ gpsLatitude.length !== 3 ||
+ gpsLongitude.length !== 3
+ ) {
+ throw Error(CustomError.NOT_A_LOCATION);
+ }
+ const latitude = convertDMSToDD(
+ gpsLatitude[0],
+ gpsLatitude[1],
+ gpsLatitude[2],
+ gpsLatitudeRef
+ );
+ const longitude = convertDMSToDD(
+ gpsLongitude[0],
+ gpsLongitude[1],
+ gpsLongitude[2],
+ gpsLongitudeRef
+ );
+ return { latitude, longitude };
+ } catch (e) {
+ logError(e, 'parseEXIFLocation failed', {
+ gpsLatitude,
+ gpsLatitudeRef,
+ gpsLongitude,
+ gpsLongitudeRef,
+ });
+ return NULL_LOCATION;
+ }
+}
+
+function convertDMSToDD(
+ degrees: number,
+ minutes: number,
+ seconds: number,
+ direction: string
+) {
+ let dd = degrees + minutes / 60 + seconds / (60 * 60);
+ if (direction === 'S' || direction === 'W') dd *= -1;
+ return dd;
+}
+
+export function getEXIFLocation(exifData: ParsedEXIFData): Location {
+ if (!exifData || (!exifData.latitude && exifData.latitude !== 0)) {
+ return NULL_LOCATION;
+ }
+ return { latitude: exifData.latitude, longitude: exifData.longitude };
+}
+
+export function getEXIFTime(exifData: ParsedEXIFData): number {
+ if (!exifData) {
+ return null;
+ }
+ const dateTime =
+ exifData.DateTimeOriginal ??
+ exifData.DateCreated ??
+ exifData.CreateDate ??
+ exifData.MetadataDate ??
+ exifData.ModifyDate;
+ if (!dateTime) {
+ return null;
+ }
+ return validateAndGetCreationUnixTimeInMicroSeconds(dateTime);
+}
+
+export async function updateFileCreationDateInEXIF(
+ reader: FileReader,
+ fileBlob: Blob,
+ updatedDate: Date
+) {
+ try {
+ let imageDataURL = await convertImageToDataURL(reader, fileBlob);
+ imageDataURL =
+ 'data:image/jpeg;base64' +
+ imageDataURL.slice(imageDataURL.indexOf(','));
+ const exifObj = piexif.load(imageDataURL);
+ if (!exifObj['Exif']) {
+ exifObj['Exif'] = {};
+ }
+ exifObj['Exif'][piexif.ExifIFD.DateTimeOriginal] =
+ convertToExifDateFormat(updatedDate);
+
+ const exifBytes = piexif.dump(exifObj);
+ const exifInsertedFile = piexif.insert(exifBytes, imageDataURL);
+ return dataURIToBlob(exifInsertedFile);
+ } catch (e) {
+ logError(e, 'updateFileModifyDateInEXIF failed');
+ return fileBlob;
+ }
+}
+
+async function convertImageToDataURL(reader: FileReader, blob: Blob) {
+ const dataURL = await new Promise<string>((resolve) => {
+ reader.onload = () => resolve(reader.result as string);
+ reader.readAsDataURL(blob);
+ });
+ return dataURL;
+}
+
+function dataURIToBlob(dataURI: string) {
+ // convert base64 to raw binary data held in a string
+ // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
+ const byteString = atob(dataURI.split(',')[1]);
+
+ // separate out the mime component
+ const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
+
+ // write the bytes of the string to an ArrayBuffer
+ const ab = new ArrayBuffer(byteString.length);
+
+ // create a view into the buffer
+ const ia = new Uint8Array(ab);
+
+ // set the bytes of the buffer to the correct values
+ for (let i = 0; i < byteString.length; i++) {
+ ia[i] = byteString.charCodeAt(i);
+ }
+
+ // write the ArrayBuffer to a blob, and you're done
+ const blob = new Blob([ab], { type: mimeString });
+ return blob;
+}
+
+function convertToExifDateFormat(date: Date) {
+ return `${date.getFullYear()}:${
+ date.getMonth() + 1
+ }:${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
+}
diff --git a/apps/cast/src/services/wasm/ffmpeg.ts b/apps/cast/src/services/wasm/ffmpeg.ts
new file mode 100644
index 0000000000..37963652e4
--- /dev/null
+++ b/apps/cast/src/services/wasm/ffmpeg.ts
@@ -0,0 +1,116 @@
+import { createFFmpeg, FFmpeg } from 'ffmpeg-wasm';
+import QueueProcessor from 'services/queueProcessor';
+import { getUint8ArrayView } from 'services/readerService';
+import { promiseWithTimeout } from 'utils/common';
+import { addLogLine } from 'utils/logging';
+import { logError } from 'utils/sentry';
+import { generateTempName } from 'utils/temp';
+
+const INPUT_PATH_PLACEHOLDER = 'INPUT';
+const FFMPEG_PLACEHOLDER = 'FFMPEG';
+const OUTPUT_PATH_PLACEHOLDER = 'OUTPUT';
+
+const FFMPEG_EXECUTION_WAIT_TIME = 30 * 1000;
+
+export class WasmFFmpeg {
+ private ffmpeg: FFmpeg;
+ private ready: Promise<void> = null;
+ private ffmpegTaskQueue = new QueueProcessor<File>(1);
+
+ constructor() {
+ this.ffmpeg = createFFmpeg({
+ corePath: '/js/ffmpeg/ffmpeg-core.js',
+ mt: false,
+ });
+
+ this.ready = this.init();
+ }
+
+ private async init() {
+ if (!this.ffmpeg.isLoaded()) {
+ await this.ffmpeg.load();
+ }
+ }
+
+ async run(
+ cmd: string[],
+ inputFile: File,
+ outputFileName: string,
+ dontTimeout = false
+ ) {
+ const response = this.ffmpegTaskQueue.queueUpRequest(() => {
+ if (dontTimeout) {
+ return this.execute(cmd, inputFile, outputFileName);
+ } else {
+ return promiseWithTimeout<File>(
+ this.execute(cmd, inputFile, outputFileName),
+ FFMPEG_EXECUTION_WAIT_TIME
+ );
+ }
+ });
+ try {
+ return await response.promise;
+ } catch (e) {
+ logError(e, 'ffmpeg run failed');
+ throw e;
+ }
+ }
+
+ private async execute(
+ cmd: string[],
+ inputFile: File,
+ outputFileName: string
+ ) {
+ let tempInputFilePath: string;
+ let tempOutputFilePath: string;
+ try {
+ await this.ready;
+ const extension = getFileExtension(inputFile.name);
+ const tempNameSuffix = extension ? `input.${extension}` : 'input';
+ tempInputFilePath = `${generateTempName(10, tempNameSuffix)}`;
+ this.ffmpeg.FS(
+ 'writeFile',
+ tempInputFilePath,
+ await getUint8ArrayView(inputFile)
+ );
+ tempOutputFilePath = `${generateTempName(10, outputFileName)}`;
+
+ cmd = cmd.map((cmdPart) => {
+ if (cmdPart === FFMPEG_PLACEHOLDER) {
+ return '';
+ } else if (cmdPart === INPUT_PATH_PLACEHOLDER) {
+ return tempInputFilePath;
+ } else if (cmdPart === OUTPUT_PATH_PLACEHOLDER) {
+ return tempOutputFilePath;
+ } else {
+ return cmdPart;
+ }
+ });
+ addLogLine(`${cmd}`);
+ await this.ffmpeg.run(...cmd);
+ return new File(
+ [this.ffmpeg.FS('readFile', tempOutputFilePath)],
+ outputFileName
+ );
+ } finally {
+ try {
+ this.ffmpeg.FS('unlink', tempInputFilePath);
+ } catch (e) {
+ logError(e, 'unlink input file failed');
+ }
+ try {
+ this.ffmpeg.FS('unlink', tempOutputFilePath);
+ } catch (e) {
+ logError(e, 'unlink output file failed');
+ }
+ }
+ }
+}
+
+function getFileExtension(filename: string) {
+ const lastDotPosition = filename.lastIndexOf('.');
+ if (lastDotPosition === -1) return null;
+ else {
+ return filename.slice(lastDotPosition + 1);
+ }
+}
diff --git a/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterClient.ts b/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterClient.ts
new file mode 100644
index 0000000000..0ca183f22e
--- /dev/null
+++ b/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterClient.ts
@@ -0,0 +1,13 @@
+import * as HeicConvert from 'heic-convert';
+import { getUint8ArrayView } from 'services/readerService';
+
+export async function convertHEIC(
+ fileBlob: Blob,
+ format: string
+): Promise<Blob> {
+ const filedata = await getUint8ArrayView(fileBlob);
+ const result = await HeicConvert({ buffer: filedata, format });
+ const convertedFileData = new Uint8Array(result);
+ const convertedFileBlob = new Blob([convertedFileData]);
+ return convertedFileBlob;
+}
diff --git a/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterService.ts b/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterService.ts
new file mode 100644
index 0000000000..3ff88a6fb2
--- /dev/null
+++ b/apps/cast/src/services/wasmHeicConverter/wasmHEICConverterService.ts
@@ -0,0 +1,114 @@
+import QueueProcessor from 'services/queueProcessor';
+import { CustomError } from 'utils/error';
+import { retryAsyncFunction } from 'utils/network';
+import { logError } from 'utils/sentry';
+import { addLogLine } from 'utils/logging';
+import { DedicatedConvertWorker } from 'worker/convert.worker';
+import { ComlinkWorker } from 'utils/comlink/comlinkWorker';
+import { convertBytesToHumanReadable } from 'utils/file/size';
+import { getDedicatedConvertWorker } from 'utils/comlink/ComlinkConvertWorker';
+
+const WORKER_POOL_SIZE = 2;
+const MAX_CONVERSION_IN_PARALLEL = 1;
+const WAIT_TIME_BEFORE_NEXT_ATTEMPT_IN_MICROSECONDS = [100, 100];
+const WAIT_TIME_IN_MICROSECONDS = 30 * 1000;
+const BREATH_TIME_IN_MICROSECONDS = 1000;
+const CONVERT_FORMAT = 'JPEG';
+
+class HEICConverter {
+ private convertProcessor = new QueueProcessor<Blob>(
+ MAX_CONVERSION_IN_PARALLEL
+ );
+ private workerPool: ComlinkWorker<typeof DedicatedConvertWorker>[] = [];
+ private ready: Promise<void>;
+
+ constructor() {
+ this.ready = this.init();
+ }
+ private async init() {
+ this.workerPool = [];
+ for (let i = 0; i < WORKER_POOL_SIZE; i++) {
+ this.workerPool.push(getDedicatedConvertWorker());
+ }
+ }
+ async convert(fileBlob: Blob): Promise<Blob> {
+ await this.ready;
+ const response = this.convertProcessor.queueUpRequest(() =>
+ retryAsyncFunction<Blob>(async () => {
+ const convertWorker = this.workerPool.shift();
+ const worker = await convertWorker.remote;
+ try {
+ const convertedHEIC = await new Promise<Blob>(
+ (resolve, reject) => {
+ const main = async () => {
+ try {
+ const timeout = setTimeout(() => {
+ reject(Error('wait time exceeded'));
+ }, WAIT_TIME_IN_MICROSECONDS);
+ const startTime = Date.now();
+ const convertedHEIC =
+ await worker.convertHEIC(
+ fileBlob,
+ CONVERT_FORMAT
+ );
+ addLogLine(
+ `originalFileSize:${convertBytesToHumanReadable(
+ fileBlob?.size
+ )},convertedFileSize:${convertBytesToHumanReadable(
+ convertedHEIC?.size
+ )}, heic conversion time: ${
+ Date.now() - startTime
+ }ms `
+ );
+ clearTimeout(timeout);
+ resolve(convertedHEIC);
+ } catch (e) {
+ reject(e);
+ }
+ };
+ main();
+ }
+ );
+ if (!convertedHEIC || convertedHEIC?.size === 0) {
+ logError(
+ Error(`converted heic fileSize is Zero`),
+ 'converted heic fileSize is Zero',
+ {
+ originalFileSize: convertBytesToHumanReadable(
+ fileBlob?.size ?? 0
+ ),
+ convertedFileSize: convertBytesToHumanReadable(
+ convertedHEIC?.size ?? 0
+ ),
+ }
+ );
+ }
+ await new Promise((resolve) => {
+ setTimeout(
+ () => resolve(null),
+ BREATH_TIME_IN_MICROSECONDS
+ );
+ });
+ this.workerPool.push(convertWorker);
+ return convertedHEIC;
+ } catch (e) {
+ logError(e, 'heic conversion failed');
+ convertWorker.terminate();
+ this.workerPool.push(getDedicatedConvertWorker());
+ throw e;
+ }
+ }, WAIT_TIME_BEFORE_NEXT_ATTEMPT_IN_MICROSECONDS)
+ );
+ try {
+ return await response.promise;
+ } catch (e) {
+ if (e.message === CustomError.REQUEST_CANCELLED) {
+ // ignore
+ return null;
+ }
+ throw e;
+ }
+ }
+}
+
+export default new HEICConverter();
diff --git a/apps/cast/src/utils/collection/index.ts b/apps/cast/src/utils/collection/index.ts
index 36b85d5636..7c985d128d 100644
--- a/apps/cast/src/utils/collection/index.ts
+++ b/apps/cast/src/utils/collection/index.ts
@@ -1,8 +1,6 @@
import {
addToCollection,
createAlbum,
- getAllLocalCollections,
- getLocalCollections,
getNonEmptyCollections,
moveToCollection,
removeFromCollection,
@@ -12,8 +10,6 @@ import {
updatePublicCollectionMagicMetadata,
updateSharedCollectionMagicMetadata,
} from 'services/collectionService';
-import { downloadFiles, downloadFilesDesktop } from 'utils/file';
-import { getAllLocalFiles, getLocalFiles } from 'services/fileService';
import { EnteFile } from 'types/file';
import { CustomError } from 'utils/error';
import { User } from 'types/user';
@@ -34,7 +30,6 @@ import {
SYSTEM_COLLECTION_TYPES,
MOVE_TO_NOT_ALLOWED_COLLECTION,
ADD_TO_NOT_ALLOWED_COLLECTION,
- HIDDEN_ITEMS_SECTION,
DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME,
} from 'constants/collection';
import { getUnixTimeInMicroSecondsWithDelta } from 'utils/time';
@@ -43,15 +38,14 @@ import { isArchivedCollection, updateMagicMetadata } from 'utils/magicMetadata';
import { getAlbumsURL } from 'utils/common/apiUtil';
import bs58 from 'bs58';
import { t } from 'i18next';
-import isElectron from 'is-electron';
-import { SetCollectionDownloadProgressAttributes } from 'types/gallery';
-import ElectronService from 'services/electron/common';
-import {
- getCollectionExportPath,
- getUniqueCollectionExportName,
-} from 'utils/export';
-import exportService from 'services/export';
-import { CollectionDownloadProgressAttributes } from 'components/Collections/CollectionDownloadProgress';
+// import { SetCollectionDownloadProgressAttributes } from 'types/gallery';
+// import ElectronService from 'services/electron/common';
+// import {
+// getCollectionExportPath,
+// getUniqueCollectionExportName,
+// } from 'utils/export';
+// import exportService from 'services/export';
+// import { CollectionDownloadProgressAttributes } from 'components/Collections/CollectionDownloadProgress';
export enum COLLECTION_OPS_TYPE {
ADD,
@@ -98,136 +92,136 @@ export function getSelectedCollection(
return collections.find((collection) => collection.id === collectionID);
}
-export async function downloadCollectionHelper(
- collectionID: number,
- setCollectionDownloadProgressAttributes: SetCollectionDownloadProgressAttributes
-) {
- try {
- const allFiles = await getAllLocalFiles();
- const collectionFiles = allFiles.filter(
- (file) => file.collectionID === collectionID
- );
- const allCollections = await getAllLocalCollections();
- const collection = allCollections.find(
- (collection) => collection.id === collectionID
- );
- if (!collection) {
- throw Error('collection not found');
- }
- await downloadCollectionFiles(
- collection.name,
- collection.id,
- isHiddenCollection(collection),
- collectionFiles,
- setCollectionDownloadProgressAttributes
- );
- } catch (e) {
- logError(e, 'download collection failed ');
- }
-}
-
-export async function downloadDefaultHiddenCollectionHelper(
- setCollectionDownloadProgressAttributes: SetCollectionDownloadProgressAttributes
-) {
- try {
- const hiddenCollections = await getLocalCollections('hidden');
- const defaultHiddenCollectionsIds =
- getDefaultHiddenCollectionIDs(hiddenCollections);
- const hiddenFiles = await getLocalFiles('hidden');
- const defaultHiddenCollectionFiles = hiddenFiles.filter((file) =>
- defaultHiddenCollectionsIds.has(file.collectionID)
- );
- await downloadCollectionFiles(
- DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME,
- HIDDEN_ITEMS_SECTION,
- true,
- defaultHiddenCollectionFiles,
- setCollectionDownloadProgressAttributes
- );
- } catch (e) {
- logError(e, 'download hidden files failed ');
- }
-}
-
-async function downloadCollectionFiles(
- collectionName: string,
- collectionID: number,
- isHidden: boolean,
- collectionFiles: EnteFile[],
- setCollectionDownloadProgressAttributes: SetCollectionDownloadProgressAttributes
-) {
- if (!collectionFiles.length) {
- return;
- }
- const canceller = new AbortController();
- const increaseSuccess = () => {
- if (canceller.signal.aborted) return;
- setCollectionDownloadProgressAttributes((prev) => ({
- ...prev,
- success: prev.success + 1,
- }));
- };
- const increaseFailed = () => {
- if (canceller.signal.aborted) return;
- setCollectionDownloadProgressAttributes((prev) => ({
- ...prev,
- failed: prev.failed + 1,
- }));
- };
- const isCancelled = () => canceller.signal.aborted;
- const initialProgressAttributes: CollectionDownloadProgressAttributes = {
- collectionName,
- collectionID,
- isHidden,
- canceller,
- total: collectionFiles.length,
- success: 0,
- failed: 0,
- downloadDirPath: null,
- };
- if (isElectron()) {
- const selectedDir = await ElectronService.selectDirectory();
- if (!selectedDir) {
- return;
- }
- const downloadDirPath = await createCollectionDownloadFolder(
- selectedDir,
- collectionName
- );
- setCollectionDownloadProgressAttributes({
- ...initialProgressAttributes,
- downloadDirPath,
- });
- await downloadFilesDesktop(
- collectionFiles,
- { increaseSuccess, increaseFailed, isCancelled },
- downloadDirPath
- );
- } else {
- setCollectionDownloadProgressAttributes(initialProgressAttributes);
- await downloadFiles(collectionFiles, {
- increaseSuccess,
- increaseFailed,
- isCancelled,
- });
- }
-}
-
-async function createCollectionDownloadFolder(
- downloadDirPath: string,
- collectionName: string
-) {
- const collectionDownloadName = getUniqueCollectionExportName(
- downloadDirPath,
- collectionName
- );
- const collectionDownloadPath = getCollectionExportPath(
- downloadDirPath,
- collectionDownloadName
- );
- await exportService.checkExistsAndCreateDir(collectionDownloadPath);
- return collectionDownloadPath;
-}
+// export async function downloadCollectionHelper(
+// collectionID: number,
+// setCollectionDownloadProgressAttributes: SetCollectionDownloadProgressAttributes
+// ) {
+// try {
+// const allFiles = await getAllLocalFiles();
+// const collectionFiles = allFiles.filter(
+// (file) => file.collectionID === collectionID
+// );
+// const allCollections = await getAllLocalCollections();
+// const collection = allCollections.find(
+// (collection) => collection.id === collectionID
+// );
+// if (!collection) {
+// throw Error('collection not found');
+// }
+// await downloadCollectionFiles(
+// collection.name,
+// collection.id,
+// isHiddenCollection(collection),
+// collectionFiles,
+// setCollectionDownloadProgressAttributes
+// );
+// } catch (e) {
+// logError(e, 'download collection failed ');
+// }
+// }
+
+// export async function downloadDefaultHiddenCollectionHelper(
+// setCollectionDownloadProgressAttributes: SetCollectionDownloadProgressAttributes
+// ) {
+// try {
+// const hiddenCollections = await getLocalCollections('hidden');
+// const defaultHiddenCollectionsIds =
+// getDefaultHiddenCollectionIDs(hiddenCollections);
+// const hiddenFiles = await getLocalFiles('hidden');
+// const defaultHiddenCollectionFiles = hiddenFiles.filter((file) =>
+// defaultHiddenCollectionsIds.has(file.collectionID)
+// );
+// await downloadCollectionFiles(
+// DEFAULT_HIDDEN_COLLECTION_USER_FACING_NAME,
+// HIDDEN_ITEMS_SECTION,
+// true,
+// defaultHiddenCollectionFiles,
+// setCollectionDownloadProgressAttributes
+// );
+// } catch (e) {
+// logError(e, 'download hidden files failed ');
+// }
+// }
+
+// async function downloadCollectionFiles(
+// collectionName: string,
+// collectionID: number,
+// isHidden: boolean,
+// collectionFiles: EnteFile[],
+// setCollectionDownloadProgressAttributes: SetCollectionDownloadProgressAttributes
+// ) {
+// if (!collectionFiles.length) {
+// return;
+// }
+// const canceller = new AbortController();
+// const increaseSuccess = () => {
+// if (canceller.signal.aborted) return;
+// setCollectionDownloadProgressAttributes((prev) => ({
+// ...prev,
+// success: prev.success + 1,
+// }));
+// };
+// const increaseFailed = () => {
+// if (canceller.signal.aborted) return;
+// setCollectionDownloadProgressAttributes((prev) => ({
+// ...prev,
+// failed: prev.failed + 1,
+// }));
+// };
+// const isCancelled = () => canceller.signal.aborted;
+// const initialProgressAttributes: CollectionDownloadProgressAttributes = {
+// collectionName,
+// collectionID,
+// isHidden,
+// canceller,
+// total: collectionFiles.length,
+// success: 0,
+// failed: 0,
+// downloadDirPath: null,
+// };
+// if (isElectron()) {
+// const selectedDir = await ElectronService.selectDirectory();
+// if (!selectedDir) {
+// return;
+// }
+// const downloadDirPath = await createCollectionDownloadFolder(
+// selectedDir,
+// collectionName
+// );
+// setCollectionDownloadProgressAttributes({
+// ...initialProgressAttributes,
+// downloadDirPath,
+// });
+// await downloadFilesDesktop(
+// collectionFiles,
+// { increaseSuccess, increaseFailed, isCancelled },
+// downloadDirPath
+// );
+// } else {
+// setCollectionDownloadProgressAttributes(initialProgressAttributes);
+// await downloadFiles(collectionFiles, {
+// increaseSuccess,
+// increaseFailed,
+// isCancelled,
+// });
+// }
+// }
+
+// async function createCollectionDownloadFolder(
+// downloadDirPath: string,
+// collectionName: string
+// ) {
+// const collectionDownloadName = getUniqueCollectionExportName(
+// downloadDirPath,
+// collectionName
+// );
+// const collectionDownloadPath = getCollectionExportPath(
+// downloadDirPath,
+// collectionDownloadName
+// );
+// await exportService.checkExistsAndCreateDir(collectionDownloadPath);
+// return collectionDownloadPath;
+// }
export function appendCollectionKeyToShareURL(
url: string,
diff --git a/apps/cast/src/utils/comlink/ComlinkConvertWorker.ts b/apps/cast/src/utils/comlink/ComlinkConvertWorker.ts
new file mode 100644
index 0000000000..c5a436728d
--- /dev/null
+++ b/apps/cast/src/utils/comlink/ComlinkConvertWorker.ts
@@ -0,0 +1,30 @@
+import { Remote } from 'comlink';
+import { runningInBrowser } from 'utils/common';
+import { DedicatedConvertWorker } from 'worker/convert.worker';
+import { ComlinkWorker } from './comlinkWorker';
+
+class ComlinkConvertWorker {
+ private comlinkWorkerInstance: Remote<DedicatedConvertWorker>;
+
+ async getInstance() {
+ if (!this.comlinkWorkerInstance) {
+ this.comlinkWorkerInstance = await getDedicatedConvertWorker()
+ .remote;
+ }
+ return this.comlinkWorkerInstance;
+ }
+}
+
+export const getDedicatedConvertWorker = () => {
+ if (runningInBrowser()) {
+ const cryptoComlinkWorker = new ComlinkWorker<
+ typeof DedicatedConvertWorker
+ >(
+ 'ente-convert-worker',
+ new Worker(new URL('worker/convert.worker.ts', import.meta.url))
+ );
+ return cryptoComlinkWorker;
+ }
+};
+
+export default new ComlinkConvertWorker();
diff --git a/apps/cast/src/utils/comlink/ComlinkFFmpegWorker.ts b/apps/cast/src/utils/comlink/ComlinkFFmpegWorker.ts
new file mode 100644
index 0000000000..efc71bf994
--- /dev/null
+++ b/apps/cast/src/utils/comlink/ComlinkFFmpegWorker.ts
@@ -0,0 +1,25 @@
+import { Remote } from 'comlink';
+import { DedicatedFFmpegWorker } from 'worker/ffmpeg.worker';
+import { ComlinkWorker } from './comlinkWorker';
+
+class ComlinkFFmpegWorker {
+ private comlinkWorkerInstance: Promise<Remote<DedicatedFFmpegWorker>>;
+
+ async getInstance() {
+ if (!this.comlinkWorkerInstance) {
+ const comlinkWorker = getDedicatedFFmpegWorker();
+ this.comlinkWorkerInstance = comlinkWorker.remote;
+ }
+ return this.comlinkWorkerInstance;
+ }
+}
+
+const getDedicatedFFmpegWorker = () => {
+ const cryptoComlinkWorker = new ComlinkWorker<typeof DedicatedFFmpegWorker>(
+ 'ente-ffmpeg-worker',
+ new Worker(new URL('worker/ffmpeg.worker.ts', import.meta.url))
+ );
+ return cryptoComlinkWorker;
+};
+
+export default new ComlinkFFmpegWorker();
diff --git a/apps/cast/src/utils/ffmpeg/index.ts b/apps/cast/src/utils/ffmpeg/index.ts
new file mode 100644
index 0000000000..9b4354924f
--- /dev/null
+++ b/apps/cast/src/utils/ffmpeg/index.ts
@@ -0,0 +1,77 @@
+import { NULL_LOCATION } from 'constants/upload';
+import { ParsedExtractedMetadata } from 'types/upload';
+import { validateAndGetCreationUnixTimeInMicroSeconds } from 'utils/time';
+
+enum MetadataTags {
+ CREATION_TIME = 'creation_time',
+ APPLE_CONTENT_IDENTIFIER = 'com.apple.quicktime.content.identifier',
+ APPLE_LIVE_PHOTO_IDENTIFIER = 'com.apple.quicktime.live-photo.auto',
+ APPLE_CREATION_DATE = 'com.apple.quicktime.creationdate',
+ APPLE_LOCATION_ISO = 'com.apple.quicktime.location.ISO6709',
+ LOCATION = 'location',
+}
+
+export function parseFFmpegExtractedMetadata(encodedMetadata: Uint8Array) {
+ const metadataString = new TextDecoder().decode(encodedMetadata);
+ const metadataPropertyArray = metadataString.split('\n');
+ const metadataKeyValueArray = metadataPropertyArray.map((property) =>
+ property.split('=')
+ );
+ const validKeyValuePairs = metadataKeyValueArray.filter(
+ (keyValueArray) => keyValueArray.length === 2
+ ) as Array<[string, string]>;
+
+ const metadataMap = Object.fromEntries(validKeyValuePairs);
+
+ const location = parseAppleISOLocation(
+ metadataMap[MetadataTags.APPLE_LOCATION_ISO] ??
+ metadataMap[MetadataTags.LOCATION]
+ );
+
+ const creationTime = parseCreationTime(
+ metadataMap[MetadataTags.APPLE_CREATION_DATE] ??
+ metadataMap[MetadataTags.CREATION_TIME]
+ );
+ const parsedMetadata: ParsedExtractedMetadata = {
+ creationTime,
+ location: {
+ latitude: location.latitude,
+ longitude: location.longitude,
+ },
+ width: null,
+ height: null,
+ };
+ return parsedMetadata;
+}
+
+function parseAppleISOLocation(isoLocation: string) {
+ let location = NULL_LOCATION;
+ if (isoLocation) {
+ const [latitude, longitude] = isoLocation
+ .match(/(\+|-)\d+\.*\d+/g)
+ .map((x) => parseFloat(x));
+
+ location = { latitude, longitude };
+ }
+ return location;
+}
+
+function parseCreationTime(creationTime: string) {
+ let dateTime = null;
+ if (creationTime) {
+ dateTime = validateAndGetCreationUnixTimeInMicroSeconds(
+ new Date(creationTime)
+ );
+ }
+ return dateTime;
+}
+
+export function splitFilenameAndExtension(filename: string): [string, string] {
+ const lastDotPosition = filename.lastIndexOf('.');
+ if (lastDotPosition === -1) return [filename, null];
+ else
+ return [
+ filename.slice(0, lastDotPosition),
+ filename.slice(lastDotPosition + 1),
+ ];
+}
diff --git a/apps/cast/src/utils/file/index.ts b/apps/cast/src/utils/file/index.ts
index fdfa167c9c..824158edf9 100644
--- a/apps/cast/src/utils/file/index.ts
+++ b/apps/cast/src/utils/file/index.ts
@@ -41,13 +41,13 @@ import {
updateFilePublicMagicMetadata,
} from 'services/fileService';
import isElectron from 'is-electron';
-import imageProcessor from 'services/electron/imageProcessor';
+// import imageProcessor from 'services/electron/imageProcessor';
import { isPlaybackPossible } from 'utils/photoFrame';
import { FileTypeInfo } from 'types/upload';
import { moveToHiddenCollection } from 'services/collectionService';
-import ElectronFSService from 'services/electron/fs';
-import { getFileExportPath, getUniqueFileExportName } from 'utils/export';
+// import ElectronFSService from 'services/electron/fs';
+// import { getFileExportPath, getUniqueFileExportName } from 'utils/export';
const WAIT_TIME_IMAGE_CONVERSION = 30 * 1000;
@@ -454,10 +454,10 @@ export async function getRenderableImage(fileName: string, imageBlob: Blob) {
imageBlob.size
)}`
);
- convertedImageBlob = await imageProcessor.convertToJPEG(
- imageBlob,
- fileName
- );
+ // convertedImageBlob = await imageProcessor.convertToJPEG(
+ // imageBlob,
+ // fileName
+ // );
addLogLine(`${fileName} successfully converted`);
} catch (e) {
try {
@@ -691,57 +691,53 @@ export async function downloadFileDesktop(
file: EnteFile,
downloadPath: string
) {
- let fileStream: ReadableStream<Uint8Array>;
- const fileURL = await DownloadManager.getCachedOriginalFile(file)[0];
- if (!fileURL) {
- fileStream = await DownloadManager.downloadFile(file);
- } else {
- fileStream = await fetch(fileURL).then((res) => res.body);
- }
- const updatedFileStream = await getUpdatedEXIFFileForDownload(
- fileReader,
- file,
- fileStream
- );
-
- if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
- const fileBlob = await new Response(updatedFileStream).blob();
- const livePhoto = await decodeLivePhoto(file, fileBlob);
- const imageExportName = getUniqueFileExportName(
- downloadPath,
- livePhoto.imageNameTitle
- );
- const imageStream = generateStreamFromArrayBuffer(livePhoto.image);
- await ElectronFSService.saveMediaFile(
- getFileExportPath(downloadPath, imageExportName),
- imageStream
- );
- try {
- const videoExportName = getUniqueFileExportName(
- downloadPath,
- livePhoto.videoNameTitle
- );
- const videoStream = generateStreamFromArrayBuffer(livePhoto.video);
- await ElectronFSService.saveMediaFile(
- getFileExportPath(downloadPath, videoExportName),
- videoStream
- );
- } catch (e) {
- ElectronFSService.deleteFile(
- getFileExportPath(downloadPath, imageExportName)
- );
- throw e;
- }
- } else {
- const fileExportName = getUniqueFileExportName(
- downloadPath,
- file.metadata.title
- );
- await ElectronFSService.saveMediaFile(
- getFileExportPath(downloadPath, fileExportName),
- updatedFileStream
- );
- }
+ console.log(fileReader, file, downloadPath);
+ // let fileStream: ReadableStream<Uint8Array>;
+ // const fileURL = await DownloadManager.getCachedOriginalFile(file)[0];
+ // if (!fileURL) {
+ // fileStream = await DownloadManager.downloadFile(file);
+ // } else {
+ // fileStream = await fetch(fileURL).then((res) => res.body);
+ // }
+
+ // if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
+ // const fileBlob = await new Response(updatedFileStream).blob();
+ // const livePhoto = await decodeLivePhoto(file, fileBlob);
+ // const imageExportName = getUniqueFileExportName(
+ // downloadPath,
+ // livePhoto.imageNameTitle
+ // );
+ // const imageStream = generateStreamFromArrayBuffer(livePhoto.image);
+ // await ElectronFSService.saveMediaFile(
+ // getFileExportPath(downloadPath, imageExportName),
+ // imageStream
+ // );
+ // try {
+ // const videoExportName = getUniqueFileExportName(
+ // downloadPath,
+ // livePhoto.videoNameTitle
+ // );
+ // const videoStream = generateStreamFromArrayBuffer(livePhoto.video);
+ // await ElectronFSService.saveMediaFile(
+ // getFileExportPath(downloadPath, videoExportName),
+ // videoStream
+ // );
+ // } catch (e) {
+ // ElectronFSService.deleteFile(
+ // getFileExportPath(downloadPath, imageExportName)
+ // );
+ // throw e;
+ // }
+ // } else {
+ // const fileExportName = getUniqueFileExportName(
+ // downloadPath,
+ // file.metadata.title
+ // );
+ // await ElectronFSService.saveMediaFile(
+ // getFileExportPath(downloadPath, fileExportName),
+ // updatedFileStream
+ // );
+ // }
}
export const isImageOrVideo = (fileType: FILE_TYPE) =>
diff --git a/apps/cast/src/utils/network/index.ts b/apps/cast/src/utils/network/index.ts
new file mode 100644
index 0000000000..832aa841dc
--- /dev/null
+++ b/apps/cast/src/utils/network/index.ts
@@ -0,0 +1,28 @@
+import { sleep } from 'utils/common';
+
+const waitTimeBeforeNextAttemptInMilliSeconds = [2000, 5000, 10000];
+
+export async function retryAsyncFunction<T>(
+ request: (abort?: () => void) => Promise<T>,
+ waitTimeBeforeNextTry?: number[]
+): Promise<T> {
+ if (!waitTimeBeforeNextTry) {
+ waitTimeBeforeNextTry = waitTimeBeforeNextAttemptInMilliSeconds;
+ }
+
+ for (
+ let attemptNumber = 0;
+ attemptNumber <= waitTimeBeforeNextTry.length;
+ attemptNumber++
+ ) {
+ try {
+ const resp = await request();
+ return resp;
+ } catch (e) {
+ if (attemptNumber === waitTimeBeforeNextTry.length) {
+ throw e;
+ }
+ await sleep(waitTimeBeforeNextTry[attemptNumber]);
+ }
+ }
+}
diff --git a/apps/cast/src/utils/photoFrame/index.ts b/apps/cast/src/utils/photoFrame/index.ts
new file mode 100644
index 0000000000..168f90f6e1
--- /dev/null
+++ b/apps/cast/src/utils/photoFrame/index.ts
@@ -0,0 +1,148 @@
+import { FILE_TYPE } from 'constants/file';
+import { EnteFile } from 'types/file';
+import { MergedSourceURL } from 'types/gallery';
+import { logError } from 'utils/sentry';
+
+const WAIT_FOR_VIDEO_PLAYBACK = 1 * 1000;
+
+export async function isPlaybackPossible(url: string): Promise<boolean> {
+ return await new Promise((resolve) => {
+ const t = setTimeout(() => {
+ resolve(false);
+ }, WAIT_FOR_VIDEO_PLAYBACK);
+
+ const video = document.createElement('video');
+ video.addEventListener('canplay', function () {
+ clearTimeout(t);
+ video.remove(); // Clean up the video element
+ // also check for duration > 0 to make sure it is not a broken video
+ if (video.duration > 0) {
+ resolve(true);
+ } else {
+ resolve(false);
+ }
+ });
+ video.addEventListener('error', function () {
+ clearTimeout(t);
+ video.remove();
+ resolve(false);
+ });
+
+ video.src = url;
+ });
+}
+
+export async function playVideo(livePhotoVideo, livePhotoImage) {
+ const videoPlaying = !livePhotoVideo.paused;
+ if (videoPlaying) return;
+ livePhotoVideo.style.opacity = 1;
+ livePhotoImage.style.opacity = 0;
+ livePhotoVideo.load();
+ livePhotoVideo.play().catch(() => {
+ pauseVideo(livePhotoVideo, livePhotoImage);
+ });
+}
+
+export async function pauseVideo(livePhotoVideo, livePhotoImage) {
+ const videoPlaying = !livePhotoVideo.paused;
+ if (!videoPlaying) return;
+ livePhotoVideo.pause();
+ livePhotoVideo.style.opacity = 0;
+ livePhotoImage.style.opacity = 1;
+}
+
+export function updateFileMsrcProps(file: EnteFile, url: string) {
+ file.msrc = url;
+ file.isSourceLoaded = false;
+ file.conversionFailed = false;
+ file.isConverted = false;
+ if (file.metadata.fileType === FILE_TYPE.IMAGE) {
+ file.src = url;
+ } else {
+ file.html = `
+ <div class = 'pswp-item-container'>
+ <img src="${url}"/>
+ </div>
+ `;
+ }
+}
+
+export async function updateFileSrcProps(
+ file: EnteFile,
+ mergedURL: MergedSourceURL
+) {
+ const urls = {
+ original: mergedURL.original.split(','),
+ converted: mergedURL.converted.split(','),
+ };
+ let originalImageURL;
+ let originalVideoURL;
+ let convertedImageURL;
+ let convertedVideoURL;
+ let originalURL;
+ let isConverted;
+ let conversionFailed;
+ if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
+ [originalImageURL, originalVideoURL] = urls.original;
+ [convertedImageURL, convertedVideoURL] = urls.converted;
+ isConverted =
+ originalVideoURL !== convertedVideoURL ||
+ originalImageURL !== convertedImageURL;
+ conversionFailed = !convertedVideoURL || !convertedImageURL;
+ } else if (file.metadata.fileType === FILE_TYPE.VIDEO) {
+ [originalVideoURL] = urls.original;
+ [convertedVideoURL] = urls.converted;
+ isConverted = originalVideoURL !== convertedVideoURL;
+ conversionFailed = !convertedVideoURL;
+ } else if (file.metadata.fileType === FILE_TYPE.IMAGE) {
+ [originalImageURL] = urls.original;
+ [convertedImageURL] = urls.converted;
+ isConverted = originalImageURL !== convertedImageURL;
+ conversionFailed = !convertedImageURL;
+ } else {
+ [originalURL] = urls.original;
+ isConverted = false;
+ conversionFailed = false;
+ }
+
+ const isPlayable = !isConverted || (isConverted && !conversionFailed);
+
+ file.w = window.innerWidth;
+ file.h = window.innerHeight;
+ file.isSourceLoaded = true;
+ file.originalImageURL = originalImageURL;
+ file.originalVideoURL = originalVideoURL;
+ file.isConverted = isConverted;
+ file.conversionFailed = conversionFailed;
+
+ if (!isPlayable) {
+ return;
+ }
+
+ if (file.metadata.fileType === FILE_TYPE.VIDEO) {
+ file.html = `
+ <video controls onContextMenu="return false;">
+ <source src="${convertedVideoURL}" />
+ Your browser does not support the video tag.
+ </video>
+ `;
+ } else if (file.metadata.fileType === FILE_TYPE.LIVE_PHOTO) {
+ file.html = `
+ <div class = 'pswp-item-container'>
+ <img id = "live-photo-image-${file.id}" src="${convertedImageURL}" onContextMenu="return false;"/>
+ <video id = "live-photo-video-${file.id}" loop muted onContextMenu="return false;">
+ <source src="${convertedVideoURL}" />
+ Your browser does not support the video tag.
+ </video>
+ </div>
+ `;
+ } else if (file.metadata.fileType === FILE_TYPE.IMAGE) {
+ file.src = convertedImageURL;
+ } else {
+ logError(
+ Error(`unknown file type - ${file.metadata.fileType}`),
+ 'Unknown file type'
+ );
+ file.src = originalURL;
+ }
+}
diff --git a/apps/cast/src/utils/temp/index.ts b/apps/cast/src/utils/temp/index.ts
new file mode 100644
index 0000000000..589c66d55d
--- /dev/null
+++ b/apps/cast/src/utils/temp/index.ts
@@ -0,0 +1,14 @@
+const CHARACTERS =
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+
+export function generateTempName(length: number, suffix: string) {
+ let tempName = '';
+
+ const charactersLength = CHARACTERS.length;
+ for (let i = 0; i < length; i++) {
+ tempName += CHARACTERS.charAt(
+ Math.floor(Math.random() * charactersLength)
+ );
+ }
+ return `${tempName}-${suffix}`;
+}
diff --git a/apps/cast/src/worker/convert.worker.ts b/apps/cast/src/worker/convert.worker.ts
new file mode 100644
index 0000000000..8dae977a91
--- /dev/null
+++ b/apps/cast/src/worker/convert.worker.ts
@@ -0,0 +1,10 @@
+import * as Comlink from 'comlink';
+import { convertHEIC } from 'services/wasmHeicConverter/wasmHEICConverterClient';
+
+export class DedicatedConvertWorker {
+ async convertHEIC(fileBlob: Blob, format: string) {
+ return convertHEIC(fileBlob, format);
+ }
+}
+
+Comlink.expose(DedicatedConvertWorker, self);
diff --git a/apps/cast/src/worker/ffmpeg.worker.ts b/apps/cast/src/worker/ffmpeg.worker.ts
new file mode 100644
index 0000000000..3c4f4c52e2
--- /dev/null
+++ b/apps/cast/src/worker/ffmpeg.worker.ts
@@ -0,0 +1,15 @@
+import * as Comlink from 'comlink';
+import { WasmFFmpeg } from 'services/wasm/ffmpeg';
+
+export class DedicatedFFmpegWorker {
+ wasmFFmpeg: WasmFFmpeg;
+ constructor() {
+ this.wasmFFmpeg = new WasmFFmpeg();
+ }
+
+ run(cmd, inputFile, outputFileName, dontTimeout) {
+ return this.wasmFFmpeg.run(cmd, inputFile, outputFileName, dontTimeout);
+ }
+}
+
+Comlink.expose(DedicatedFFmpegWorker, self);