-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathipfs.js
109 lines (99 loc) · 2.69 KB
/
ipfs.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
const DaemonFactory = require('ipfsd-ctl')
const ipfsApi = require('ipfs-api')
const fs = require('fs')
const multiaddr = require('multiaddr')
const generator = require('./generator')
const config = require('./config')
class DSPIpfs {
constructor ({ ipfs, apiAddr }) {
this.initialize = ipfs
this.apiAddr = apiAddr
this.node = undefined
this.api = undefined
}
start () {
if (this.initialize === true) {
console.log('Initializing IPFS...')
return this._startIpfsDaemon()
} else {
this.api = ipfsApi(this.apiAddr || config.IPFS.apiAddr)
return Promise.resolve()
}
}
stop () {
if (this.initialize === true) {
return this._stopIpfsDaemon()
} else {
Promise.resolve()
}
}
id () {
return this.api.id()
}
async getGatewayAddress () {
const addr = multiaddr(await this.api.config.get('Addresses.Gateway'))
const gtwAddr = addr.nodeAddress()
return `//${gtwAddr.address}:${gtwAddr.port}`
}
getConnectedPeers () {
return this.api.swarm.peers()
}
async publish (incidents, settings) {
const homeFile = {
path: `/${config.IPFS.namespace}/index.html`,
content: generator.buildHomePage(incidents, settings)
}
const incidentFiles = [ ...incidents.open || [], ...incidents.history || [] ].map(i => {
return {
path: `/${config.IPFS.namespace}/incidents/${i.id}.html`,
content: generator.buildIncidentPage(i, settings)
}
})
try {
const files = await this.api.files.add([ homeFile, ...incidentFiles ])
const { hash } = files.filter(f => f.path === config.IPFS.namespace)[0]
await this.api.name.publish(`/ipfs/${hash}`)
return hash
} catch (err) {
throw new Error('Unable to publish: ', err)
}
}
_startIpfsDaemon () {
return new Promise((resolve, reject) => {
const df = DaemonFactory.create({ type: 'go' })
const options = {
disposable: false,
config: {
Bootstrap: config.IPFS.bootstrap
}
}
const startNode = () => {
this.node.start((err, ipfsapi) => {
if (err) reject(err)
this.api = ipfsapi
console.log('IPFS ready.')
resolve()
})
}
df.spawn(options, (err, ipfsd) => {
if (err) reject(err)
this.node = ipfsd
if (fs.existsSync(this.node.repoPath)) {
startNode()
} else {
this.node.init((err, ipfsd) => {
if (err) reject(err)
this.node = ipfsd
startNode()
})
}
})
})
}
_stopIpfsDaemon () {
return new Promise(resolve => {
this.node.stop(resolve)
})
}
}
module.exports = DSPIpfs