tracker/http/scrape.go

78 lines
1.8 KiB
Go
Raw Normal View History

2013-06-23 12:21:59 +02:00
// Copyright 2013 The Chihaya Authors. All rights reserved.
// 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 (
2014-06-30 20:59:31 +02:00
"fmt"
2013-11-24 06:49:20 +01:00
"io"
"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/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-02 03:40:29 +02:00
func (t *Tracker) ServeScrape(w http.ResponseWriter, r *http.Request, p httprouter.Params) int {
scrape, err := models.NewScrape(t.cfg, r, p)
if err == models.ErrMalformedRequest {
2014-07-02 03:40:29 +02:00
fail(w, r, err)
return http.StatusOK
} else if err != nil {
return http.StatusInternalServerError
2013-11-24 06:49:20 +01:00
}
2013-06-23 09:56:28 +02:00
2014-07-02 03:40:29 +02:00
conn, err := t.tp.Get()
2013-11-24 06:49:20 +01:00
if err != nil {
2014-07-02 03:40:29 +02:00
return http.StatusInternalServerError
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)
return http.StatusOK
} else if err != nil {
return http.StatusInternalServerError
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)
return http.StatusOK
} else if err != nil {
return http.StatusInternalServerError
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
bencoder := bencode.NewEncoder(w)
2014-07-01 05:21:08 +02:00
fmt.Fprintf(w, "d")
2014-06-24 04:47:43 +02:00
bencoder.Encode("files")
for _, torrent := range torrents {
writeTorrentStatus(w, torrent)
}
2014-07-01 05:21:08 +02:00
fmt.Fprintf(w, "e")
2014-06-24 04:47:43 +02:00
2014-07-02 03:40:29 +02:00
return http.StatusOK
2013-06-23 09:56:28 +02:00
}
2014-06-24 04:47:43 +02:00
func writeTorrentStatus(w io.Writer, t *models.Torrent) {
bencoder := bencode.NewEncoder(w)
2014-06-30 20:59:31 +02:00
bencoder.Encode(t.Infohash)
fmt.Fprintf(w, "d")
2014-06-24 04:47:43 +02:00
bencoder.Encode("complete")
bencoder.Encode(len(t.Seeders))
bencoder.Encode("downloaded")
bencoder.Encode(t.Snatches)
bencoder.Encode("incomplete")
bencoder.Encode(len(t.Leechers))
2014-06-30 20:59:31 +02:00
fmt.Fprintf(w, "e")
2013-06-23 09:56:28 +02:00
}