This repository has been archived by the owner on Jan 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
96 lines (79 loc) · 2.33 KB
/
index.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
var assert = require('assert')
var speedometer = require('speedometer')
var debug = require('debug')('dat-network')
module.exports = function (archive, opts) {
assert.ok(archive, 'archive required')
opts = opts || {}
var speed = {}
var downloadSpeed = speedometer()
var uploadSpeed = speedometer()
var timeout = opts.timeout || 1000
var upTimeout = null
var downTimeout = null
var totalTransfer = {
up: 0,
down: 0
}
if (debug.enabled) {
setInterval(function () {
if (totalTransfer.up) debug('Uploaded data:', totalTransfer.up)
if (totalTransfer.down) debug('Downloaded data:', totalTransfer.down)
}, 500)
}
archive.metadata.on('download', function (block, data) {
totalTransfer.down += data.length
ondownload(data.length)
})
archive.metadata.on('upload', function (block, data) {
totalTransfer.up += data.length
onupload(data.length)
})
if (archive.content) trackContent()
else archive.on('content', trackContent)
Object.defineProperty(speed, 'downloadSpeed', {
enumerable: true,
get: function () { return downloadSpeed() }
})
Object.defineProperty(speed, 'uploadSpeed', {
enumerable: true,
get: function () { return uploadSpeed() }
})
Object.defineProperty(speed, 'downloadTotal', {
enumerable: true,
get: function () { return totalTransfer.down }
})
Object.defineProperty(speed, 'uploadTotal', {
enumerable: true,
get: function () { return totalTransfer.up }
})
return speed
function trackContent () {
archive.content.on('download', function (block, data) {
totalTransfer.down += data.length
ondownload(data.length)
})
archive.content.on('upload', function (block, data) {
totalTransfer.up += data.length
onupload(data.length)
})
}
// Zero out for uploads & disconnections
function downZero () {
downloadSpeed = speedometer()
if (downTimeout) clearTimeout(downTimeout)
}
function upZero () {
uploadSpeed = speedometer()
if (upTimeout) clearTimeout(upTimeout)
}
function ondownload (bytes) {
downloadSpeed(bytes)
if (downTimeout) clearTimeout(downTimeout)
downTimeout = setTimeout(downZero, timeout)
}
function onupload (bytes) {
uploadSpeed(bytes)
if (upTimeout) clearTimeout(upTimeout)
upTimeout = setTimeout(upZero, timeout)
}
}