forked from freechessclub/freechessclub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
srv.go
158 lines (138 loc) · 3.34 KB
/
srv.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
// Copyright © 2019 Free Chess Club <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/json"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/freechessclub/icsgo"
"github.com/gorilla/websocket"
)
// control message
type ctlMsg struct {
Command int `json:"command"`
Control string `json:"control"`
}
// Session represents a new game session
type Session struct {
client *icsgo.Client
ws *websocket.Conn
username string
wlock sync.Mutex
}
func newSession(user, pass, ip string, ws *websocket.Conn) (*Session, error) {
cmd := 1
var username string
// create a new FICS client
client, err := icsgo.NewClient(
&icsgo.Config{},
"freechess.org:5000", user, pass)
if err != nil {
cmd = 2
username = err.Error()
return nil, fmt.Errorf("failed to create a new ICS client: %v", err)
}
// log.Printf("Registering IP: %s", "%i"+ip)
// if err := client.Send("%i" + ip); err != nil {
// return nil, err
// }
username = client.Username()
bs, _ := json.Marshal(&ctlMsg{
Command: cmd,
Control: username,
})
err = sendWS(ws, bs)
if err != nil {
return nil, err
}
s := &Session{
client: client,
ws: ws,
username: username,
}
go s.keepAlive(80 * time.Second)
go s.ficsReader()
return s, nil
}
func (s *Session) ficsReader() {
for {
msgs, err := s.client.Recv()
if err != nil {
log.WithField("err", err).Println("failed to create a new session")
s.end()
break
}
if msgs == nil {
continue
}
var m interface{}
if len(msgs) == 1 {
m = msgs[0]
} else {
m = msgs
}
bs, err := json.Marshal(m)
if err != nil {
log.Println("Error marshaling message")
}
if len(bs) == 0 {
continue
}
s.wlock.Lock()
sendWS(s.ws, []byte(bs))
s.wlock.Unlock()
}
}
func (s *Session) keepAlive(timeout time.Duration) {
var lastResponse int64
atomic.StoreInt64(&lastResponse, time.Now().UnixNano())
s.ws.SetPongHandler(func(msg string) error {
atomic.StoreInt64(&lastResponse, time.Now().UnixNano())
return nil
})
for {
s.wlock.Lock()
err := s.ws.WriteMessage(websocket.PingMessage, []byte("keepalive"))
s.wlock.Unlock()
if err != nil {
log.WithField("err", err).Println("failed to write to websocket")
s.end()
return
}
time.Sleep(timeout / 2)
if atomic.LoadInt64(&lastResponse) < time.Now().Add(-timeout).UnixNano() {
log.WithField("err", err).Println("timeout failed")
s.end()
return
}
}
}
// Send sends a message to the server
func (s *Session) Send(msg []byte) error {
return s.client.Send(msg)
}
// Send sends a raw encoded message to the server
func (s *Session) RawSend(msg []byte) error {
return s.client.RawSend(msg)
}
func (s *Session) end() {
s.wlock.Lock()
s.ws.WriteMessage(websocket.CloseMessage, []byte{})
s.wlock.Unlock()
s.client.Send([]byte("exit"))
s.client.Destroy()
s.ws.Close()
}