tracker/server/serve_scrape.go

92 lines
1.8 KiB
Go
Raw Normal View History

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