]> Sergey Matveev's repositories - btrtrc.git/blob - webseed/request.go
WebSeed PathEscaper API tweaks
[btrtrc.git] / webseed / request.go
1 package webseed
2
3 import (
4         "fmt"
5         "net/http"
6         "net/url"
7         "path"
8         "strings"
9
10         "github.com/anacrolix/torrent/metainfo"
11 )
12
13 type PathEscaper func(pathComps []string) string
14
15 // Escapes path name components suitable for appending to a webseed URL. This works for converting
16 // S3 object keys to URLs too.
17 //
18 // Contrary to the name, this actually does a QueryEscape, rather than a PathEscape. This works
19 // better with most S3 providers.
20 func EscapePath(pathComps []string) string {
21         return defaultPathEscaper(pathComps)
22 }
23
24 func defaultPathEscaper(pathComps []string) string {
25         var ret []string
26         for _, comp := range pathComps {
27                 ret = append(ret, url.QueryEscape(comp))
28         }
29         return path.Join(ret...)
30 }
31
32 func trailingPath(
33         infoName string,
34         fileComps []string,
35         pathEscaper PathEscaper,
36 ) string {
37         if pathEscaper == nil {
38                 pathEscaper = defaultPathEscaper
39         }
40         return pathEscaper(append([]string{infoName}, fileComps...))
41 }
42
43 // Creates a request per BEP 19.
44 func newRequest(
45         url_ string, fileIndex int,
46         info *metainfo.Info,
47         offset, length int64,
48         pathEscaper PathEscaper,
49 ) (*http.Request, error) {
50         fileInfo := info.UpvertedFiles()[fileIndex]
51         if strings.HasSuffix(url_, "/") {
52                 // BEP specifies that we append the file path. We need to escape each component of the path
53                 // for things like spaces and '#'.
54                 url_ += trailingPath(info.Name, fileInfo.Path, pathEscaper)
55         }
56         req, err := http.NewRequest(http.MethodGet, url_, nil)
57         if err != nil {
58                 return nil, err
59         }
60         if offset != 0 || length != fileInfo.Length {
61                 req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1))
62         }
63         return req, nil
64 }