-
Notifications
You must be signed in to change notification settings - Fork 5
/
drop-dat.js
executable file
·163 lines (143 loc) · 4.43 KB
/
drop-dat.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
import hyperdrive from 'hyperdrive'
import swarm from 'hyperdiscovery'
import ram from 'random-access-memory'
import minimist from 'minimist'
import pump from 'pump'
import hyperdriveHttp from 'hyperdrive-http'
import websocket from 'websocket-stream'
import { readFile, stat, readdir } from 'fs'
import { resolve, join } from 'path'
import { M, E, F } from 'promisey'
import { createServer } from 'http'
const PORT = parseInt(process.env.PORT || '0') || 8040
const HOST = process.env.HOST || 'localhost'
main(minimist(process.argv.slice(2))).catch(err => {
console.error(err.stack)
return process.exit(1)
})
function parseUrl (url) {
let host, port
console.log('PARSE', {url})
if (url === true) {
host = HOST
port = PORT
} else {
let match = url.match(/^(.*):([0-9]*)$/)
if (match) {
host = match[1] || HOST
port = parseInt(match[2] || '0', 10) || PORT
} else {
match = url.match(/^[0-9]+$/)
if (match) {
host = HOST
port = parseInt(match[0], 10)
} else {
host = url || HOST
port = PORT
}
}
}
return { host, port }
}
async function main (argv) {
// Run a server if the `--serve` option is given
if (argv.serve) return serve(argv.serve)
if (!argv._.length) {
console.error('Usage: drop-dat files...')
return process.exit(2)
}
// Create a new in-memory hyperdrive
let archive = hyperdrive(name => ram())
// Wait for it to be ready
await E(archive, 'ready')
console.error('Importing file(s):')
let cwd = process.cwd()
await importList('.', argv._)
async function importList (base, names) {
for (let name of names) {
let path = join(base, name)
let fullPath = resolve(cwd, path)
let meta = await F(stat, fullPath)
if (meta.isDirectory()) {
let children = await F(readdir, fullPath)
await importList(path, children.filter(name => name[0] !== '.'))
}
if (meta.isFile()) {
console.error(` ${path}`)
await M(archive, 'writeFile', path, await F(readFile, fullPath))
}
}
}
if (argv.upload) return upload(archive, argv.upload)
console.error('Sharing on P2P network')
return share(archive)
}
async function share (archive) {
var sw = swarm(archive)
sw.on('connection', (peer, type) => {
console.error('Found swarm peer.')
})
console.error('Sharing on dat P2P network...')
console.error('Press Control+C to stop sharing.\n')
console.log(`dat://${archive.key.toString('hex')}`)
// Keep the event loop alive forever.
process.stdin.resume()
}
async function upload (archive, url) {
if (url === true) url = 'localhost'
if (typeof url === 'number') url = 'localhost:' + url
let { host, port } = parseUrl(url)
let socket = websocket(`ws://${host}:${port}/`)
await E(socket, 'connect')
console.error('Connected to Server, uploading...')
await M(socket, 'write', archive.key)
console.log(`http://${host}:${port}/${archive.key.toString('hex')}/`)
archive.content.on('upload', index => {
console.log('Upload', index)
})
await F(pump, socket, archive.replicate({ upload: true, live: true }), socket)
}
async function serve (url) {
let { host, port } = parseUrl(url)
let sites = {}
let server = createServer((req, res) => {
// See if the request matches
let match = req.url.match(/\/([0-9a-f]{64})\//)
let site = match && sites[match[1]]
if (!site) return res.writeHead(404)
req.url = req.url.replace(match[0], '/')
return site(req, res)
}).listen({host, port})
websocket.createServer({server}, stream => {
handleClient(stream).catch(err => {
console.error(err.stack)
})
})
console.log(`Proxy Server running at http://localhost:${port}/:key/`)
console.log(`Upload interface at ws://localhost:${port}/`)
async function handleClient (socket) {
let key
while (true) {
key = socket.read(32)
if (key) break
await E(socket, 'readable')
}
let hex = key.toString('hex')
let archive = hyperdrive(name => ram(), key, { sparse: true })
await E(archive, 'ready')
console.log(`Added site dat://${hex}`)
sites[hex] = hyperdriveHttp(archive, {
exposeHeaders: true,
live: true,
footer: `Served by Drop-Dat`
})
try {
await F(pump, socket, archive.replicate(), socket)
} catch (err) {
if (!err.message.match(/premature close/)) throw err
} finally {
console.log('Removed site', hex)
delete sites[hex]
}
}
}