-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsend.js
130 lines (109 loc) · 2.56 KB
/
send.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
const { Origin } = require('./origin')
const duplexify = require('duplexify')
const { Box } = require('./box')
const codecs = require('./codecs')
const assert = require('assert')
const path = require('path')
const pump = require('pump')
const zlib = require('zlib')
const tar = require('tar-stream')
// exported symbols attached to the `Send` class
const kSendPack = Symbol('Send.pack')
const kSendStream = Symbol('Send.stream')
/**
* The `SendOrigin` class TBD
* @class SendOrigin
* @extends Origin
*/
class SendOrigin extends Origin {
/**
*/
[Box.init](opts) {
super[Box.init](opts)
this[kSendStream] = null
this[kSendPack] = null
}
/**
*/
[Box.codec](opts) {
const { encryptionKey, nonce } = opts
if (encryptionKey && nonce) {
assert(Buffer.isBuffer(nonce))
assert(Buffer.isBuffer(encryptionKey))
return codecs.xsalsa20poly1305({ nonce, key: encryptionKey })
}
}
}
/**
* The `Send` class TBD
* @class Send
* @extends SendOrigin
*/
class Send extends SendOrigin {
/**
*/
packFile(name, buffer, opts, callback) {
buffer = Buffer.from(buffer)
if ('function' === typeof opts) {
callback = opts
opts = {}
}
if (!opts) {
opts = {}
}
if (!opts.size) {
opts.size = buffer.length
}
const stream = this.createPackStream(name, opts)
if ('function' === typeof callback) {
stream.once('close', callback)
stream.once('error', callback)
}
stream.write(buffer)
stream.end()
}
/**
*/
createPackStream(name, opts) {
assert(opts && 'object' === typeof opts)
assert(opts.size > 0 && 'number' === typeof opts.size)
name = path.resolve('/', name)
opts = Object.assign({ name }, opts)
const proxy = duplexify()
this.lock((release) => {
this.ready(() => {
this.guard.wait()
const pack = this[kSendPack] || tar.pack()
const stream = this[kSendStream] || this.createWriteStream()
const source = pack.entry(opts, () => {
this.guard.continue()
})
if (!this[kSendStream] || !this[kSendPack]) {
pump(pack, stream, this.onerror)
this[kSendStream] = stream
this[kSendPack] = pack
}
proxy.setReadable(false)
proxy.setWritable(source)
proxy.on('finish', release)
})
})
return proxy
}
}
/**
*/
Send.pack = kSendPack
/**
*/
Send.stream = kSendStream
/**
*/
function createSend(storage, key, opts) {
return new Send(storage, key, opts)
}
/**
*/
module.exports = Object.assign(createSend, {
Send
})