/
torrent.go
98 lines (87 loc) · 1.88 KB
/
torrent.go
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
package engine
import (
"time"
"github.com/anacrolix/torrent"
)
type Torrent struct {
//anacrolix/torrent
InfoHash string
Name string
Loaded bool
Downloaded int64
Size int64
Files []*File
//cloud torrent
Started bool
Dropped bool
Percent float32
DownloadRate float32
t *torrent.Torrent
updatedAt time.Time
}
type File struct {
//anacrolix/torrent
Path string
Size int64
Chunks int
Completed int
//cloud torrent
Started bool
Percent float32
f torrent.File
}
func (torrent *Torrent) Update(t *torrent.Torrent) {
torrent.Name = t.Name()
torrent.Loaded = t.Info() != nil
torrent.Size = t.Length()
totalChunks := 0
totalCompleted := 0
tfiles := t.Files()
if len(tfiles) > 0 && torrent.Files == nil {
torrent.Files = make([]*File, len(tfiles))
}
//merge in files
for i, f := range tfiles {
path := f.Path()
file := torrent.Files[i]
if file == nil {
file = &File{Path: path}
torrent.Files[i] = file
}
chunks := f.State()
file.Size = f.Length()
file.Chunks = len(chunks)
completed := 0
for _, p := range chunks {
if p.Complete {
completed++
}
}
file.Completed = completed
file.Percent = percent(int64(file.Completed), int64(file.Chunks))
file.f = f
totalChunks += file.Chunks
totalCompleted += file.Completed
}
//cacluate rate
now := time.Now()
bytes := t.BytesCompleted()
torrent.Percent = percent(bytes, torrent.Size)
if !torrent.updatedAt.IsZero() {
dt := float32(now.Sub(torrent.updatedAt))
db := float32(bytes - torrent.Downloaded)
rate := db * (float32(time.Second) / dt)
if rate >= 0 {
torrent.DownloadRate = rate
}
}
torrent.Downloaded = bytes
torrent.updatedAt = now
torrent.t = t
}
func percent(n, total int64) float32 {
if total == 0 {
return float32(0)
}
return float32(int(float64(10000)*(float64(n)/float64(total)))) / 100
}