tracker/server/scrape.go

81 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.
2013-06-23 09:56:28 +02:00
package server
import (
"errors"
"io"
"log"
2013-06-23 09:56:28 +02:00
"net/http"
"path"
2013-08-23 21:39:42 +02:00
"github.com/pushrax/chihaya/models"
2013-06-23 09:56:28 +02:00
)
func (s *Server) serveScrape(w http.ResponseWriter, r *http.Request) {
// Parse the query
pq, err := parseQuery(r.URL.RawQuery)
2013-06-23 09:56:28 +02:00
if err != nil {
fail(errors.New("Error parsing query"), w, r)
2013-06-23 09:56:28 +02:00
return
}
// Start a transaction
tx, err := s.dbConnPool.Get()
2013-06-23 09:56:28 +02:00
if err != nil {
log.Fatal(err)
}
// Find and validate the user
passkey, _ := path.Split(r.URL.Path)
_, err = validateUser(tx, passkey)
if err != nil {
fail(err, w, r)
2013-06-23 09:56:28 +02:00
return
}
io.WriteString(w, "d")
2013-07-12 06:36:24 +02:00
writeBencoded(w, "files")
if pq.Infohashes != nil {
for _, infohash := range pq.Infohashes {
torrent, exists, err := tx.FindTorrent(infohash)
2013-06-23 09:56:28 +02:00
if err != nil {
log.Panicf("server: %s", err)
2013-06-23 09:56:28 +02:00
}
if exists {
2013-07-12 06:36:24 +02:00
writeBencoded(w, infohash)
2013-06-23 09:56:28 +02:00
writeScrapeInfo(w, torrent)
}
}
2013-07-12 06:36:24 +02:00
} else if infohash, exists := pq.Params["info_hash"]; exists {
torrent, exists, err := tx.FindTorrent(infohash)
2013-06-23 09:56:28 +02:00
if err != nil {
log.Panicf("server: %s", err)
2013-06-23 09:56:28 +02:00
}
if exists {
2013-07-12 06:36:24 +02:00
writeBencoded(w, infohash)
2013-06-23 09:56:28 +02:00
writeScrapeInfo(w, torrent)
}
}
io.WriteString(w, "e")
// Finish up and write headers
r.Close = true
w.Header().Add("Content-Type", "text/plain")
w.Header().Add("Connection", "close")
w.(http.Flusher).Flush()
2013-06-23 09:56:28 +02:00
}
2013-08-23 21:39:42 +02:00
func writeScrapeInfo(w io.Writer, torrent *models.Torrent) {
2013-06-23 09:56:28 +02:00
io.WriteString(w, "d")
2013-07-12 06:36:24 +02:00
writeBencoded(w, "complete")
writeBencoded(w, len(torrent.Seeders))
writeBencoded(w, "downloaded")
writeBencoded(w, torrent.Snatches)
writeBencoded(w, "incomplete")
writeBencoded(w, len(torrent.Leechers))
2013-06-23 09:56:28 +02:00
io.WriteString(w, "e")
}