-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathserver.js
More file actions
82 lines (69 loc) · 2.01 KB
/
server.js
File metadata and controls
82 lines (69 loc) · 2.01 KB
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
const { SimHash } = require('simhash-vocabulary')
const createTestnet = require('hyperdht/testnet')
const path = require('bare-path')
const { randomBytes } = require('bare-crypto')
const MirrorDrive = require('mirror-drive')
const Localdrive = require('localdrive')
const Hyperdrive = require('hyperdrive')
const Corestore = require('corestore')
const Hyperswarm = require('hyperswarm')
const { Transform } = require('streamx')
const vocabulary = require('./vocabulary')
const Hyperbee = require('hyperbee')
async function main() {
const testnet = await createTestnet(10, {
port: 49739
})
for (const n of testnet) {
n._simhash = new SimHash(vocabulary)
}
function pushDHT(file) {
return new Transform({
async transform(chunk, cb) {
const tokens = path.basename(file).replace(/\..+$/, '').split('_').filter(Boolean)
const key = randomBytes(32)
await testnet.nodes[0].searchableRecordPut(['gif', ...tokens], key)
await bee.put(key.toString('hex'), {
path: file,
key: dst.key.toString('hex')
})
this.push(chunk)
cb(null)
}
})
}
const swarm = new Hyperswarm()
const store = new Corestore('./server')
const bee = new Hyperbee(store.get({ name: 'lookup' }), {
keyEncoding: 'utf-8',
valueEncoding: 'json'
})
await bee.ready()
swarm.on('connection', (conn) => {
console.log('connection')
store.replicate(conn)
})
const src = new Localdrive('./images')
const dst = new Hyperdrive(store)
const mirror = new MirrorDrive(src, dst, {
transformers: [
(file) => {
return pushDHT(file)
}
]
})
await mirror.done()
{
const discovery = swarm.join(bee.discoveryKey)
await discovery.flushed()
}
{
const discovery = swarm.join(dst.discoveryKey)
await discovery.flushed()
}
for await (const file of dst.list('.')) {
console.log('list', file) // => { key, value }
}
console.log('Serving DHT on', bee.key.toString('hex'), testnet.nodes[0].port)
}
main()