-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathofflineVideo.ts
More file actions
52 lines (46 loc) · 1.6 KB
/
offlineVideo.ts
File metadata and controls
52 lines (46 loc) · 1.6 KB
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
import { openDB } from 'idb';
const DB_NAME = 'offline-videos';
const STORE_NAME = 'videos';
// Generate a crypto key for encryption/decryption (per user/session)
async function getKey(): Promise<CryptoKey> {
const keyMaterial = await window.crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
);
return keyMaterial;
}
export async function encryptBlob(blob: Blob): Promise<{ data: ArrayBuffer; iv: Uint8Array }> {
const key = await getKey();
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const data = await blob.arrayBuffer();
const encrypted = await window.crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
data
);
return { data: encrypted, iv };
}
export async function decryptBlob(encrypted: ArrayBuffer, iv: Uint8Array): Promise<Blob> {
const key = await getKey();
const decrypted = await window.crypto.subtle.decrypt(
{ name: 'AES-GCM', iv },
key,
encrypted
);
return new Blob([decrypted]);
}
export async function saveVideoToIndexedDB(contentId: number, encrypted: ArrayBuffer, iv: Uint8Array) {
const db = await openDB(DB_NAME, 1, {
upgrade(db) {
db.createObjectStore(STORE_NAME);
},
});
await db.put(STORE_NAME, { encrypted, iv: Array.from(iv) }, contentId);
}
export async function getVideoFromIndexedDB(contentId: number): Promise<{ encrypted: ArrayBuffer; iv: Uint8Array } | null> {
const db = await openDB(DB_NAME, 1);
const result = await db.get(STORE_NAME, contentId);
if (!result) return null;
return { encrypted: result.encrypted, iv: new Uint8Array(result.iv) };
}