tracker/http/scrape.go

84 lines
1.9 KiB
Go
Raw Normal View History

// Copyright 2014 The Chihaya Authors. All rights reserved.
2013-06-23 12:21:59 +02:00
// Use of this source code is governed by the BSD 2-Clause license,
// which can be found in the LICENSE file.
2014-07-02 03:40:29 +02:00
package http
2013-06-23 09:56:28 +02:00
import (
2013-11-24 06:49:20 +01:00
"net/http"
2013-06-23 09:56:28 +02:00
2014-07-02 03:40:29 +02:00
"github.com/julienschmidt/httprouter"
2014-06-24 04:47:43 +02:00
"github.com/chihaya/bencode"
"github.com/chihaya/chihaya/drivers/tracker"
2014-06-24 04:47:43 +02:00
"github.com/chihaya/chihaya/models"
2013-06-23 09:56:28 +02:00
)
2014-07-09 06:53:57 +02:00
func (t *Tracker) ServeScrape(w http.ResponseWriter, r *http.Request, p httprouter.Params) (int, error) {
2014-07-02 03:40:29 +02:00
scrape, err := models.NewScrape(t.cfg, r, p)
if err == models.ErrMalformedRequest {
2014-07-02 03:40:29 +02:00
fail(w, r, err)
2014-07-09 06:53:57 +02:00
return http.StatusOK, nil
} else if err != nil {
2014-07-09 06:53:57 +02:00
return http.StatusInternalServerError, err
2013-11-24 06:49:20 +01:00
}
2013-06-23 09:56:28 +02:00
conn, err := t.pool.Get()
2013-11-24 06:49:20 +01:00
if err != nil {
2014-07-09 06:53:57 +02:00
return http.StatusInternalServerError, err
2013-11-24 06:49:20 +01:00
}
2013-06-23 09:56:28 +02:00
2014-07-02 03:40:29 +02:00
if t.cfg.Private {
_, err = conn.FindUser(scrape.Passkey)
if err == tracker.ErrUserDNE {
2014-07-02 03:40:29 +02:00
fail(w, r, err)
2014-07-09 06:53:57 +02:00
return http.StatusOK, nil
} else if err != nil {
2014-07-09 06:53:57 +02:00
return http.StatusInternalServerError, err
2013-11-24 06:49:20 +01:00
}
2014-06-24 04:47:43 +02:00
}
2014-07-02 03:40:29 +02:00
var torrents []*models.Torrent
2014-06-24 04:47:43 +02:00
for _, infohash := range scrape.Infohashes {
torrent, err := conn.FindTorrent(infohash)
if err == tracker.ErrTorrentDNE {
2014-07-02 03:40:29 +02:00
fail(w, r, err)
2014-07-09 06:53:57 +02:00
return http.StatusOK, nil
} else if err != nil {
2014-07-09 06:53:57 +02:00
return http.StatusInternalServerError, err
2013-11-24 06:49:20 +01:00
}
2014-06-24 04:47:43 +02:00
torrents = append(torrents, torrent)
2013-11-24 06:49:20 +01:00
}
2014-06-24 04:47:43 +02:00
resp := bencode.NewDict()
resp["files"] = filesDict(torrents)
2014-06-24 04:47:43 +02:00
bencoder := bencode.NewEncoder(w)
err = bencoder.Encode(resp)
if err != nil {
return http.StatusInternalServerError, err
2014-06-24 04:47:43 +02:00
}
2014-07-09 06:53:57 +02:00
return http.StatusOK, nil
2013-06-23 09:56:28 +02:00
}
func filesDict(torrents []*models.Torrent) bencode.Dict {
d := bencode.NewDict()
for _, torrent := range torrents {
d[torrent.Infohash] = torrentDict(torrent)
}
return d
}
func torrentDict(torrent *models.Torrent) bencode.Dict {
d := bencode.NewDict()
d["complete"] = len(torrent.Seeders)
d["incomplete"] = len(torrent.Leechers)
d["downloaded"] = torrent.Snatches
return d
2013-06-23 09:56:28 +02:00
}