summaryrefslogtreecommitdiff
path: root/apps/web/src/services/storage/migrations/v0-to-v1.ts
blob: 7ec388f178193d866e006df27743a415912cef2d (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
import { IndexedDBAdapter } from "@/services/storage/indexeddb-adapter";
import type { SerializedScene } from "@/services/storage/types";
import { buildDefaultScene } from "@/lib/scenes";
import type { TScene } from "@/types/timeline";
import { StorageMigration } from "./base";

type ProjectRecord = Record<string, unknown>;

export class V0toV1Migration extends StorageMigration {
	from = 0;
	to = 1;

	async run(): Promise<void> {
		const projectsAdapter = new IndexedDBAdapter<unknown>(
			"video-editor-projects",
			"projects",
			1,
		);
		const projects = await projectsAdapter.getAll();

		for (const project of projects) {
			if (!isRecord(project)) {
				continue;
			}

			const scenesValue = project.scenes;
			if (Array.isArray(scenesValue) && scenesValue.length > 0) {
				continue;
			}

			const mainScene = buildDefaultScene({ isMain: true, name: "Main scene" });
			const serializedScene = serializeScene({ scene: mainScene });
			const updatedProject: ProjectRecord = {
				...project,
				scenes: [serializedScene],
				currentSceneId: mainScene.id,
				version: 1,
			};

			const updatedAt = new Date().toISOString();
			if (isRecord(project.metadata)) {
				updatedProject.metadata = {
					...project.metadata,
					updatedAt,
				};
			} else {
				updatedProject.updatedAt = updatedAt;
			}

			const projectId = getProjectId({ project: updatedProject });
			if (!projectId) {
				continue;
			}

			await projectsAdapter.set(projectId, updatedProject);
		}
	}
}

function serializeScene({ scene }: { scene: TScene }): SerializedScene {
	return {
		id: scene.id,
		name: scene.name,
		isMain: scene.isMain,
		tracks: scene.tracks,
		bookmarks: scene.bookmarks,
		createdAt: scene.createdAt.toISOString(),
		updatedAt: scene.updatedAt.toISOString(),
	};
}

function getProjectId({ project }: { project: ProjectRecord }): string | null {
	const idValue = project.id;
	if (typeof idValue === "string" && idValue.length > 0) {
		return idValue;
	}

	const metadataValue = project.metadata;
	if (!isRecord(metadataValue)) {
		return null;
	}

	const metadataId = metadataValue.id;
	if (typeof metadataId === "string" && metadataId.length > 0) {
		return metadataId;
	}

	return null;
}

function isRecord(value: unknown): value is ProjectRecord {
	return typeof value === "object" && value !== null;
}