/
torrent.go
73 lines (60 loc) · 1.43 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
package main
import (
"fmt"
"io"
"regexp"
"strings"
"time"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
)
func checkFileComplete(file *torrent.File) bool {
return file.BytesCompleted() == file.Length()
}
func downloadTorrent(body io.Reader) (torrentDir *string, err error) {
startTime := time.Now()
// Load the .torrent file
torrentMeta, err := metainfo.Load(body)
if err != nil {
return nil, err
}
// Create a new Torrent client
client, err := torrent.NewClient(nil)
if err != nil {
return nil, err
}
// Add the torrent to the client
torrent, err := client.AddTorrent(torrentMeta)
if err != nil {
return nil, err
}
// Get information about the files in the torrent
files := torrent.Files()
fpath := strings.Split(files[0].Path(), "/")[0]
regex := regexp.MustCompile(fmt.Sprintf("(?i)%s/(ui/)?[^(fs)][a-z]+.vromfs.bin", fpath))
fmt.Println(regex)
// Download specific files
for _, file := range files {
if regex.MatchString(file.Path()) {
file.Download()
}
}
// Wait for specific files to finish downloading
for {
allComplete := true
for _, file := range files {
if regex.MatchString(file.Path()) && !checkFileComplete(file) {
allComplete = false
break
}
}
if allComplete {
break
}
time.Sleep(time.Second)
}
// Close the client
client.Close()
fmt.Printf("Download complete! %fs elapsed\n", time.Since(startTime).Seconds())
return &fpath, err
}