ProfouzorsLinx/torrent.go

81 lines
1.8 KiB
Go
Raw Permalink Normal View History

package main
import (
"bytes"
"fmt"
"io"
"net/http"
"time"
"github.com/andreimarcu/linx-server/backends"
2019-01-25 08:33:11 +01:00
"github.com/andreimarcu/linx-server/expiry"
"github.com/andreimarcu/linx-server/torrent"
"github.com/zeebo/bencode"
"github.com/zenazn/goji/web"
)
2019-01-25 08:33:11 +01:00
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)
2019-01-25 08:33:11 +01:00
t := torrent.Torrent{
Encoding: "UTF-8",
2019-01-25 08:33:11 +01:00
Info: torrent.TorrentInfo{
PieceLength: torrent.TORRENT_PIECE_LENGTH,
Name: fileName,
},
2019-01-25 08:33:11 +01:00
UrlList: []string{url},
}
for {
2019-01-25 08:33:11 +01:00
n, err := io.ReadFull(f, chunk)
if err == io.EOF {
break
2019-01-25 08:33:11 +01:00
} else if err != nil && err != io.ErrUnexpectedEOF {
return []byte{}, err
}
2019-01-25 08:33:11 +01:00
t.Info.Length += n
t.Info.Pieces += string(torrent.HashPiece(chunk[:n]))
}
2019-01-25 08:33:11 +01:00
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"]
2019-01-25 08:33:11 +01:00
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
2019-01-25 08:33:11 +01:00
} else if err != nil {
oopsHandler(c, w, r, RespAUTO, err.Error())
return
}
2019-01-25 08:33:11 +01:00
defer f.Close()
2019-01-25 08:33:11 +01:00
if expiry.IsTsExpired(metadata.Expiry) {
storageBackend.Delete(fileName)
notFoundHandler(c, w, r)
return
}
encoded, err := createTorrent(fileName, f, r)
if err != nil {
2015-10-04 18:47:20 +02:00
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))
}