forked from milankragujevic/go-peerflix
/
client.go
186 lines (149 loc) · 4.37 KB
/
client.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
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
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/anacrolix/torrent"
"github.com/dustin/go-humanize"
)
const clearScreen = "\033[H\033[2J"
var isHTTP = regexp.MustCompile(`^https?:\/\/`)
// ClientError formats errors coming from the client.
type ClientError struct {
Type string
Origin error
}
func (clientError ClientError) Error() string {
return fmt.Sprintf("Error %s: %s\n", clientError.Type, clientError.Origin)
}
// Client manages the torrent downloading.
type Client struct {
Client *torrent.Client
Torrent torrent.Torrent
Progress int64
}
// NewClient creates a new torrent client based on a magnet or a torrent file.
// If the torrent file is on http, we try downloading it.
func NewClient(torrentPath string) (client Client, err error) {
var t torrent.Torrent
var c *torrent.Client
// Create client.
c, err = torrent.NewClient(&torrent.Config{
DataDir: os.TempDir(),
NoUpload: !(*seed),
})
if err != nil {
return client, ClientError{Type: "creating torrent client", Origin: err}
}
client.Client = c
// Add torrent.
// Add as magnet url.
if strings.HasPrefix(torrentPath, "magnet:") {
if t, err = c.AddMagnet(torrentPath); err != nil {
return client, ClientError{Type: "adding torrent", Origin: err}
}
} else {
// Otherwise add as a torrent file.
// If it's online, we try downloading the file.
if isHTTP.MatchString(torrentPath) {
if torrentPath, err = downloadFile(torrentPath); err != nil {
return client, ClientError{Type: "downloading torrent file", Origin: err}
}
}
// Check if the file exists.
if _, err = os.Stat(torrentPath); err != nil {
return client, ClientError{Type: "file not found", Origin: err}
}
if t, err = c.AddTorrentFromFile(torrentPath); err != nil {
return client, ClientError{Type: "adding torrent to the client", Origin: err}
}
}
client.Torrent = t
go func() {
<-t.GotInfo()
t.DownloadAll()
}()
return
}
// Render outputs the command line interface for the client.
func (c *Client) Render() {
t := c.Torrent
var currentProgress = c.Torrent.BytesCompleted()
speed := humanize.Bytes(uint64(currentProgress-c.Progress)) + "/s"
c.Progress = currentProgress
percentage := float64(t.BytesCompleted()) / float64(t.Length()) * 100
complete := humanize.Bytes(uint64(t.BytesCompleted()))
size := humanize.Bytes(uint64(t.Length()))
connections := len(t.Conns)
print(clearScreen)
fmt.Println(t.Name())
fmt.Println("=============================================================")
if t.BytesCompleted() > 0 {
fmt.Printf("Progress: \t%s / %s %.2f%%\n", complete, size, percentage)
}
if t.BytesCompleted() < t.Length() {
fmt.Printf("Download speed: %s\n", speed)
}
fmt.Printf("Connections: \t%d\n", connections)
}
func (c Client) getLargestFile() torrent.File {
var target torrent.File
var maxSize int64
for _, file := range c.Torrent.Files() {
if maxSize < file.Length() {
maxSize = file.Length()
target = file
}
}
return target
}
// ReadyForPlayback checks if the torrent is ready for playback or not.
// we wait until 5% of the torrent to start playing.
func (c Client) ReadyForPlayback() bool {
percentage := float64(c.Torrent.BytesCompleted()) / float64(c.Torrent.Length())
return percentage > 0.05
}
// GetFile is an http handler to serve the biggest file managed by the client.
func (c Client) GetFile(w http.ResponseWriter, r *http.Request) {
target := c.getLargestFile()
entry, err := NewFileReader(c, target)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer func() {
if err := entry.Close(); err != nil {
log.Printf("Error closing file reader: %s\n", err)
}
}()
w.Header().Set("Content-Disposition", "attachment; filename=\""+c.Torrent.Name()+"\"")
http.ServeContent(w, r, target.DisplayPath(), time.Now(), entry)
}
func downloadFile(URL string) (fileName string, err error) {
var file *os.File
if file, err = ioutil.TempFile(os.TempDir(), "torrent-imageviewer"); err != nil {
return
}
defer func() {
if err := file.Close(); err != nil {
log.Printf("Error closing torrent file: %s", err)
}
}()
response, err := http.Get(URL)
if err != nil {
return
}
defer func() {
if err := response.Body.Close(); err != nil {
log.Printf("Error closing torrent file: %s", err)
}
}()
_, err = io.Copy(file, response.Body)
return file.Name(), err
}