-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtorrent.go
106 lines (96 loc) · 2.81 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package tpb
import (
"encoding/json"
"fmt"
"strconv"
"time"
)
// Torrent represents a Torrent
type Torrent struct {
ID int `json:"id"`
Category TorrentCategory `json:"category"`
Status UserStatus `json:"status"`
Name string `json:"name"`
NumFiles int `json:"num_files"`
Size uint64 `json:"size"`
Seeders int `json:"seeders"`
Leechers int `json:"leechers"`
User string `json:"username"`
Added time.Time `json:"added"`
Description string `json:"descripiton"`
InfoHash string `json:"info_hash"`
ImdbID string `json:"imdb"`
}
// UnmarshalJSON is a custom unmarshal function to handle timestamps and
// boolean as int and convert them to the right type.
func (t *Torrent) UnmarshalJSON(data []byte) error {
var aux struct {
ID flexInt `json:"id"`
Category flexInt `json:"category"`
Status string `json:"status"`
Name string `json:"name"`
NumFiles flexInt `json:"num_files"`
InfoHash string `json:"info_hash"`
Description string `json:"descr"`
Leechers flexInt `json:"leechers"`
Seeders flexInt `json:"seeders"`
User string `json:"username"`
Size flexInt `json:"size"`
Added flexInt `json:"added"`
ImdbID flexString `json:"imdb"`
}
// Decode json into the aux struct
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
t.ID = int(aux.ID)
t.Category = TorrentCategory(int(aux.Category))
t.Status = UserStatus(aux.Status)
t.Name = aux.Name
t.NumFiles = int(aux.NumFiles)
t.Size = uint64(aux.Size)
t.Seeders = int(aux.Seeders)
t.Leechers = int(aux.Leechers)
t.User = aux.User
t.Added = time.Unix(int64(aux.Added), 0)
t.Description = aux.Description
t.InfoHash = aux.InfoHash
t.ImdbID = string(aux.ImdbID)
return nil
}
// flexInt represents a int that is a string or a int in json
// - if it's a int, it represents the int
// - if it's a string, it represents the string converted in int
type flexInt int
func (fi *flexInt) UnmarshalJSON(b []byte) error {
if len(b) == 0 {
return fmt.Errorf("json: Unmarshaling nil data")
}
if b[0] != '"' {
return json.Unmarshal(b, (*int)(fi))
}
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
i, err := strconv.Atoi(s)
if err != nil {
return err
}
*fi = flexInt(i)
return nil
}
// flexString represents a string or 'null' in json
// - if it's a string, it represents the string
// - if it's not, it's ""
type flexString string
func (fs *flexString) UnmarshalJSON(b []byte) error {
if len(b) == 0 {
return fmt.Errorf("json: Unmarshaling nil data")
}
if b[0] != '"' {
*fs = ""
return nil
}
return json.Unmarshal(b, (*string)(fs))
}