tracker/server/serve_scrape.go

83 lines
1.7 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.
2013-06-23 09:56:28 +02:00
package server
import (
2013-11-24 06:49:20 +01:00
"io"
"net/http"
2014-06-26 23:10:39 +02:00
"strings"
2013-06-23 09:56:28 +02:00
2014-06-24 04:47:43 +02:00
log "github.com/golang/glog"
"github.com/chihaya/chihaya/bencode"
"github.com/chihaya/chihaya/models"
2013-06-23 09:56:28 +02:00
)
func (s *Server) serveScrape(w http.ResponseWriter, r *http.Request) {
2014-06-24 04:47:43 +02:00
scrape, err := models.NewScrape(r, s.conf)
2013-11-24 06:49:20 +01:00
if err != nil {
2014-06-24 04:47:43 +02:00
fail(err, w, r)
2013-11-24 06:49:20 +01:00
return
}
2013-06-23 09:56:28 +02:00
2014-02-23 05:47:11 +01:00
conn, err := s.trackerPool.Get()
2013-11-24 06:49:20 +01:00
if err != nil {
fail(err, w, r)
}
2013-06-23 09:56:28 +02:00
2014-06-26 23:10:39 +02:00
var user *models.User
2014-06-24 04:47:43 +02:00
if s.conf.Private {
2014-06-26 23:10:39 +02:00
user, err = conn.FindUser(scrape.Passkey)
2013-11-24 06:49:20 +01:00
if err != nil {
2014-06-24 04:47:43 +02:00
fail(err, w, r)
return
2013-11-24 06:49:20 +01:00
}
2014-06-24 04:47:43 +02:00
}
2014-06-26 23:10:39 +02:00
var (
torrents []*models.Torrent
torrentIDs []string
)
2014-06-24 04:47:43 +02:00
for _, infohash := range scrape.Infohashes {
torrent, err := conn.FindTorrent(infohash)
if err != nil {
fail(err, w, r)
return
2013-11-24 06:49:20 +01:00
}
2014-06-24 04:47:43 +02:00
torrents = append(torrents, torrent)
2014-06-26 23:10:39 +02:00
torrentIDs = append(torrentIDs, string(torrent.ID))
2013-11-24 06:49:20 +01:00
}
2014-06-24 04:47:43 +02:00
bencoder := bencode.NewEncoder(w)
bencoder.Encode("d")
bencoder.Encode("files")
for _, torrent := range torrents {
writeTorrentStatus(w, torrent)
}
bencoder.Encode("e")
2013-11-24 06:49:20 +01:00
w.(http.Flusher).Flush()
2014-06-26 23:10:39 +02:00
log.V(5).Infof(
"scrape: ip: %s user: %s torrents: %s",
r.RemoteAddr,
user.ID,
strings.Join(torrentIDs, ", "),
)
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)
bencoder.Encode("t.Infohash")
bencoder.Encode("d")
bencoder.Encode("complete")
bencoder.Encode(len(t.Seeders))
bencoder.Encode("downloaded")
bencoder.Encode(t.Snatches)
bencoder.Encode("incomplete")
bencoder.Encode(len(t.Leechers))
bencoder.Encode("e")
2013-06-23 09:56:28 +02:00
}