1 | import FileSystem from './fs/index'
|
2 |
|
3 | import * as cidLog from './common/cid-log'
|
4 | import * as debug from './common/debug'
|
5 | import * as dataRoot from './data-root'
|
6 | import * as ucan from './ucan/internal'
|
7 |
|
8 | import { Branch } from './path'
|
9 | import { Maybe, authenticatedUsername } from './common/index'
|
10 | import { Permissions } from './ucan/permissions'
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | export async function loadFileSystem(
|
25 | permissions: Maybe<Permissions>,
|
26 | username?: string,
|
27 | rootKey?: string
|
28 | ): Promise<FileSystem> {
|
29 | let cid, fs
|
30 |
|
31 |
|
32 | username = username || (await authenticatedUsername() || undefined)
|
33 | if (!username) throw new Error("User hasn't authenticated yet")
|
34 |
|
35 |
|
36 | await ucan.store([])
|
37 |
|
38 |
|
39 | const dataCid = navigator.onLine ? await dataRoot.lookup(username) : null
|
40 | const [ logIdx, logLength ] = dataCid ? await cidLog.index(dataCid) : [ -1, 0 ]
|
41 |
|
42 | if (!navigator.onLine) {
|
43 |
|
44 | cid = await cidLog.newest()
|
45 |
|
46 | } else if (!dataCid) {
|
47 |
|
48 | cid = await cidLog.newest()
|
49 | if (cid) debug.log("📓 No DNSLink, using local CID:", cid)
|
50 | else debug.log("📓 Creating a new file system")
|
51 |
|
52 | } else if (logIdx === 0) {
|
53 |
|
54 | cid = dataCid
|
55 | debug.log("📓 DNSLink is up to date:", cid)
|
56 |
|
57 | } else if (logIdx > 0) {
|
58 |
|
59 | cid = await cidLog.newest()
|
60 | const idxLog = logIdx === 1 ? "1 newer local entry" : logIdx + " newer local entries"
|
61 | debug.log("📓 DNSLink is outdated (" + idxLog + "), using local CID:", cid)
|
62 |
|
63 | } else {
|
64 |
|
65 | cid = dataCid
|
66 | await cidLog.add(cid)
|
67 | debug.log("📓 DNSLink is newer:", cid)
|
68 |
|
69 | }
|
70 |
|
71 |
|
72 | const p = permissions || undefined
|
73 |
|
74 | fs = cid ? await FileSystem.fromCID(cid, { permissions: p }) : null
|
75 | if (fs) return fs
|
76 |
|
77 |
|
78 | if (!rootKey) throw new Error("Can't make new filesystem without a root AES key")
|
79 | fs = await FileSystem.empty({ permissions: p, rootKey })
|
80 | await addSampleData(fs)
|
81 |
|
82 |
|
83 | return fs
|
84 | }
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 | async function addSampleData(fs: FileSystem): Promise<void> {
|
92 | await fs.mkdir({ directory: [ Branch.Private, "Apps" ] })
|
93 | await fs.mkdir({ directory: [ Branch.Private, "Audio" ] })
|
94 | await fs.mkdir({ directory: [ Branch.Private, "Documents" ] })
|
95 | await fs.mkdir({ directory: [ Branch.Private, "Photos" ] })
|
96 | await fs.mkdir({ directory: [ Branch.Private, "Video" ] })
|
97 | await fs.publish()
|
98 | }
|