scrape.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package httpTracker
  2. import (
  3. "context"
  4. "log"
  5. "net/http"
  6. "net/url"
  7. "github.com/anacrolix/torrent/bencode"
  8. "github.com/anacrolix/torrent/tracker/udp"
  9. "github.com/anacrolix/torrent/types/infohash"
  10. )
  11. type scrapeResponse struct {
  12. Files files `bencode:"files"`
  13. }
  14. // Bencode should support bencode.Unmarshalers from a string in the dict key position.
  15. type files = map[string]udp.ScrapeInfohashResult
  16. func (cl Client) Scrape(ctx context.Context, ihs []infohash.T) (out udp.ScrapeResponse, err error) {
  17. _url := cl.url_.JoinPath("..", "scrape")
  18. query, err := url.ParseQuery(_url.RawQuery)
  19. if err != nil {
  20. return
  21. }
  22. for _, ih := range ihs {
  23. query.Add("info_hash", ih.AsString())
  24. }
  25. _url.RawQuery = query.Encode()
  26. log.Printf("%q", _url.String())
  27. req, err := http.NewRequestWithContext(ctx, http.MethodGet, _url.String(), nil)
  28. if err != nil {
  29. return
  30. }
  31. resp, err := cl.hc.Do(req)
  32. if err != nil {
  33. return
  34. }
  35. defer resp.Body.Close()
  36. var decodedResp scrapeResponse
  37. err = bencode.NewDecoder(resp.Body).Decode(&decodedResp)
  38. for _, ih := range ihs {
  39. out = append(out, decodedResp.Files[ih.AsString()])
  40. }
  41. return
  42. }