forked from NyaaPantsu/nyaa
/
functions.go
295 lines (265 loc) · 7.53 KB
/
functions.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package torrentValidator
import (
"encoding/base32"
"encoding/hex"
"io"
"mime/multipart"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/NyaaPantsu/nyaa/config"
"github.com/NyaaPantsu/nyaa/utils/categories"
"github.com/NyaaPantsu/nyaa/utils/cookies"
"github.com/NyaaPantsu/nyaa/utils/format"
msg "github.com/NyaaPantsu/nyaa/utils/messages"
"github.com/NyaaPantsu/nyaa/utils/metainfo"
"github.com/NyaaPantsu/nyaa/utils/torrentLanguages"
"github.com/gin-gonic/gin"
"github.com/zeebo/bencode"
)
func (r *TorrentRequest) ValidateName() error {
// then actually check that we have everything we need
if len(r.Name) == 0 {
return errTorrentNameInvalid
}
return nil
}
func (r *TorrentRequest) ValidateDescription() error {
if len(r.Description) > config.Get().DescriptionLength {
return errTorrentDescInvalid
}
return nil
}
func (r *TorrentRequest) ValidateMagnet() error {
magnetURL, err := url.Parse(string(r.Magnet)) //?
if err != nil {
return err
}
xt := magnetURL.Query().Get("xt")
if !strings.HasPrefix(xt, "urn:btih:") {
return errTorrentMagnetInvalid
}
xt = strings.SplitAfter(xt, ":")[2]
r.Infohash = strings.TrimSpace(strings.ToUpper(strings.Split(xt, "&")[0]))
return nil
}
func (r *TorrentRequest) ValidateWebsiteLink() error {
if r.WebsiteLink != "" {
// WebsiteLink
urlRegexp, _ := regexp.Compile(`^(https?:\/\/|ircs?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*(\/.*)?$`)
if !urlRegexp.MatchString(r.WebsiteLink) {
return errTorrentURIInvalid
}
}
return nil
}
func (r *TorrentRequest) ValidateHash() error {
isBase32, err := regexp.MatchString("^[2-7A-Z]{32}$", r.Infohash)
if err != nil {
return err
}
if !isBase32 {
isBase16, err := regexp.MatchString("^[0-9A-F]{40}$", r.Infohash)
if err != nil {
return err
}
if !isBase16 {
return errTorrentHashInvalid
}
} else {
//convert to base16
data, err := base32.StdEncoding.DecodeString(r.Infohash)
if err != nil {
return err
}
hash16 := make([]byte, hex.EncodedLen(len(data)))
hex.Encode(hash16, data)
r.Infohash = strings.ToUpper(string(hash16))
}
return nil
}
// ExtractCategory : takes an http request and computes category field for this form
func (r *TorrentRequest) ExtractCategory() error {
catsSplit := strings.Split(r.Category, "_")
// need this to prevent out of index panics
if len(catsSplit) != 2 {
return errTorrentCatInvalid
}
CatID, err := strconv.Atoi(catsSplit[0])
if err != nil {
return errTorrentCatInvalid
}
SubCatID, err := strconv.Atoi(catsSplit[1])
if err != nil {
return errTorrentCatInvalid
}
if !categories.Exists(r.Category) {
return errTorrentCatInvalid
}
r.CategoryID = CatID
r.SubCategoryID = SubCatID
return nil
}
// ExtractLanguage : takes a http request, computes the torrent language from the form.
func (r *TorrentRequest) ExtractLanguage() error {
isEnglishCategory := false
for _, cat := range config.Get().Torrents.EnglishOnlyCategories {
if cat == r.Category {
isEnglishCategory = true
break
}
}
if len(r.Languages) == 0 {
// If no language, but in an English category, set to en-us, else just stop the check.
if !isEnglishCategory {
return nil
}
r.Languages = append(r.Languages, "en")
return nil
}
englishSelected := false
for _, language := range r.Languages {
if language == "en" {
englishSelected = true
}
if language != "" && !torrentLanguages.LanguageExists(language) {
return errTorrentLangInvalid
}
if strings.HasPrefix(language, "en") && isEnglishCategory {
englishSelected = true
}
}
// We shouldn't return an error for languages, just adding the right language is enough
if !englishSelected && isEnglishCategory {
r.Languages = append(r.Languages, "en")
return nil
}
// We shouldn't return an error if someone has selected only english for languages and missed the right category. Just move the torrent in the right one
// Multiple if conditions so we only do this for loop when needed
if len(r.Languages) == 1 && strings.HasPrefix(r.Languages[0], "en") && !isEnglishCategory && r.CategoryID > 0 {
for key, cat := range config.Get().Torrents.NonEnglishOnlyCategories {
if cat == r.Category {
r.Category = config.Get().Torrents.EnglishOnlyCategories[key]
isEnglishCategory = true
break
}
}
}
return nil
}
// ValidateMultipartUpload : Check if multipart upload is valid
func (r *TorrentRequest) ValidateMultipartUpload(c *gin.Context, uploadFormTorrent string) (multipart.File, error) {
// first: parse torrent file (if any) to fill missing information
tfile, _, err := c.Request.FormFile(uploadFormTorrent)
if err == nil {
var torrent metainfo.TorrentFile
// decode torrent
_, seekErr := tfile.Seek(0, io.SeekStart)
if seekErr != nil {
return tfile, seekErr
}
err = bencode.NewDecoder(tfile).Decode(&torrent)
if err != nil {
return tfile, metainfo.ErrInvalidTorrentFile
}
// check a few things
if torrent.IsPrivate() {
return tfile, errTorrentPrivate
}
trackers := torrent.GetAllAnnounceURLS()
r.Trackers = CheckTrackers(trackers)
if len(r.Trackers) == 0 {
return tfile, errTorrentNoTrackers
}
// Name
if len(r.Name) == 0 {
r.Name = torrent.TorrentName()
}
// Magnet link: if a file is provided it should be empty
if len(r.Magnet) != 0 {
return tfile, errTorrentAndMagnet
}
_, seekErr = tfile.Seek(0, io.SeekStart)
if seekErr != nil {
return tfile, seekErr
}
infohash, err := metainfo.DecodeInfohash(tfile)
if err != nil {
return tfile, metainfo.ErrInvalidTorrentFile
}
r.Infohash = infohash
r.Magnet = format.InfoHashToMagnet(infohash, r.Name, trackers...)
// extract filesize
r.Filesize = int64(torrent.TotalSize())
// extract filelist
fileInfos := torrent.Info.GetFiles()
for _, fileInfo := range fileInfos {
r.FileList = append(r.FileList, uploadedFile{
Path: fileInfo.Path,
Filesize: int64(fileInfo.Length),
})
}
} else {
err = r.ValidateMagnet()
if err != nil {
return tfile, err
}
err = r.ValidateHash()
if err != nil {
return tfile, err
}
// TODO: Get Trackers from magnet URL
r.Filesize = 0
r.Filepath = ""
return tfile, nil
}
return tfile, err
}
// ExtractInfo : Function to assign values from request to ReassignForm
func (f *ReassignForm) ExtractInfo(c *gin.Context) bool {
f.By = c.PostForm("by")
messages := msg.GetMessages(c)
if f.By != "olduser" && f.By != "torrentid" {
messages.AddErrorTf("errors", "no_action_exist", f.By)
return false
}
f.Data = strings.Trim(c.PostForm("data"), " \r\n")
if f.By == "olduser" {
if f.Data == "" {
messages.AddErrorT("errors", "user_not_found")
return false
} else if strings.Contains(f.Data, "\n") {
messages.AddErrorT("errors", "multiple_username_error")
return false
}
} else if f.By == "torrentid" {
if f.Data == "" {
messages.AddErrorT("errors", "no_id_given")
return false
}
splitData := strings.Split(f.Data, "\n")
for i, tmp := range splitData {
tmp = strings.Trim(tmp, " \r")
torrentID, err := strconv.ParseUint(tmp, 10, 0)
if err != nil {
messages.AddErrorTf("errors", "parse_error_line", i+1)
return false // TODO: Shouldn't it continue to parse the rest and display the errored lines?
}
f.Torrents = append(f.Torrents, uint(torrentID))
}
}
tmpID := c.PostForm("to")
parsed, err := strconv.ParseUint(tmpID, 10, 32)
if err != nil {
messages.Error(err)
return false
}
f.AssignTo = uint(parsed)
_, _, _, _, err = cookies.RetrieveUserFromRequest(c, uint(parsed))
if err != nil {
messages.AddErrorTf("errors", "no_user_found_id", int(parsed))
return false
}
return true
}