-
Notifications
You must be signed in to change notification settings - Fork 0
/
Magnet.go
86 lines (73 loc) · 1.64 KB
/
Magnet.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
package helpers
import (
"errors"
"net/http"
"net/url"
"strings"
"time"
"github.com/anacrolix/torrent/metainfo"
)
func GetMagnet(link string) (*metainfo.Magnet, error) {
url, err := url.Parse(link)
if err != nil {
return nil, err
}
var mag *metainfo.Magnet
switch strings.ToLower(url.Scheme) {
case "magnet":
mag, err = getMag(url.String())
case "http", "https":
mag, err = getMagFromHttp(url.String())
case "":
mag, err = getMag("magnet:?xt=urn:btih:" + url.Path)
default:
mag, err = getMagFromFile(url.Path)
}
if err != nil {
return nil, err
}
return mag, nil
}
func getMag(link string) (*metainfo.Magnet, error) {
mag, err := metainfo.ParseMagnetURI(link)
return &mag, err
}
func getMagFromHttp(url string) (*metainfo.Magnet, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
client := new(http.Client)
client.Timeout = time.Duration(time.Second * 30)
req.Header.Set("User-Agent", "DWL/1.1.1 (Torrent)")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, errors.New(resp.Status)
}
minfo, err := metainfo.Load(resp.Body)
if err != nil {
return nil, err
}
info, err := minfo.UnmarshalInfo()
if err != nil {
return nil, err
}
mag := minfo.Magnet(info.Name, minfo.HashInfoBytes())
return &mag, nil
}
func getMagFromFile(path string) (*metainfo.Magnet, error) {
minfo, err := metainfo.LoadFromFile(path)
if err != nil {
return nil, err
}
info, err := minfo.UnmarshalInfo()
if err != nil {
return nil, err
}
mag := minfo.Magnet(info.Name, minfo.HashInfoBytes())
return &mag, nil
}