forked from glblduh/torrenttp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathendpoints.go
359 lines (306 loc) · 9.39 KB
/
endpoints.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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package main
import (
"net/http"
"net/url"
"time"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
"github.com/dustin/go-humanize"
"github.com/gorilla/mux"
)
// Endpoint handler for torrent adding to client
func apiAddTorrent(w http.ResponseWriter, r *http.Request) {
var t *torrent.Torrent
var spec *torrent.TorrentSpec = nil
/* Decodes the request body */
body := apiAddTorrentBody{}
if decodeBody(w, r.Body, &body) != nil {
return
}
/* Parses the inputs */
// If magnet link is present
if body.Magnet != "" {
var err error
spec, err = torrent.TorrentSpecFromMagnetUri(body.Magnet)
if err != nil {
errorRes(w, "Magnet decoding error: "+err.Error(), http.StatusInternalServerError)
return
}
}
// If manual metainfo is present
if body.Magnet == "" && body.InfoHash != "" && body.DisplayName != "" {
spec = makeTorrentSpec(body.InfoHash, body.DisplayName, body.Trackers)
}
if spec == nil {
errorRes(w, "No torrent provided", http.StatusNotFound)
return
}
var terr error
t, terr = btEngine.addTorrent(spec, false)
if terr != nil {
errorRes(w, "Torrent add error: "+terr.Error(), http.StatusInternalServerError)
return
}
/* Creates the response body*/
res := createAddTorrentRes(t)
encodeRes(w, &res)
return
}
// Endpoint for selecting which file/s to download
func apiTorrentSelectFile(w http.ResponseWriter, r *http.Request) {
res := apiTorrentSelectFileRes{}
/* Parse the request body to apiTorrentSelectFileBody */
body := apiTorrentSelectFileBody{}
if decodeBody(w, r.Body, &body) != nil {
return
}
/* Check if no provided files */
if !body.AllFiles && len(body.Files) < 1 {
errorRes(w, "No files provided", http.StatusNotFound)
return
}
/* Gets torrent handler from client */
t, err := btEngine.getTorrHandle(body.InfoHash)
if err != nil {
errorRes(w, err.Error(), http.StatusInternalServerError)
return
}
/* Create the response body */
res.InfoHash = t.InfoHash().String()
res.Name = t.Name()
/* Initiate download for selected files */
// If AllFiles is toggled
if body.AllFiles {
// Empties the Files slice to prevent the execution of the code below when AllFiles if toggled
body.Files = nil
// Starts download for all files in the torrent
t.DownloadAll()
/* Go through the selected files to append its info to the response */
for _, f := range t.Files() {
saveSpecFile(t.InfoHash().String(), f.DisplayPath())
res.Files = append(res.Files, apiTorrentSelectFileResFiles{
FileName: f.DisplayPath(),
Stream: createFileLink(t.InfoHash().String(), f.DisplayPath(), false),
Download: createFileLink(t.InfoHash().String(), f.DisplayPath(), true),
})
}
}
// If specific files are selected
for _, f := range body.Files {
/* Get the handle of the torrent file from its DisplayPath */
tf, tferr := getTorrentFile(t, f)
if tferr != nil {
continue
}
// Starts download of said torrent file
tf.Download()
// Save the filename to the DB for persistence
saveSpecFile(t.InfoHash().String(), tf.DisplayPath())
/* Go through the selected files to append its info to the response */
res.Files = append(res.Files, apiTorrentSelectFileResFiles{
FileName: tf.DisplayPath(),
Stream: createFileLink(t.InfoHash().String(), tf.DisplayPath(), false),
Download: createFileLink(t.InfoHash().String(), tf.DisplayPath(), true),
})
}
encodeRes(w, &res)
return
}
// Endpoint for streaming a file
func apiStreamTorrentFile(w http.ResponseWriter, r *http.Request) {
// Get infohash and filename variables
vars := mux.Vars(r)
/* Get torrent handle from infohash */
t, err := btEngine.getTorrHandle(vars["infohash"])
if err != nil {
errorRes(w, err.Error(), http.StatusNotFound)
return
}
/* Unescape given filename */
fn, fnerr := url.QueryUnescape(vars["file"])
if fnerr != nil {
errorRes(w, "Filename unescaping error: "+fnerr.Error(), http.StatusInternalServerError)
return
}
/* Get torrent file handle from filename */
f, ferr := getTorrentFile(t, fn)
if ferr != nil {
errorRes(w, ferr.Error(), http.StatusNotFound)
return
}
/* Make torrent file reader for streaming */
reader := f.NewReader()
defer reader.Close()
// Set the buffer to 1% of the file size
reader.SetReadahead(f.Length() / 100)
// Send the reader as HTTP response
http.ServeContent(w, r, f.DisplayPath(), time.Now(), reader)
return
}
// Endpoint for removing a torrent
func apiRemoveTorrent(w http.ResponseWriter, r *http.Request) {
/* Parses the request body to apiRemoveTorrent */
body := apiRemoveTorrentBody{}
if decodeBody(w, r.Body, &body) != nil {
return
}
/* Getting the torrent handle */
t, terr := btEngine.getTorrHandle(body.InfoHash)
if terr != nil {
errorRes(w, terr.Error(), http.StatusNotFound)
return
}
/* Saving of variables for response body */
tname := t.Name()
ih := t.InfoHash().String()
/* Remover function */
rmerr := btEngine.dropTorrent(ih, body.RemoveFiles)
if rmerr != nil {
errorRes(w, "Torrent removal error: "+rmerr.Error(), http.StatusInternalServerError)
return
}
/* Creating response body */
res := apiRemoveTorrentRes{
Name: tname,
InfoHash: ih,
}
encodeRes(w, &res)
return
}
// Torrent stats endpoint
func apiTorrentStats(w http.ResponseWriter, r *http.Request) {
/* Get infohash variable from the request */
vars := mux.Vars(r)
res := apiTorrentStasRes{}
/* Variables */
tlist := btEngine.Torrents
ih := vars["infohash"]
/* If provided with infohash */
if ih != "" {
/* Check if infohash is valid */
_, terr := btEngine.getTorrHandle(ih)
if terr != nil {
errorRes(w, terr.Error(), http.StatusNotFound)
return
}
/* Overwrite tlist with only the selected torrent's handle */
templist := make(map[string]*torrentHandle)
templist[ih] = btEngine.Torrents[ih]
tlist = templist
}
/* Go through the tlist */
for _, v := range tlist {
tstats := apiTorrentStasResTorrents{}
/* Setting main stats */
tstats.Name = v.Torrent.Name()
tstats.InfoHash = v.Torrent.InfoHash().String()
tstats.TotalPeers = v.Torrent.Stats().TotalPeers
tstats.ActivePeers = v.Torrent.Stats().ActivePeers
tstats.PendingPeers = v.Torrent.Stats().PendingPeers
tstats.HalfOpenPeers = v.Torrent.Stats().HalfOpenPeers
tstats.DownloadSpeed = v.DlSpeedReadable
tstats.UploadSpeed = v.UlSpeedReadable
tstats.Progress = calcTorrentProgress(v.Torrent)
/* Setting the peers info */
for _, peer := range v.Torrent.PeerConns() {
paddr := peer.Peer.RemoteAddr.String()
pcli, ok := peer.Peer.PeerClientName.Load().(string)
if !ok {
pcli = "NOTPROVIDED"
}
tstats.Peers = append(tstats.Peers, apiTorrentStatsPeersInfo{
PeerAddr: paddr,
PeerClient: pcli,
})
}
/* Setting the files available in the torrent */
for _, tf := range v.Torrent.Files() {
tfname := tf.DisplayPath()
tfbc := tf.BytesCompleted()
tflen := tf.Length()
curf := apiTorrentStatsTorrentsFiles{
FileName: tfname,
FileSizeBytes: int(tflen),
FileSizeReadable: humanize.Bytes(uint64(tflen)),
DownloadedBytes: int(tfbc),
DownloadedReadable: humanize.Bytes(uint64(tfbc)),
}
if tf.BytesCompleted() > 0 {
curf.Stream = createFileLink(tstats.InfoHash, tfname, false)
curf.Download = createFileLink(tstats.InfoHash, tfname, true)
}
tstats.Files = append(tstats.Files, curf)
}
/* Append it response body */
res.Torrents = append(res.Torrents, tstats)
}
/* Send response */
encodeRes(w, &res)
return
}
func apiDownloadFile(w http.ResponseWriter, r *http.Request) {
/* Get infohash and filename vars*/
vars := mux.Vars(r)
/* Get torrent handle from infohash */
t, err := btEngine.getTorrHandle(vars["infohash"])
if err != nil {
errorRes(w, err.Error(), http.StatusNotFound)
return
}
/* Unescape given filename */
fn, fnerr := url.QueryUnescape(vars["file"])
if fnerr != nil {
errorRes(w, "Filename unescaping error: "+fnerr.Error(), http.StatusInternalServerError)
return
}
/* Get torrent file handle from filename */
f, ferr := getTorrentFile(t, fn)
if ferr != nil {
errorRes(w, ferr.Error(), http.StatusNotFound)
return
}
/* Check if file is finished downloading */
if f.BytesCompleted() != f.Length() {
errorRes(w, "File is not completed", http.StatusAccepted)
return
}
/* Set Content-Disposition as f.DisplayPath() */
w.Header().Add("Content-Disposition", "attachment; filename=\""+safenDisplayPath(f.DisplayPath())+"\"")
/* Send file as response */
reader := f.NewReader()
defer reader.Close()
http.ServeContent(w, r, f.DisplayPath(), time.Now(), reader)
return
}
func apiAddTorrentFile(w http.ResponseWriter, r *http.Request) {
/* Gets file from form */
torrfile, _, err := r.FormFile("torrent")
if err != nil {
errorRes(w, err.Error(), http.StatusInternalServerError)
return
}
defer torrfile.Close()
/* Loads torrent file to the BitTorrent client */
/* Loads the torrent file as a MetaInfo */
mi, mierr := metainfo.Load(torrfile)
if mierr != nil {
errorRes(w, mierr.Error(), http.StatusInternalServerError)
return
}
/* Makes torrent spec from given MetaInfo */
spec, specerr := torrent.TorrentSpecFromMetaInfoErr(mi)
if specerr != nil {
errorRes(w, specerr.Error(), http.StatusInternalServerError)
return
}
/* Adds torrent spec to the BitTorrent client */
t, terr := btEngine.addTorrent(spec, false)
if terr != nil {
errorRes(w, terr.Error(), http.StatusInternalServerError)
return
}
/* Create response */
res := createAddTorrentRes(t)
encodeRes(w, &res)
return
}