torrent/wstracker.go

88 lines
2.3 KiB
Go
Raw Normal View History

2020-04-06 05:38:01 +00:00
package torrent
import (
"context"
2020-04-06 05:38:01 +00:00
"fmt"
"net"
2021-12-17 21:58:56 +00:00
"net/url"
"sync"
"github.com/anacrolix/log"
"github.com/anacrolix/torrent/tracker/http"
"github.com/gorilla/websocket"
2020-04-06 06:45:47 +00:00
"github.com/anacrolix/torrent/tracker"
2020-04-06 06:45:47 +00:00
"github.com/anacrolix/torrent/webtorrent"
"github.com/pion/datachannel"
2020-04-06 05:38:01 +00:00
)
type websocketTrackerStatus struct {
2020-04-06 05:38:01 +00:00
url url.URL
tc *webtorrent.TrackerClient
2020-04-06 05:38:01 +00:00
}
func (me websocketTrackerStatus) statusLine() string {
2020-04-27 23:13:44 +00:00
return fmt.Sprintf("%+v", me.tc.Stats())
2020-04-06 05:38:01 +00:00
}
2020-04-27 23:13:44 +00:00
func (me websocketTrackerStatus) URL() *url.URL {
return &me.url
2020-04-06 05:38:01 +00:00
}
type refCountedWebtorrentTrackerClient struct {
webtorrent.TrackerClient
refCount int
}
type websocketTrackers struct {
PeerId [20]byte
Logger log.Logger
GetAnnounceRequest func(event tracker.AnnounceEvent, infoHash [20]byte) (tracker.AnnounceRequest, error)
OnConn func(datachannel.ReadWriteCloser, webtorrent.DataChannelContext)
mu sync.Mutex
clients map[string]*refCountedWebtorrentTrackerClient
Proxy http.ProxyFunc
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
}
func (me *websocketTrackers) Get(url string, infoHash [20]byte) (*webtorrent.TrackerClient, func()) {
me.mu.Lock()
defer me.mu.Unlock()
value, ok := me.clients[url]
if !ok {
dialer := &websocket.Dialer{Proxy: me.Proxy, NetDialContext: me.DialContext, HandshakeTimeout: websocket.DefaultDialer.HandshakeTimeout}
value = &refCountedWebtorrentTrackerClient{
TrackerClient: webtorrent.TrackerClient{
Dialer: dialer,
Url: url,
GetAnnounceRequest: me.GetAnnounceRequest,
PeerId: me.PeerId,
OnConn: me.OnConn,
Logger: me.Logger.WithText(func(m log.Msg) string {
return fmt.Sprintf("tracker client for %q: %v", url, m)
}),
},
}
value.TrackerClient.Start(func(err error) {
if err != nil {
me.Logger.Printf("error running tracker client for %q: %v", url, err)
}
})
if me.clients == nil {
me.clients = make(map[string]*refCountedWebtorrentTrackerClient)
}
me.clients[url] = value
}
value.refCount++
return &value.TrackerClient, func() {
me.mu.Lock()
defer me.mu.Unlock()
value.TrackerClient.CloseOffersForInfohash(infoHash)
value.refCount--
if value.refCount == 0 {
value.TrackerClient.Close()
delete(me.clients, url)
}
}
}