-
Notifications
You must be signed in to change notification settings - Fork 25
/
annnounce.go
69 lines (64 loc) · 1.8 KB
/
annnounce.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
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/jackpal/bencode-go"
)
type AnnounceRequest struct {
InfoHash string `query:"info_hash"`
PeerID string `query:"peer_id"`
IP string `query:"ip"`
Port uint16 `query:"port"`
Uploaded uint `query:"uploaded"`
Downloaded uint `query:"downloaded"`
Left uint `query:"left"`
Numwant uint `query:"numwant"`
Key string `query:"key"`
Compact bool `query:"compact"`
SupportCrypto bool `query:"supportcrypto"`
Event string `query:"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 *fiber.Ctx) error {
var req AnnounceRequest
err := c.QueryParser(&req)
if err != nil {
return err
}
req.IP = c.IP()
if req.Numwant == 0 {
req.Numwant = 30
}
switch req.Event {
case "stopped":
DeletePeer(c.Params("room"), req.InfoHash, req.IP, req.Port)
case "completed":
GraduateLeecher(c.Params("room"), req.InfoHash, req.IP, req.Port)
default:
PutPeer(c.Params("room"), req.InfoHash, req.IP, req.Port, req.IsSeeding())
}
peersIPv4, peersIPv6, numSeeders, numLeechers := GetPeers(c.Params("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,
}
defer c.Response().SetConnectionClose()
return bencode.Marshal(c, resp)
}