2014-06-26 14:57:07 +00:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base32"
|
|
|
|
"encoding/hex"
|
|
|
|
"fmt"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Magnet struct {
|
|
|
|
InfoHash [20]byte
|
|
|
|
Trackers []string
|
|
|
|
DisplayName string
|
|
|
|
}
|
|
|
|
|
|
|
|
const xtPrefix = "urn:btih:"
|
|
|
|
|
2015-02-25 03:50:01 +00:00
|
|
|
func (m *Magnet) String() (ret string) {
|
|
|
|
// net.URL likes to assume //, and encodes ':' on us, so we do most of
|
|
|
|
// this manually.
|
|
|
|
ret = "magnet:?xt="
|
|
|
|
ret += xtPrefix + hex.EncodeToString(m.InfoHash[:])
|
|
|
|
if m.DisplayName != "" {
|
|
|
|
ret += "&dn=" + url.QueryEscape(m.DisplayName)
|
|
|
|
}
|
|
|
|
for _, tr := range m.Trackers {
|
|
|
|
ret += "&tr=" + url.QueryEscape(tr)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-03-22 17:50:16 +00:00
|
|
|
// ParseMagnetURI parses Magnet-formatted URIs into a Magnet instance
|
2014-06-26 14:57:07 +00:00
|
|
|
func ParseMagnetURI(uri string) (m Magnet, err error) {
|
|
|
|
u, err := url.Parse(uri)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("error parsing uri: %s", err)
|
|
|
|
return
|
|
|
|
}
|
2014-09-11 04:19:23 +00:00
|
|
|
if u.Scheme != "magnet" {
|
|
|
|
err = fmt.Errorf("unexpected scheme: %q", u.Scheme)
|
|
|
|
return
|
|
|
|
}
|
2014-06-26 14:57:07 +00:00
|
|
|
xt := u.Query().Get("xt")
|
|
|
|
if !strings.HasPrefix(xt, xtPrefix) {
|
|
|
|
err = fmt.Errorf("bad xt parameter")
|
|
|
|
return
|
|
|
|
}
|
2015-03-22 17:50:16 +00:00
|
|
|
infoHash := xt[len(xtPrefix):]
|
|
|
|
|
|
|
|
// BTIH hash can be in HEX or BASE32 encoding
|
|
|
|
// will assign apropriate func judging from symbol length
|
|
|
|
var decode func(dst, src []byte) (int, error)
|
|
|
|
switch len(infoHash) {
|
|
|
|
case 40:
|
|
|
|
decode = hex.Decode
|
|
|
|
case 32:
|
|
|
|
decode = base32.StdEncoding.Decode
|
|
|
|
}
|
|
|
|
|
2014-06-26 14:57:07 +00:00
|
|
|
if decode == nil {
|
2015-03-22 17:50:16 +00:00
|
|
|
err = fmt.Errorf("unhandled xt parameter encoding: encoded length %d", len(infoHash))
|
2014-06-26 14:57:07 +00:00
|
|
|
return
|
|
|
|
}
|
2015-03-22 17:50:16 +00:00
|
|
|
n, err := decode(m.InfoHash[:], []byte(infoHash))
|
2014-06-26 14:57:07 +00:00
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("error decoding xt: %s", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if n != 20 {
|
|
|
|
panic(n)
|
|
|
|
}
|
|
|
|
m.DisplayName = u.Query().Get("dn")
|
|
|
|
m.Trackers = u.Query()["tr"]
|
|
|
|
return
|
|
|
|
}
|