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

type ProjectRecord = Record<string, unknown>;

export class V2toV3Migration extends StorageMigration {
	from = 2;
	to = 3;

	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 projectId = getProjectId({ project });
			if (!projectId) {
				continue;
			}

			if (isV3Project({ project })) {
				continue;
			}

			const scenes = getScenes({ project });
			const duration = getProjectDurationFromScenes({ scenes });

			const metadataValue = project.metadata;
			const metadata = isRecord(metadataValue)
				? { ...metadataValue, duration }
				: { duration };

			const migratedProject = {
				...project,
				metadata,
				version: 3,
			};

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

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 getScenes({ project }: { project: ProjectRecord }): TScene[] {
	const scenesValue = project.scenes;
	if (!Array.isArray(scenesValue)) {
		return [];
	}

	return scenesValue.filter(isRecord) as unknown as TScene[];
}

function isV3Project({ project }: { project: ProjectRecord }): boolean {
	const versionValue = project.version;
	if (typeof versionValue === "number" && versionValue >= 3) {
		return true;
	}

	return isRecord(project.metadata) && typeof project.metadata.duration === "number";
}

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