]> git.lizzy.rs Git - go-anidb.git/blob - udp/misc.go
Modernize
[go-anidb.git] / udp / misc.go
1 package udpapi
2
3 import (
4         "encoding/gob"
5         "strconv"
6         "time"
7 )
8
9 func init() {
10         // implements APIReply
11         gob.RegisterName("*udpapi.UptimeReply", &UptimeReply{})
12         // implements APIReply
13         gob.RegisterName("*udpapi.PingReply", &PingReply{})
14 }
15
16 type UptimeReply struct {
17         APIReply
18         Uptime time.Duration
19 }
20
21 // Retrieves the server's uptime. The recommended way to verify if a session
22 // is valid.
23 //
24 // Returns a channel through which the eventual response will be sent.
25 //
26 // http://wiki.anidb.net/w/UDP_API_Definition#UPTIME:_Retrieve_Server_Uptime
27 func (a *AniDBUDP) Uptime() <-chan *UptimeReply {
28         ch := make(chan *UptimeReply, 2)
29         go func() {
30                 reply := <-a.SendRecv("UPTIME", ParamMap{})
31
32                 r := &UptimeReply{APIReply: reply}
33                 if r.Error() == nil {
34                         uptime, _ := strconv.ParseInt(reply.Lines()[1], 10, 32)
35                         r.Uptime = time.Duration(uptime) * time.Millisecond
36                 }
37                 ch <- r
38                 close(ch)
39         }()
40         return ch
41 }
42
43 type PingReply struct {
44         APIReply
45         Port uint16 // This client's local UDP port
46 }
47
48 // Simple echo command. The recommended way to verify if the server
49 // is alive and responding. Does not require authentication.
50 //
51 // Returns a channel through which the eventual response will be sent.
52 //
53 // http://wiki.anidb.net/w/UDP_API_Definition#PING:_Ping_Command
54 func (a *AniDBUDP) Ping() <-chan *PingReply {
55         ch := make(chan *PingReply, 2)
56         go func() {
57                 reply := <-a.SendRecv("PING", ParamMap{"nat": 1})
58
59                 r := &PingReply{APIReply: reply}
60                 if r.Error() == nil {
61                         port, _ := strconv.ParseUint(reply.Lines()[1], 10, 16)
62                         r.Port = uint16(port)
63                 }
64                 ch <- r
65                 close(ch)
66         }()
67         return ch
68 }