This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
app.js
285 lines (239 loc) · 7.04 KB
/
app.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
'use strict'
/* global self */
const $startButton = document.querySelector('#start')
const $stopButton = document.querySelector('#stop')
const $peers = document.querySelector('#peers')
const $errors = document.querySelector('#errors')
const $filesStatus = document.querySelector('#filesStatus')
const $multihashInput = document.querySelector('#multihash')
const $catButton = document.querySelector('#cat')
const $connectPeer = document.querySelector('input.connect-peer')
const $connectPeerButton = document.querySelector('button.connect-peer')
const $dragoverPopup = document.querySelector('.dragover-popup')
const $wrapper = document.querySelector('.wrapper')
const $header = document.querySelector('.header')
const $body = document.querySelector('body')
const $idContainer = document.querySelector('.id-container')
const $addressesContainer = document.querySelector('.addresses-container')
const $details = document.querySelector('#details')
const $allDisabledButtons = document.querySelectorAll('button:disabled')
const $allDisabledInputs = document.querySelectorAll('input:disabled')
const $filesList = document.querySelector('.file-list')
let node
let peerInfo
/*
* Start and stop the IPFS node
*/
function start () {
if (!node) {
updateView('starting', node)
const repoPath = 'ipfs-' + Math.random()
node = new self.Ipfs({
repo: repoPath,
config: {
Addresses: {
Swarm: [
'/libp2p-webrtc-star/dns4/star-signal.cloud.ipfs.team/wss'
]
}
}
})
node.on('start', () => {
node.id().then((id) => {
peerInfo = id
updateView('ready', node)
setInterval(refreshPeerList, 1000)
$peers.innerHTML = '<h2>peers</h2><i>waiting for peers...</i>'
})
})
}
}
function stop () {
window.location.href = window.location.href // refresh page
}
/*
* Fetch files and display them to the user
*/
function createFileBlob (data, multihash) {
const file = new window.Blob(data, {type: 'application/octet-binary'})
const fileUrl = window.URL.createObjectURL(file)
const listItem = document.createElement('div')
const link = document.createElement('a')
link.setAttribute('href', fileUrl)
link.setAttribute('download', multihash)
const date = (new Date()).toLocaleTimeString()
link.innerText = date + ' - ' + multihash + ' - Size: ' + file.size
listItem.appendChild(link)
return listItem
}
function getFile () {
const multihash = $multihashInput.value
$multihashInput.value = ''
$errors.className = 'hidden'
if (!multihash) {
return console.log('no multihash was inserted')
}
// files.get documentation
// https://github.com/ipfs/interface-ipfs-core/tree/master/API/files#get
node.files.get(multihash, (err, filesStream) => {
if (err) {
return onError(err)
}
filesStream.on('data', (file) => {
if (file.content) {
const buf = []
// buffer up all the data in the file
file.content.on('data', (data) => buf.push(data))
file.content.once('end', () => {
const listItem = createFileBlob(buf, multihash)
$filesList.insertBefore(listItem, $filesList.firstChild)
})
file.content.resume()
}
})
filesStream.resume()
filesStream.on('end', () => console.log('Every file was fetched for', multihash))
})
}
/*
* Drag and drop
*/
function onDrop (event) {
onDragExit()
$errors.className = 'hidden'
event.preventDefault()
const dt = event.dataTransfer
const files = dt.files
function readFileContents (file) {
return new Promise((resolve) => {
const reader = new window.FileReader()
reader.onload = (event) => resolve(event.target.result)
reader.readAsArrayBuffer(file)
})
}
let filesArray = []
for (let i = 0; i < files.length; i++) {
filesArray.push(files[i])
}
filesArray.map((file) => {
readFileContents(file)
.then((buffer) => {
return node.files.add([{
path: file.name,
content: new node.types.Buffer(buffer)
}])
})
.then((files) => {
$multihashInput.value = files[0].hash
$filesStatus.innerHTML = files
.map((e) => `Added ${e.path} as ${e.hash}`)
.join('<br>')
})
.catch(onError)
})
}
/*
* Network related functions
*/
// Get peers from IPFS and display them
function connectToPeer (event) {
event.target.disabled = true
node.swarm.connect($connectPeer.value, (err) => {
if (err) {
return onError(err)
}
$connectPeer.value = ''
setTimeout(() => {
event.target.disabled = false
}, 500)
})
}
function refreshPeerList () {
node.swarm.peers((err, peers) => {
if (err) {
return onError(err)
}
const peersAsHtml = peers
.map((peer) => {
const addr = peer.addr.toString()
if (addr.indexOf('ipfs') >= 0) {
return addr
} else {
return addr + peer.peer.id.toB58String()
}
})
.map((addr) => {
return '<li>' + addr + '</li>'
}).join('')
$peers.innerHTML = peers.length > 0
? '<h2>Remote Peers</h2><ul>' + peersAsHtml + '</ul>'
: '<h2>Remote Peers</h2><i>Waiting for peers...</i>'
})
}
/*
* UI functions
*/
function onError (err) {
let msg = 'An error occured, check the dev console'
if (err.stack !== undefined) {
msg = err.stack
} else if (typeof err === 'string') {
msg = err
}
$errors.innerHTML = '<span class="error">' + msg + '</span>'
$errors.className = 'error visible'
}
window.onerror = onError
function onDragEnter () {
$dragoverPopup.style.display = 'block'
$wrapper.style.filter = 'blur(5px)'
$header.style.filter = 'blur(5px)'
}
function onDragExit () {
$dragoverPopup.style.display = 'none'
$wrapper.style.filter = ''
$header.style.filter = ''
}
/*
* App states
*/
const states = {
ready: () => {
const addressesHtml = peerInfo.addresses.map((address) => {
return '<li><span class="address">' + address + '</span></li>'
}).join('')
$idContainer.innerText = peerInfo.id
$addressesContainer.innerHTML = addressesHtml
$allDisabledButtons.forEach(b => { b.disabled = false })
$allDisabledInputs.forEach(b => { b.disabled = false })
$peers.className = ''
$details.className = ''
$stopButton.disabled = false
$startButton.disabled = true
},
starting: () => {
$startButton.disabled = true
}
}
function updateView (state, ipfs) {
if (states[state] !== undefined) {
states[state]()
} else {
throw new Error('Could not find state "' + state + '"')
}
}
/*
* Boot this application!
*/
const startApplication = () => {
// Setup event listeners
$body.addEventListener('dragenter', onDragEnter)
$body.addEventListener('drop', onDrop)
// TODO should work to hide the dragover-popup but doesn't...
$body.addEventListener('dragleave', onDragExit)
$startButton.addEventListener('click', start)
$stopButton.addEventListener('click', stop)
$catButton.addEventListener('click', getFile)
$connectPeerButton.addEventListener('click', connectToPeer)
}
startApplication()