Skip to content

🎥 Make videos programmatically with React

handle content disposition while downloading

Jonny Burgerc421d50a9140
diff --git a/packages/renderer/src/assets/download-and-map-assets-to-file.ts b/packages/renderer/src/assets/download-and-map-assets-to-file.ts
index adca98e983..cfe2983a9e 100644
--- a/packages/renderer/src/assets/download-and-map-assets-to-file.ts
+++ b/packages/renderer/src/assets/download-and-map-assets-to-file.ts
@@ -10,44 +10,58 @@ export type RenderMediaOnDownload = (
src: string
) => ((progress: {percent: number}) => void) | undefined | void;
-const isDownloadingMap: {[src: string]: {[to: string]: boolean} | undefined} =
- {};
+const isDownloadingMap: {
+ [src: string]: {[downloadDir: string]: boolean} | undefined;
+} = {};
const hasBeenDownloadedMap: {
- [src: string]: {[to: string]: boolean} | undefined;
+ [src: string]: {[downloadDir: string]: string | null} | undefined;
} = {};
-const listeners: {[key: string]: {[to: string]: (() => void)[]}} = {};
+const listeners: {[key: string]: {[downloadDir: string]: (() => void)[]}} = {};
-export const waitForAssetToBeDownloaded = (
- src: string,
- to: string
-): Promise<void> => {
- if (hasBeenDownloadedMap[src]?.[to]) {
- return Promise.resolve();
+export const waitForAssetToBeDownloaded = ({
+ src,
+ downloadDir,
+}: {
+ src: string;
+ downloadDir: string;
+}): Promise<string> => {
+ if (hasBeenDownloadedMap[src]?.[downloadDir]) {
+ return Promise.resolve(hasBeenDownloadedMap[src]?.[downloadDir] as string);
}
if (!listeners[src]) {
listeners[src] = {};
}
- if (!listeners[src][to]) {
- listeners[src][to] = [];
+ if (!listeners[src][downloadDir]) {
+ listeners[src][downloadDir] = [];
}
- return new Promise<void>((resolve) => {
- listeners[src][to].push(() => resolve());
+ return new Promise<string>((resolve) => {
+ listeners[src][downloadDir].push(() => {
+ resolve(hasBeenDownloadedMap[src]?.[downloadDir] as string);
+ });
});
};
-const notifyAssetIsDownloaded = (src: string, to: string) => {
+const notifyAssetIsDownloaded = ({
+ src,
+ downloadDir,
+ to,
+}: {
+ src: string;
+ downloadDir: string;
+ to: string;
+}) => {
if (!listeners[src]) {
listeners[src] = {};
}
- if (!listeners[src][to]) {
- listeners[src][to] = [];
+ if (!listeners[src][downloadDir]) {
+ listeners[src][downloadDir] = [];
}
- listeners[src][to].forEach((fn) => fn());
+ listeners[src][downloadDir].forEach((fn) => fn());
if (!isDownloadingMap[src]) {
isDownloadingMap[src] = {};
@@ -55,9 +69,9 @@ const notifyAssetIsDownloaded = (src: string, to: string) => {
(
isDownloadingMap[src] as {
- [to: string]: boolean;
+ [downloadDir: string]: boolean;
}
- )[to] = false;
+ )[downloadDir] = true;
if (!hasBeenDownloadedMap[src]) {
hasBeenDownloadedMap[src] = {};
@@ -65,9 +79,9 @@ const notifyAssetIsDownloaded = (src: string, to: string) => {
(
hasBeenDownloadedMap[src] as {
- [to: string]: boolean;
+ [downloadDir: string]: string | null;
}
- )[to] = true;
+ )[downloadDir] = to;
};
const validateMimeType = (mimeType: string, src: string) => {
@@ -114,17 +128,25 @@ function validateBufferEncoding(
}
}
-const downloadAsset = async (
- src: string,
- to: string,
- onDownload: RenderMediaOnDownload
-) => {
- if (hasBeenDownloadedMap[src]?.[to]) {
- return;
+export const downloadAsset = async ({
+ src,
+ onDownload,
+ downloadDir,
+}: {
+ src: string;
+ onDownload: RenderMediaOnDownload;
+ downloadDir: string;
+}): Promise<string> => {
+ if (Internals.AssetCompression.isAssetCompressed(src)) {
+ return src;
+ }
+
+ if (hasBeenDownloadedMap[src]?.[downloadDir]) {
+ return hasBeenDownloadedMap[src]?.[downloadDir] as string;
}
- if (isDownloadingMap[src]?.[to]) {
- return waitForAssetToBeDownloaded(src, to);
+ if (isDownloadingMap[src]?.[downloadDir]) {
+ return waitForAssetToBeDownloaded({src, downloadDir});
}
if (!isDownloadingMap[src]) {
@@ -133,14 +155,19 @@ const downloadAsset = async (
(
isDownloadingMap[src] as {
- [to: string]: boolean;
+ [downloadDir: string]: boolean;
}
- )[to] = true;
+ )[downloadDir] = true;
const onProgress = onDownload(src);
- ensureOutputDirectory(to);
if (src.startsWith('data:')) {
+ const output = getSanitizedFilenameForAssetUrl({
+ contentDisposition: null,
+ downloadDir,
+ src,
+ });
+ ensureOutputDirectory(output);
const [assetDetails, assetData] = src.substring('data:'.length).split(',');
if (!assetDetails.includes(';')) {
const errMessage = [
@@ -158,17 +185,23 @@ const downloadAsset = async (
validateBufferEncoding(encoding, src);
const buff = Buffer.from(assetData, encoding);
- await fs.promises.writeFile(to, buff);
- notifyAssetIsDownloaded(src, to);
- return;
+ await fs.promises.writeFile(output, buff);
+ notifyAssetIsDownloaded({src, downloadDir, to: output});
+ return output;
}
- await downloadFile(src, to, ({progress}) => {
- onProgress?.({
- percent: progress,
- });
+ const {to} = await downloadFile({
+ url: src,
+ downloadDir,
+ onProgress: ({progress}) => {
+ onProgress?.({
+ percent: progress,
+ });
+ },
});
- notifyAssetIsDownloaded(src, to);
+ notifyAssetIsDownloaded({src, downloadDir, to});
+
+ return to;
};
export const markAllAssetsAsDownloaded = () => {
@@ -181,18 +214,50 @@ export const markAllAssetsAsDownloaded = () => {
});
};
+export const getFilename = ({
+ contentDisposition,
+ src,
+}: {
+ src: string;
+ contentDisposition: string | null;
+}): {pathname: string; search: string} => {
+ const filenameProbe = 'filename=';
+ if (contentDisposition?.includes(filenameProbe)) {
+ const start = contentDisposition.indexOf(filenameProbe);
+ const onlyFromFileName = contentDisposition.substring(
+ start + filenameProbe.length
+ );
+
+ const hasSemi = onlyFromFileName.indexOf(';');
+ if (hasSemi === -1) {
+ return {pathname: onlyFromFileName.trim(), search: ''};
+ }
+
+ return {
+ search: '',
+ pathname: onlyFromFileName.substring(0, hasSemi).trim(),
+ };
+ }
+
+ const {pathname, search} = new URL(src);
+
+ return {pathname, search};
+};
+
export const getSanitizedFilenameForAssetUrl = ({
src,
downloadDir,
+ contentDisposition,
}: {
src: string;
downloadDir: string;
+ contentDisposition: string | null;
}) => {
if (Internals.AssetCompression.isAssetCompressed(src)) {
return src;
}
- const {pathname, search} = new URL(src);
+ const {pathname, search} = getFilename({contentDisposition, src});
const split = pathname.split('.');
const fileExtension =
@@ -203,10 +268,10 @@ export const getSanitizedFilenameForAssetUrl = ({
'0.',
''
);
- return path.join(
- downloadDir,
- sanitizeFilePath(hashedFileName + fileExtension)
- );
+
+ const filename = hashedFileName + fileExtension;
+
+ return path.join(downloadDir, sanitizeFilePath(filename));
};
export const downloadAndMapAssetsToFileUrl = async ({
@@ -218,7 +283,7 @@ export const downloadAndMapAssetsToFileUrl = async ({
downloadDir: string;
onDownload: RenderMediaOnDownload;
}): Promise<TAsset> => {
- const newSrc = await startDownloadForSrc({
+ const newSrc = await downloadAsset({
src: asset.src,
downloadDir,
onDownload,
@@ -229,20 +294,3 @@ export const downloadAndMapAssetsToFileUrl = async ({
src: newSrc,
};
};
-
-export const startDownloadForSrc = async ({
- src,
- downloadDir,
- onDownload,
-}: {
- src: string;
- downloadDir: string;
- onDownload: RenderMediaOnDownload;
-}) => {
- const newSrc = getSanitizedFilenameForAssetUrl({downloadDir, src});
- if (!Internals.AssetCompression.isAssetCompressed(newSrc)) {
- await downloadAsset(src, newSrc, onDownload);
- }
-
- return newSrc;
-};
diff --git a/packages/renderer/src/assets/download-file.ts b/packages/renderer/src/assets/download-file.ts
index 7698470715..401782f4fb 100644
--- a/packages/renderer/src/assets/download-file.ts
+++ b/packages/renderer/src/assets/download-file.ts
@@ -1,27 +1,41 @@
import {createWriteStream} from 'fs';
+import {ensureOutputDirectory} from '../ensure-output-directory';
+import {getSanitizedFilenameForAssetUrl} from './download-and-map-assets-to-file';
import {readFile} from './read-file';
-export const downloadFile = (
- url: string,
- to: string,
+export const downloadFile = ({
+ onProgress,
+ url,
+ downloadDir,
+}: {
+ url: string;
+ downloadDir: string;
onProgress:
| ((progress: {
progress: number;
downloaded: number;
totalSize: number;
}) => void)
- | undefined
-) => {
- return new Promise<{sizeInBytes: number}>((resolve, reject) => {
+ | undefined;
+}) => {
+ return new Promise<{sizeInBytes: number; to: string}>((resolve, reject) => {
readFile(url)
.then((res) => {
+ const contentDisposition = res.headers['content-disposition'] ?? null;
+ const to = getSanitizedFilenameForAssetUrl({
+ downloadDir,
+ src: url,
+ contentDisposition,
+ });
+ ensureOutputDirectory(to);
+
const totalSize = Number(res.headers['content-length']);
const writeStream = createWriteStream(to);
// Listen to 'close' event instead of more
// concise method to avoid this problem
// https://github.com/remotion-dev/remotion/issues/384#issuecomment-844398183
- writeStream.on('close', () => resolve({sizeInBytes: totalSize}));
+ writeStream.on('close', () => resolve({sizeInBytes: totalSize, to}));
writeStream.on('error', (err) => reject(err));
let downloaded = 0;
res.pipe(writeStream).on('error', (err) => reject(err));
diff --git a/packages/renderer/src/offthread-video-server.ts b/packages/renderer/src/offthread-video-server.ts
index a44aeb0ace..6c34e5d9c8 100644
--- a/packages/renderer/src/offthread-video-server.ts
+++ b/packages/renderer/src/offthread-video-server.ts
@@ -3,11 +3,7 @@ import type {FfmpegExecutable, OffthreadVideoImageFormat} from 'remotion';
import {Internals} from 'remotion';
import {URLSearchParams} from 'url';
import type {RenderMediaOnDownload} from './assets/download-and-map-assets-to-file';
-import {
- getSanitizedFilenameForAssetUrl,
- startDownloadForSrc,
- waitForAssetToBeDownloaded,
-} from './assets/download-and-map-assets-to-file';
+import {downloadAsset} from './assets/download-and-map-assets-to-file';
import {extractFrameFromVideo} from './extract-frame-from-video';
export const extractUrlAndSourceFromUrl = (url: string) => {
@@ -76,16 +72,8 @@ export const startOffthreadVideoServer = ({
`image/${imageFormat === 'jpeg' ? 'jpg' : 'png'}`
);
- const to = getSanitizedFilenameForAssetUrl({downloadDir, src});
-
- startDownloadForSrc({src, downloadDir, onDownload}).catch((err) => {
- onError(
- new Error(`Error while downloading asset: ${(err as Error).stack}`)
- );
- });
-
- waitForAssetToBeDownloaded(src, to)
- .then(() => {
+ downloadAsset({src, downloadDir, onDownload})
+ .then((to) => {
return extractFrameFromVideo({
time,
src: to,
diff --git a/packages/renderer/src/test/download-file.test.ts b/packages/renderer/src/test/download-file.test.ts
index f0799293d2..e4a12003ea 100644
--- a/packages/renderer/src/test/download-file.test.ts
+++ b/packages/renderer/src/test/download-file.test.ts
@@ -1,12 +1,15 @@
import fs from 'fs';
import {tmpdir} from 'os';
-import path from 'path';
import {downloadFile} from '../assets/download-file';
test('Should be able to download file', async () => {
- const output = path.join(tmpdir(), 'tmp.html');
- await downloadFile('https://example.net/', output, () => undefined);
- const data = await fs.promises.readFile(output, 'utf8');
+ const downloadDir = tmpdir();
+ const {to} = await downloadFile({
+ url: 'https://example.net/',
+ downloadDir,
+ onProgress: () => undefined,
+ });
+ const data = await fs.promises.readFile(to, 'utf8');
expect(data).toMatch(
/This domain is for use in illustrative examples in documents/
@@ -14,8 +17,12 @@ test('Should be able to download file', async () => {
});
test('Should fail to download invalid files', async () => {
- const output = path.join(tmpdir(), 'invalid.html');
+ const downloadDir = tmpdir();
await expect(() =>
- downloadFile('https://thisdomain.doesnotexist', output, () => undefined)
+ downloadFile({
+ downloadDir,
+ url: 'https://thisdomain.doesnotexist',
+ onProgress: () => undefined,
+ })
).rejects.toThrow(/ENOTFOUND/);
});
diff --git a/packages/renderer/src/test/handle-weird-file-names.test.ts b/packages/renderer/src/test/handle-weird-file-names.test.ts
index 9e7480a19f..cdff3fa67c 100644
--- a/packages/renderer/src/test/handle-weird-file-names.test.ts
+++ b/packages/renderer/src/test/handle-weird-file-names.test.ts
@@ -4,6 +4,7 @@ test('Should sanitize weird file names when downloading', () => {
const newSrc = getSanitizedFilenameForAssetUrl({
src: 'http://gtts-api.miniggiodev.fr/Ici+Japon+Corp.?lang=ja',
downloadDir: '/var/tmp',
+ contentDisposition: null,
});
expect(newSrc).toBe(
process.platform === 'win32'
@@ -16,15 +17,35 @@ test('Should give different file names based on different url query parameters',
const asset1 = getSanitizedFilenameForAssetUrl({
src: 'https://gtts-api.miniggiodev.fr/Ici+Japon+Corp.mp4?hi=1',
downloadDir: '',
+ contentDisposition: null,
});
const sameAgain = getSanitizedFilenameForAssetUrl({
src: 'https://gtts-api.miniggiodev.fr/Ici+Japon+Corp.mp4?hi=1',
downloadDir: '',
+ contentDisposition: null,
});
const differentAsset = getSanitizedFilenameForAssetUrl({
src: 'https://gtts-api.miniggiodev.fr/Ici+Japon+Corp.mp4?hi=2',
downloadDir: '',
+ contentDisposition: null,
});
expect(asset1).toEqual(sameAgain);
expect(asset1).not.toEqual(differentAsset);
});
+
+test('Should give different file names based on different url query parameters', () => {
+ const asset1 = getSanitizedFilenameForAssetUrl({
+ src: 'https://gtts-api.miniggiodev.fr/Ici+Japon+Corp.mp4?hi=1',
+ downloadDir: 'dl',
+ contentDisposition:
+ 'attachment; filename=notjacksondatiras_1656689770_musicaldown.com.mp4; otherstuff',
+ });
+ expect(asset1).toEqual('dl/2276125883217901.mp4');
+ const asset2 = getSanitizedFilenameForAssetUrl({
+ src: 'https://gtts-api.miniggiodev.fr/Ici+Japon+Corp.mp4?hi=1',
+ downloadDir: 'dl',
+ contentDisposition:
+ 'attachment; filename=notjacksondatiras_1656689770_musicaldown.com.mp4',
+ });
+ expect(asset2).toEqual('dl/2276125883217901.mp4');
+});