This repository has been archived by the owner on Aug 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdatabase.js
70 lines (56 loc) · 1.73 KB
/
database.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
/*
database.js
Hyperdb storage and authorization logic. If a pool key was supplied, then
initiate our hyperdb using that key. If not, then initiate using our local
key. When a peer connects, check if the peer is authorized and if not then
authorize them so any changed will propogate.
*/
const hyperdb = require('hyperdb')
const hyperdiscovery = require('hyperdiscovery')
const path = require('path')
const args = require('minimist')(process.argv.slice(2))
const logger = require('./helpers/logger')
const homeDir = require('os').homedir()
let appDir = args.d ? args.d : path.resolve(homeDir, '.datkeyserver')
if (process.env.NODE_ENV === 'test') {
appDir = 'testdb'
}
let db, swarm
if (args.k) {
db = hyperdb(path.resolve(appDir, 'keys.db'), args.k, {
valueEncoding: 'json'
})
} else {
db = hyperdb(path.resolve(appDir, 'keys.db'), { valueEncoding: 'json' })
}
db.on('ready', () => {
swarm = hyperdiscovery(db)
logger.info(`database ${db.key.toString('hex')} ready`)
if (!args.k) {
logger.info(`your pool key is ${db.key.toString('hex')}`)
}
db.put('/t', { t: new Date().getTime() })
swarm.on('connection', (peer, type) => {
logger.info(
`a peer at ${type.host} connected. ${swarm.connections.length} total`
)
db.authorized(peer.remoteUserData, (err, auth) => {
if (err) {
logger.error(`${err}`)
} else {
if (!auth) {
db.authorize(peer.remoteUserData, err => {
if (!err) {
logger.info(`peer at ${type.host} was authorised`)
}
})
}
}
})
peer.on('close', () => {
logger.info(`a peer at ${type.host} disconnected`)
})
})
})
const getSwarm = () => swarm
module.exports = { db, getSwarm }