From 11811053fa3d0d04add3b49a1aaab13a328640ce Mon Sep 17 00:00:00 2001 From: Manav Rathi Date: Mon, 13 May 2024 14:40:32 +0530 Subject: [PATCH] Web --- desktop/src/main/stream.ts | 2 +- web/apps/photos/src/utils/native-stream.ts | 57 ++++++++++++++++++++-- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/desktop/src/main/stream.ts b/desktop/src/main/stream.ts index 2c8a8f44b8..3bd3fa7f40 100644 --- a/desktop/src/main/stream.ts +++ b/desktop/src/main/stream.ts @@ -209,4 +209,4 @@ const writeNodeStream = async (filePath: string, fileStream: Readable) => { * * See also: [Note: IPC streams] */ -const convertToMP4 = (token: string | undefined) => {}; +const convertToMP4 = (token?: string) => {}; diff --git a/web/apps/photos/src/utils/native-stream.ts b/web/apps/photos/src/utils/native-stream.ts index 4ed9da753a..8a55fe33d1 100644 --- a/web/apps/photos/src/utils/native-stream.ts +++ b/web/apps/photos/src/utils/native-stream.ts @@ -111,7 +111,58 @@ export const writeStream = async ( const res = await fetch(req); if (!res.ok) - throw new Error( - `Failed to write stream to ${path}: HTTP ${res.status}`, - ); + throw new Error(`Failed to write stream to ${url}: HTTP ${res.status}`); +}; + +/** + * Variant of {@link writeStream} tailored for video conversion. + * + * @param blob The video to convert. + * + * @returns a token that can then be passed to {@link readConvertToMP4Stream} to + * read back the converted video. See: [Note: Convert to MP4]. + */ +export const writeConvertToMP4Stream = async (_: Electron, blob: Blob) => { + const url = "stream://convert-to-mp4"; + + const req = new Request(url, { + method: "POST", + body: blob, + // @ts-expect-error TypeScript's libdom.d.ts does not include the + // "duplex" parameter, e.g. see + // https://github.com/node-fetch/node-fetch/issues/1769. + duplex: "half", + }); + + const res = await fetch(req); + if (!res.ok) + throw new Error(`Failed to write stream to ${url}: HTTP ${res.status}`); + + const token = res.text(); + return token; +}; + +/** + * Variant of {@link readStream} tailored for video conversion. + * + * @param token A token obtained from {@link writeConvertToMP4Stream}. + * + * @returns the contents of the converted video. See: [Note: Convert to MP4]. + */ +export const readConvertToMP4Stream = async ( + _: Electron, + token: string, +): Promise => { + const params = new URLSearchParams({ token }); + const url = new URL(`stream://convert-to-mp4?${params.toString()}`); + + const req = new Request(url, { method: "GET" }); + + const res = await fetch(req); + if (!res.ok) + throw new Error( + `Failed to read stream from ${url}: HTTP ${res.status}`, + ); + + return res.blob(); };