torrent/web_seed.go

98 lines
2.0 KiB
Go
Raw Normal View History

2020-05-30 07:52:27 +00:00
package torrent
import (
"net/http"
2020-06-01 08:25:45 +00:00
2020-06-02 06:41:49 +00:00
"github.com/anacrolix/log"
"github.com/anacrolix/torrent/common"
"github.com/anacrolix/torrent/metainfo"
2020-06-01 08:41:21 +00:00
pp "github.com/anacrolix/torrent/peer_protocol"
2020-06-01 08:25:45 +00:00
"github.com/anacrolix/torrent/segments"
"github.com/anacrolix/torrent/webseed"
2020-05-30 07:52:27 +00:00
)
2020-06-01 08:25:45 +00:00
type httpRequestResult struct {
resp *http.Response
err error
}
type requestPart struct {
req *http.Request
e segments.Extent
result chan httpRequestResult
}
type webseedRequest struct {
cancel func()
}
2020-05-30 07:52:27 +00:00
type webSeed struct {
client webseed.Client
requests map[request]webseed.Request
peer peer
2020-06-01 08:25:45 +00:00
}
var _ PeerImpl = (*webSeed)(nil)
func (ws *webSeed) onGotInfo(info *metainfo.Info) {
ws.client.FileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
ws.client.Info = info
}
2020-05-31 03:22:36 +00:00
func (ws *webSeed) PostCancel(r request) {
2020-06-01 08:25:45 +00:00
ws.Cancel(r)
2020-05-30 07:52:27 +00:00
}
2020-05-31 03:22:36 +00:00
func (ws *webSeed) WriteInterested(interested bool) bool {
2020-05-30 07:52:27 +00:00
return true
}
2020-05-31 03:22:36 +00:00
func (ws *webSeed) Cancel(r request) bool {
ws.requests[r].Cancel()
2020-06-01 08:25:45 +00:00
return true
2020-05-30 07:52:27 +00:00
}
func (ws *webSeed) intoSpec(r request) webseed.RequestSpec {
return webseed.RequestSpec{ws.peer.t.requestOffset(r), int64(r.Length)}
}
2020-05-31 03:22:36 +00:00
func (ws *webSeed) Request(r request) bool {
webseedRequest := ws.client.NewRequest(ws.intoSpec(r))
ws.requests[r] = webseedRequest
go ws.requestResultHandler(r, webseedRequest)
2020-06-01 08:25:45 +00:00
return true
2020-05-30 07:52:27 +00:00
}
2020-05-31 03:22:36 +00:00
func (ws *webSeed) ConnectionFlags() string {
2020-05-30 07:52:27 +00:00
return "WS"
}
2020-05-31 03:22:36 +00:00
func (ws *webSeed) Drop() {
2020-05-30 07:52:27 +00:00
}
2020-05-31 03:22:36 +00:00
func (ws *webSeed) UpdateRequests() {
2020-05-30 07:52:27 +00:00
ws.peer.doRequestState()
}
2020-05-31 03:09:56 +00:00
2020-05-31 03:22:36 +00:00
func (ws *webSeed) Close() {}
2020-06-01 08:41:21 +00:00
func (ws *webSeed) requestResultHandler(r request, webseedRequest webseed.Request) {
2020-06-02 06:41:49 +00:00
result := <-webseedRequest.Result
ws.peer.t.cl.lock()
2020-06-02 06:41:49 +00:00
defer ws.peer.t.cl.unlock()
if result.Err != nil {
log.Printf("webseed request rejected: %v", result.Err)
ws.peer.remoteRejectedRequest(r)
} else {
err := ws.peer.receiveChunk(&pp.Message{
Type: pp.Piece,
Index: r.Index,
Begin: r.Begin,
Piece: result.Bytes,
})
if err != nil {
panic(err)
}
2020-06-01 08:41:21 +00:00
}
}