-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDatArchive.js
397 lines (327 loc) · 9.84 KB
/
DatArchive.js
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
// Ripped out of node-dat-archive
const path = require('path')
const pda = require('pauls-dat-api')
const parseURL = require('url-parse')
const concat = require('concat-stream')
const pump = require('pump')
const { timer, toEventTarget } = require('node-dat-archive/lib/util')
const {
DAT_MANIFEST_FILENAME,
DAT_VALID_PATH_REGEX,
DEFAULT_DAT_API_TIMEOUT
} = require('node-dat-archive/lib/const')
const {
ArchiveNotWritableError,
ProtectedFileNotWritableError,
InvalidPathError
} = require('beaker-error-constants')
const hyperdrive = require('hyperdrive')
const crypto = require('hypercore/lib/crypto')
const REPLICATION_DELAY = 3000
const to = (opts) =>
(opts && typeof opts.timeout !== 'undefined')
? opts.timeout
: DEFAULT_DAT_API_TIMEOUT
class DatArchive {
static setManager (manager) {
DatArchive._manager = manager
}
constructor (url) {
let version = null
let key = null
this._loadPromise = getURLData(url).then(async (urlData) => {
const options = {
sparse: true
}
if (urlData.key) {
key = urlData.key
version = urlData.version
} else {
const keypair = crypto.keyPair()
key = keypair.publicKey
options.secretKey = keypair.secretKey
}
const storage = DatArchive._manager.getStorage(key.toString('hex'))
const archive = hyperdrive(storage, key, options)
this._archive = archive
await waitReady(archive)
this._checkout = version ? archive.checkout(version) : archive
this.url = this.url || `dat://${archive.key.toString('hex')}`
const stream = this._replicate()
await waitOpen(stream)
if (url) {
await waitReplication()
}
})
}
_replicate () {
const archive = this._archive
const key = archive.key.toString('hex')
const stream = DatArchive._manager.replicate(key)
pump(stream, archive.replicate({
live: true,
upload: true
}), stream, (err) => {
console.error(err)
this._replicate()
})
this._stream = stream
return stream
}
async getInfo (url, opts = {}) {
return timer(to(opts), async () => {
await this._loadPromise
// read manifest
var manifest
try {
manifest = await pda.readManifest(this._checkout)
} catch (e) {
manifest = {}
}
// return
return {
key: this._archive.key.toString('hex'),
url: this.url,
isOwner: this._archive.writable,
// state
version: this._checkout.version,
peers: this._archive.metadata.peers.length,
mtime: 0,
size: 0,
// manifest
title: manifest.title,
description: manifest.description,
type: manifest.type,
author: manifest.author
}
})
}
async diff () {
// noop
return []
}
async commit () {
// noop
return []
}
async revert () {
// noop
return []
}
async history (opts = {}) {
return timer(to(opts), async () => {
await this._loadPromise
var reverse = opts.reverse === true
var { start, end } = opts
// if reversing the output, modify start/end
start = start || 0
end = end || this._checkout.metadata.length
if (reverse) {
// swap values
let t = start
start = end
end = t
// start from the end
start = this._checkout.metadata.length - start
end = this._checkout.metadata.length - end
}
return new Promise((resolve, reject) => {
var stream = this._checkout.history({ live: false, start, end })
stream.pipe(concat({ encoding: 'object' }, values => {
values = values.map(massageHistoryObj)
if (reverse) values.reverse()
resolve(values)
}))
stream.on('error', reject)
})
})
}
async stat (filepath, opts = {}) {
filepath = massageFilepath(filepath)
return timer(to(opts), async () => {
await this._loadPromise
return pda.stat(this._checkout, filepath)
})
}
async readFile (filepath, opts = {}) {
filepath = massageFilepath(filepath)
return timer(to(opts), async () => {
await this._loadPromise
return pda.readFile(this._checkout, filepath, opts)
})
}
async writeFile (filepath, data, opts = {}) {
filepath = massageFilepath(filepath)
return timer(to(opts), async () => {
await this._loadPromise
if (this._version) throw new ArchiveNotWritableError('Cannot modify a historic version')
await assertWritePermission(this._archive)
await assertValidFilePath(filepath)
await assertUnprotectedFilePath(filepath)
return pda.writeFile(this._archive, filepath, data, opts)
})
}
async unlink (filepath) {
filepath = massageFilepath(filepath)
return timer(to(), async () => {
await this._loadPromise
if (this._version) throw new ArchiveNotWritableError('Cannot modify a historic version')
await assertWritePermission(this._archive)
await assertUnprotectedFilePath(filepath)
return pda.unlink(this._archive, filepath)
})
}
async download (filepath, opts = {}) {
filepath = massageFilepath(filepath)
return timer(to(opts), async (checkin) => {
await this._loadPromise
if (this._version) throw new Error('Not yet supported: can\'t download() old versions yet. Sorry!') // TODO
if (this._archive.writable) {
return // no need to download
}
return pda.download(this._archive, filepath)
})
}
async readdir (filepath, opts = {}) {
filepath = massageFilepath(filepath)
return timer(to(opts), async () => {
await this._loadPromise
var names = await pda.readdir(this._checkout, filepath, opts)
if (opts.stat) {
for (let i = 0; i < names.length; i++) {
names[i] = {
name: names[i],
stat: await pda.stat(this._checkout, path.join(filepath, names[i]))
}
}
}
return names
})
}
async mkdir (filepath) {
filepath = massageFilepath(filepath)
return timer(to(), async () => {
await this._loadPromise
if (this._version) throw new ArchiveNotWritableError('Cannot modify a historic version')
await assertWritePermission(this._archive)
await assertValidPath(filepath)
await assertUnprotectedFilePath(filepath)
return pda.mkdir(this._archive, filepath)
})
}
async rmdir (filepath, opts = {}) {
return timer(to(opts), async () => {
filepath = massageFilepath(filepath)
await this._loadPromise
if (this._version) throw new ArchiveNotWritableError('Cannot modify a historic version')
await assertUnprotectedFilePath(filepath)
return pda.rmdir(this._archive, filepath, opts)
})
}
createFileActivityStream (pathPattern) {
return toEventTarget(pda.createFileActivityStream(this._archive, pathPattern))
}
createNetworkActivityStream () {
return toEventTarget(pda.createNetworkActivityStream(this._archive))
}
static async resolveName (name) {
return DatArchive._manager.resolveName(name)
}
static async fork (url, opts) {
const srcDat = new DatArchive(url)
const destDat = await DatArchive.create(opts)
await srcDat._loadPromise
await pda.exportArchiveToArchive({
srcArchive: srcDat._archive,
dstArchive: destDat._archive
})
return destDat
}
static async selectArchive (options) {
const url = await DatArchive._manager.selectArchive(options)
const archive = new DatArchive(url)
await archive._loadPromise
return archive
}
static async create ({ title, description, type, author } = {}) {
const archive = new DatArchive(null)
await archive._loadPromise
await pda.writeManifest(archive._archive, { url: archive.url, title, description, type, author })
return archive
}
}
module.exports = DatArchive
// helper to check if filepath refers to a file that userland is not allowed to edit directly
function assertUnprotectedFilePath (filepath) {
if (filepath === '/' + DAT_MANIFEST_FILENAME) {
throw new ProtectedFileNotWritableError()
}
}
async function assertWritePermission (archive) {
// ensure we have the archive's private key
if (!archive.writable) {
throw new ArchiveNotWritableError()
}
return true
}
async function assertValidFilePath (filepath) {
if (filepath.slice(-1) === '/') {
throw new InvalidPathError('Files can not have a trailing slash')
}
await assertValidPath(filepath)
}
async function assertValidPath (fileOrFolderPath) {
if (!DAT_VALID_PATH_REGEX.test(fileOrFolderPath)) {
throw new InvalidPathError('Path contains invalid characters')
}
}
function massageHistoryObj ({ name, version, type }) {
return { path: name, version, type }
}
function massageFilepath (filepath) {
filepath = filepath || ''
filepath = decodeURIComponent(filepath)
if (!filepath.startsWith('/')) {
filepath = '/' + filepath
}
return filepath
}
function waitReady (archive) {
return new Promise((resolve, reject) => {
archive.once('ready', resolve)
archive.once('error', reject)
})
}
function waitOpen (stream) {
return new Promise(function (resolve, reject) {
stream.once('data', onData)
stream.once('error', onError)
function onData () {
stream.removeListener('error', onError)
resolve(stream)
}
function onError (e) {
stream.removeListener('data', onData)
reject(e)
}
})
}
function waitReplication () {
return new Promise((resolve) => {
setTimeout(resolve, REPLICATION_DELAY)
})
}
async function getURLData (url) {
let key = null
let version = null
if (url) {
const parsed = parseURL(url)
const hostnameParts = parsed.hostname.split('+')
key = await DatArchive._manager.resolveName(`dat://${hostnameParts[0]}`)
version = hostnameParts[1] || null
}
return {
key: key,
version: version
}
}