-
Notifications
You must be signed in to change notification settings - Fork 188
/
torrent.go
80 lines (67 loc) · 1.79 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
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"time"
"github.com/andreimarcu/linx-server/backends"
"github.com/andreimarcu/linx-server/expiry"
"github.com/andreimarcu/linx-server/torrent"
"github.com/zeebo/bencode"
"github.com/zenazn/goji/web"
)
func createTorrent(fileName string, f io.Reader, r *http.Request) ([]byte, error) {
url := getSiteURL(r) + Config.selifPath + fileName
chunk := make([]byte, torrent.TORRENT_PIECE_LENGTH)
t := torrent.Torrent{
Encoding: "UTF-8",
Info: torrent.TorrentInfo{
PieceLength: torrent.TORRENT_PIECE_LENGTH,
Name: fileName,
},
UrlList: []string{url},
}
for {
n, err := io.ReadFull(f, chunk)
if err == io.EOF {
break
} else if err != nil && err != io.ErrUnexpectedEOF {
return []byte{}, err
}
t.Info.Length += n
t.Info.Pieces += string(torrent.HashPiece(chunk[:n]))
}
data, err := bencode.EncodeBytes(&t)
if err != nil {
return []byte{}, err
}
return data, nil
}
func fileTorrentHandler(c web.C, w http.ResponseWriter, r *http.Request) {
fileName := c.URLParams["name"]
metadata, f, err := storageBackend.Get(fileName)
if err == backends.NotFoundErr {
notFoundHandler(c, w, r)
return
} else if err == backends.BadMetadata {
oopsHandler(c, w, r, RespAUTO, "Corrupt metadata.")
return
} else if err != nil {
oopsHandler(c, w, r, RespAUTO, err.Error())
return
}
defer f.Close()
if expiry.IsTsExpired(metadata.Expiry) {
storageBackend.Delete(fileName)
notFoundHandler(c, w, r)
return
}
encoded, err := createTorrent(fileName, f, r)
if err != nil {
oopsHandler(c, w, r, RespHTML, "Could not create torrent.")
return
}
w.Header().Set(`Content-Disposition`, fmt.Sprintf(`attachment; filename="%s.torrent"`, fileName))
http.ServeContent(w, r, "", time.Now(), bytes.NewReader(encoded))
}