-
Notifications
You must be signed in to change notification settings - Fork 1
/
js.js
91 lines (72 loc) · 2.98 KB
/
js.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
// var util = require('./util')
// HTML elements
// var panodata = JSON.parse(db);
var $body = document.body
var $progressBar = document.querySelector('#progressBar')
var $numPeers = document.querySelector('#numPeers')
var $downloaded = document.querySelector('#downloaded')
var $total = document.querySelector('#total')
var $remaining = document.querySelector('#remaining')
var $uploadSpeed = document.querySelector('#uploadSpeed')
var $downloadSpeed = document.querySelector('#downloadSpeed')
var client = new WebTorrent()
// window.client = client // for easier debugging
// client.on('warning', util.warning)
// client.on('error', util.error)
// Download the torrent
client.add(torrentId, function (torrent) {
torrent.addWebSeed(webSeedUrl)
// Trigger statistics refresh
torrent.on('done', onDone)
setInterval(onProgress, 500)
onProgress()
file.getBlobURL(function (err, url) {
if (err) throw err
var a = document.createElement('a')
a.download = file.name
a.href = url
a.textContent = 'Download ' + file.name
document.body.appendChild(a)
})
// Statistics
function onProgress () {
// Peers
$numPeers.innerHTML = torrent.numPeers + (torrent.numPeers === 1 ? ' peer' : ' peers')
// Progress
var percent = Math.round(torrent.progress * 100 * 100) / 100
$progressBar.style.width = percent + '%'
$downloaded.innerHTML = prettyBytes(torrent.downloaded)
$total.innerHTML = prettyBytes(torrent.length)
// Remaining time
var remaining
if (torrent.done) {
remaining = 'Done.'
} else {
remaining = moment.duration(torrent.timeRemaining / 1000, 'seconds').humanize()
remaining = remaining[0].toUpperCase() + remaining.substring(1) + ' remaining.'
}
$remaining.innerHTML = remaining
// Speed rates
$downloadSpeed.innerHTML = prettyBytes(torrent.downloadSpeed) + '/s'
$uploadSpeed.innerHTML = prettyBytes(torrent.uploadSpeed) + '/s'
}
function onDone () {
$body.className += ' is-seed'
onProgress()
}
})
// Human readable bytes util
function prettyBytes(num) {
var exponent, unit, neg = num < 0, units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
if (neg) num = -num
if (num < 1) return (neg ? '-' : '') + num + ' B'
exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1)
num = Number((num / Math.pow(1000, exponent)).toFixed(2))
unit = units[exponent]
return (neg ? '-' : '') + num + ' ' + unit
}
function log (str) {
var p = document.createElement('p')
p.innerHTML = str
document.querySelector('.log').appendChild(p)
}