forked from meehow/privtracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
110 lines (100 loc) · 2.59 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"github.com/gin-gonic/gin"
"github.com/jackpal/bencode-go"
)
func main() {
r := gin.Default()
r.GET("/:room/announce", announce)
r.GET("/:room/scrape", scrape)
go Cleanup()
r.Run()
}
type AnnounceRequest struct {
InfoHash string `form:"info_hash"`
PeerID string `form:"peer_id"`
IP string `form:"ip"`
Port uint16 `form:"port"`
Uploaded uint `form:"uploaded"`
Downloaded uint `form:"downloaded"`
Left uint `form:"left"`
Numwant uint `form:"numwant"`
Key string `form:"key"`
Compact bool `form:"compact"`
SupportCrypto bool `form:"supportcrypto"`
Event string `form:"event"`
}
func (req *AnnounceRequest) IsSeeding() bool {
return req.Left == 0
}
type AnnounceResponse struct {
Interval int `bencode:"interval"`
Complete int `bencode:"complete"`
Incomplete int `bencode:"incomplete"`
Peers []byte `bencode:"peers"`
PeersIPv6 []byte `bencode:"peers_ipv6"`
}
func announce(c *gin.Context) {
req := new(AnnounceRequest)
c.BindQuery(req)
// if req.IP == "" {
req.IP = c.ClientIP() // not sure if ip from request should be honored
// }
if req.Numwant == 0 {
req.Numwant = 30
}
switch req.Event {
case "stopped":
DeletePeer(c.Param("room"), req.InfoHash, req.IP, req.Port)
case "completed":
GraduateLeecher(c.Param("room"), req.InfoHash, req.IP, req.Port)
default:
PutPeer(c.Param("room"), req.InfoHash, req.IP, req.Port, req.IsSeeding())
}
peersIPv4, peersIPv6, numSeeders, numLeechers := GetPeers(c.Param("room"), req.InfoHash, req.IP, req.Port, req.IsSeeding(), req.Numwant)
interval := 120
if numSeeders == 0 {
interval /= 2
} else if numLeechers == 0 {
interval *= 2
}
resp := AnnounceResponse{
Interval: interval,
Complete: numSeeders,
Incomplete: numLeechers,
Peers: peersIPv4,
PeersIPv6: peersIPv6,
}
if err := bencode.Marshal(c.Writer, resp); err != nil {
c.Error(err)
return
}
}
type ScrapeRequest struct {
InfoHash string `form:"info_hash"`
}
type ScrapeResponse struct {
Files map[string]Stat `bencode:"files"`
}
type Stat struct {
Complete int `bencode:"complete"`
Incomplete int `bencode:"incomplete"`
// Downloaded uint `bencode:"downloaded"`
}
func scrape(c *gin.Context) {
req := new(ScrapeRequest)
c.BindQuery(req)
numSeeders, numLeechers := GetStats(c.Param("room"), req.InfoHash)
resp := ScrapeResponse{
Files: map[string]Stat{
req.InfoHash: {
Complete: numSeeders,
Incomplete: numLeechers,
},
},
}
if err := bencode.Marshal(c.Writer, resp); err != nil {
c.Error(err)
return
}
}