/
db.ts
81 lines (72 loc) · 2.07 KB
/
db.ts
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
import Dexie from '@cliqz-oss/dexie';
import { DatManifest } from './dat';
import { IDat } from '@sammacbeth/dat-types/lib/dat';
import createDatArchive from '@sammacbeth/dat-archive';
export default class Database extends Dexie {
library: Dexie.Table<IDatInfo, string>
dnsCache: Dexie.Table<IDNSCacheEntry, string>
keyCache: Map<string, number>
constructor() {
super('dat-db');
this.version(1).stores({
library: 'key, seedingMode, isInLibrary, seedUntil',
dnsCache: 'host, address',
});
this.keyCache = new Map();
this.library = this.table('library');
this.dnsCache = this.table('dnsCache');
}
async updateDat(dat: IDat, seedTime: number) {
await dat.ready;
const now = Date.now();
const key = dat.drive.key.toString('hex');
const lastUpdate = this.keyCache.get(key);
const exists = !!lastUpdate || !!(await this.library.get(key));
if (!exists) {
// create new entry
await this.library.put({
key,
isOwner: dat.drive.writable,
isInLibrary: dat.drive.writable ? 1 : 0,
firstUsed: now,
lastUsed: now,
seedingMode: dat.drive.writable ? 1 : 0,
seedUntil: now + seedTime,
size: 0,
});
} else if (lastUpdate < now - 30000) {
// update last used info
await this.library.update(key, {
lastUsed: now,
seedUntil: now + seedTime,
});
}
if (!exists || lastUpdate < now - 30000) {
this.keyCache.set(key, now);
// update metadata for this dat
try {
const archive = createDatArchive(dat.drive);
const { title, description, type, size } = await archive.getInfo();
await this.library.update(key, {
title, description, type, size
});
} catch (e) {
}
}
}
}
export interface IDatInfo extends DatManifest {
key: string
isOwner: boolean
isInLibrary: number
firstUsed: number
lastUsed: number
seedingMode: number
seedUntil: number
size: number
}
export interface IDNSCacheEntry {
host: string
address: string
expires: number
}