-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcmd.js
executable file
·177 lines (164 loc) · 5.51 KB
/
cmd.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
#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var env = process.env
var minimist = require('minimist')
var pump = require('pump')
var argv = minimist(process.argv.slice(2), {
alias: {
v: 'version', h: 'help',
d: 'datadir', f: 'format', p: 'port', q: 'quiet'
},
boolean: ['quiet','help','version'],
})
if (argv.help || argv._[0] === 'help') {
usage()
} else if (argv.version || argv._[0] === 'version') {
console.log(require('./package.json').version)
} else if (argv._[0] === 'datadir') {
console.log(getDataDir())
} else if (argv._[0] === 'query') {
var u = argv._[1]
var datadir = getDataDir()
var bbox = argv.bbox.split(',').map(Number)
var m, storage
if (m = /^hyper:[\/]*([^\/]+)/.exec(u)) {
var file = path.join(datadir, m[1].replace(/[^A-Za-z0-9]+/g,'-'))
var storage = require('./lib/hyperdrive')(file, u)
} else {
return console.error('URI not yet supported')
}
var eyros = require('eyros/2d')
var wasmSource = fs.readFileSync(require.resolve('eyros/2d.wasm'))
var format = argv.format || 'base64'
var lp = null
if (format === 'lp') {
lp = require('length-prefixed-stream').encode()
lp.pipe(process.stdout)
}
process.stdout.once('error', function () {
storage.close()
})
eyros({ storage, wasmSource }).then(async function (db) {
var q = await db.query(bbox)
var row
var i = 0
while (row = await q.next()) {
if (format === 'lp') {
lp.write(row[1])
} else if (format === 'base64') {
var b64 = Buffer.from(row[1]).toString('base64')
process.stdout.write(b64+'\n')
}
i++
}
if (lp) lp.end()
if (typeof storage.close === 'function') storage.close()
})
} else if (argv._[0] === 'http') {
var http = require('http')
var Hyperdrive = require('hyperdrive')
var hyperswarm = require('hyperswarm')
var mime = require('mime')
var u = argv._[1]
var datadir = getDataDir()
var m = /^hyper:[\/]*([^\/]+)/.exec(u)
if (!m) return console.error('URI not yet supported')
var file = path.join(datadir, m[1].replace(/[^A-Za-z0-9]+/g,'-'))
var key = u.replace(/^hyper:[\/]*/,'')
var swarm = hyperswarm()
var drive = new Hyperdrive(file, key)
var isOpen = false
var openQueue = []
function open() {
isOpen = true
for (var i = 0; i < openQueue.length; i++) {
openQueue[i]()
}
openQueue = null
}
drive.once('ready', function () {
swarm.join(drive.discoveryKey)
})
swarm.on('connection', function (socket, info) {
var peer = `${info.peer.host}:${info.peer.port}`
if (!argv.quiet) console.log(`connected to ${peer}`)
pump(socket, drive.replicate(info.client), socket, function (err) {
if (err) console.error(`pump error on ${peer}`, err)
else if (!argv.quiet) console.log(`pump finished on ${peer}`)
})
if (!isOpen) open()
})
function error (res, err, code) {
res.statusCode = code
res.setHeader('content-type', 'text/plain')
res.end('error: ' + err)
}
var server = http.createServer(function handler(req, res) {
if (!argv.quiet) console.log(req.method, req.url)
if (!isOpen) return openQueue.push(function () { handler(req, res) })
// todo: etag, if-modified-since, and head requests
if (req.method === 'GET') {
var ct = mime.getType(path.extname(req.url)) || 'application/octet-stream'
res.setHeader('content-type', ct)
res.setHeader('access-control-allow-origin', '*')
res.setHeader('access-control-allow-methods', 'GET')
res.setHeader('access-control-allow-headers', [
'content-type', 'range', 'user-agent', 'x-requested-with'
])
res.setHeader('access-control-expose-headers', [
'content-range', 'x-chunked-output', 'x-stream-output'
])
drive.open(req.url, 'r', function (err, fd) {
if (err) {
error(res, err, err.code === 'ENOENT' ? 404 : 500)
return
}
drive.stat(req.url, { wait: true }, function (err, stat) {
if (err) {
error(res, err, 500)
return
}
var buf = Buffer.alloc(stat.size)
drive.read(fd, buf, 0, stat.size, 0, function (err) {
if (err) {
error(res, err, 500)
} else {
res.end(buf)
}
})
})
})
} else {
error(res, 'method not allowed', 405)
}
})
var port = argv.port || 8081
server.listen(port, function () {
if (!argv.quiet) console.log('listening on port ' + port)
})
} else {
usage()
}
function getDataDir() {
if (argv.datadir !== undefined) return argv.datadir
if (env.PEERMAPS_DATADIR) return env.PEERMAPS_DATADIR
var home = env.XDG_DATA_HOME || env.HOME
return path.join(home, '.local/share/peermaps')
}
function usage() {
console.log(`
usage: ${path.basename(process.argv[1])} COMMAND ...
query URI - list all features that intersect BBOX
URI is a hyper://, ipfs://, or https?:// link to the peermaps dataset
BBOX is in west,south,east,north form.
-f FORMAT - display results in FORMAT: base64 (default), lp
--bbox=BBOX - list all features that intersect BBOX
The rows of output are in georender format:
https://github.com/peermaps/docs/blob/master/georender.md
http URI - serve peermaps content from URI
URI is a hyper://, ipfs://, or https?:// link to the peermaps dataset
-p --port - serve http on this port. default: 8081
-q --quiet - do not log http requests to stdout
`.trim().replace(/^ {4}/gm,'') + '\n')
}