summaryrefslogtreecommitdiff
path: root/apps/web/src/project/transfer/container.ts
blob: 8aee8cf8aa834cc946db35fc92ff387dc449e6e5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
import type { MediaType } from "@/media/types";
import { isRecord } from "@/services/storage/migrations/transformers/utils";

/**
 * Single-file project container (`.ocp`) — a zip archive holding:
 *
 * - `project.json` — the SerializedProject document exactly as the storage
 *   layer persists it (including its `version` number).
 * - `media/manifest.json` — metadata needed to rebuild every media File
 *   byte-identically (original name, MIME type, lastModified) plus the
 *   media-store metadata (dimensions, duration, thumbnail, …).
 * - `media/<assetId>-<sanitized name>` — one entry per media asset holding
 *   the original File bytes (stored, never re-encoded).
 */

export const PROJECT_ARCHIVE_EXTENSION = ".ocp";
export const PROJECT_JSON_ENTRY = "project.json";
export const MEDIA_MANIFEST_ENTRY = "media/manifest.json";
export const MEDIA_ENTRY_PREFIX = "media/";

export class ProjectArchiveError extends Error {
	constructor({ message }: { message: string }) {
		super(message);
		this.name = "ProjectArchiveError";
	}
}

export interface ArchivedMediaMetadata {
	id: string;
	name: string;
	mediaType: MediaType;
	fileType: string;
	lastModified: number;
	width?: number;
	height?: number;
	duration?: number;
	ephemeral?: boolean;
	thumbnailUrl?: string;
}

export interface ArchivedMediaEntry extends ArchivedMediaMetadata {
	entry: string;
}

export interface ArchiveMediaInput {
	metadata: ArchivedMediaMetadata;
	data: Uint8Array;
}

export interface ParsedProjectArchive {
	project: Record<string, unknown>;
	media: ArchivedMediaEntry[];
	readMediaData: ({ entry }: { entry: string }) => Uint8Array;
}

const MEDIA_MANIFEST_VERSION = 1;

export function sanitizeFileName({ name }: { name: string }): string {
	const sanitized = name
		.trim()
		.replace(/[^\w.-]+/g, "_")
		.replace(/^\.+/, "");
	return sanitized.length > 0 ? sanitized : "file";
}

export function buildMediaEntryName({
	assetId,
	name,
}: {
	assetId: string;
	name: string;
}): string {
	return `${MEDIA_ENTRY_PREFIX}${assetId}-${sanitizeFileName({ name })}`;
}

export function buildProjectArchive({
	projectJson,
	media,
}: {
	projectJson: string;
	media: ArchiveMediaInput[];
}): Uint8Array {
	const manifest: ArchivedMediaEntry[] = media.map(({ metadata }) => ({
		...metadata,
		entry: buildMediaEntryName({
			assetId: metadata.id,
			name: metadata.name,
		}),
	}));

	const files: Record<string, [Uint8Array, { level: 0 }]> = {
		[PROJECT_JSON_ENTRY]: [strToU8(projectJson), { level: 0 }],
		[MEDIA_MANIFEST_ENTRY]: [
			strToU8(JSON.stringify({ version: MEDIA_MANIFEST_VERSION, media: manifest })),
			{ level: 0 },
		],
	};
	for (const [index, { data }] of media.entries()) {
		const entry = manifest.at(index)?.entry;
		if (!entry) continue;
		files[entry] = [data, { level: 0 }];
	}

	return zipSync(files);
}

export function parseProjectArchive({
	archive,
}: {
	archive: Uint8Array;
}): ParsedProjectArchive {
	let files: Record<string, Uint8Array>;
	try {
		files = unzipSync(archive);
	} catch {
		throw new ProjectArchiveError({
			message: "Not a valid project archive (unreadable zip file)",
		});
	}

	const projectBytes = files[PROJECT_JSON_ENTRY];
	if (!projectBytes) {
		throw new ProjectArchiveError({
			message: "Not a valid project archive (project.json is missing)",
		});
	}

	let project: unknown;
	try {
		project = JSON.parse(strFromU8(projectBytes));
	} catch {
		throw new ProjectArchiveError({
			message: "Not a valid project archive (project.json is not valid JSON)",
		});
	}
	if (!isRecord(project) || Array.isArray(project)) {
		throw new ProjectArchiveError({
			message: "Not a valid project archive (project.json is not a project)",
		});
	}

	const media = parseMediaManifest({ files });

	return {
		project,
		media,
		readMediaData: ({ entry }: { entry: string }) => {
			const data = files[entry];
			if (!data) {
				throw new ProjectArchiveError({
					message: `Media file is missing from the archive (${entry})`,
				});
			}
			return data;
		},
	};
}

function parseMediaManifest({
	files,
}: {
	files: Record<string, Uint8Array>;
}): ArchivedMediaEntry[] {
	const manifestBytes = files[MEDIA_MANIFEST_ENTRY];
	if (!manifestBytes) {
		const hasMediaEntries = Object.keys(files).some((name) =>
			name.startsWith(MEDIA_ENTRY_PREFIX),
		);
		if (hasMediaEntries) {
			throw new ProjectArchiveError({
				message: "Not a valid project archive (media manifest is missing)",
			});
		}
		return [];
	}

	let parsed: unknown;
	try {
		parsed = JSON.parse(strFromU8(manifestBytes));
	} catch {
		throw new ProjectArchiveError({
			message: "Not a valid project archive (media manifest is not valid JSON)",
		});
	}
	if (!isRecord(parsed) || Array.isArray(parsed) || !Array.isArray(parsed.media)) {
		throw new ProjectArchiveError({
			message: "Not a valid project archive (media manifest is malformed)",
		});
	}

	return parsed.media.map((value) => parseManifestEntry({ value, files }));
}

function parseManifestEntry({
	value,
	files,
}: {
	value: unknown;
	files: Record<string, Uint8Array>;
}): ArchivedMediaEntry {
	const invalid = (reason: string): ProjectArchiveError =>
		new ProjectArchiveError({
			message: `Not a valid project archive (media manifest entry ${reason})`,
		});

	if (!isRecord(value) || Array.isArray(value)) throw invalid("is malformed");
	const { id, name, entry, mediaType, fileType, lastModified } = value;
	if (typeof id !== "string" || id.length === 0) throw invalid("has no id");
	if (typeof name !== "string") throw invalid(`(${id}) has no name`);
	if (
		typeof entry !== "string" ||
		!entry.startsWith(MEDIA_ENTRY_PREFIX) ||
		entry.includes("..")
	) {
		throw invalid(`(${id}) has an invalid file path`);
	}
	if (mediaType !== "image" && mediaType !== "video" && mediaType !== "audio") {
		throw invalid(`(${id}) has an invalid media type`);
	}
	if (typeof fileType !== "string") throw invalid(`(${id}) has no file type`);
	if (typeof lastModified !== "number" || !Number.isFinite(lastModified)) {
		throw invalid(`(${id}) has no last-modified timestamp`);
	}
	if (!files[entry]) {
		throw new ProjectArchiveError({
			message: `Not a valid project archive (media file ${entry} is missing)`,
		});
	}

	const { width, height, duration, ephemeral, thumbnailUrl } = value;
	return {
		id,
		name,
		entry,
		mediaType,
		fileType,
		lastModified,
		...(typeof width === "number" && { width }),
		...(typeof height === "number" && { height }),
		...(typeof duration === "number" && { duration }),
		...(typeof ephemeral === "boolean" && { ephemeral }),
		...(typeof thumbnailUrl === "string" && { thumbnailUrl }),
	};
}