-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsession.go
236 lines (218 loc) · 5.36 KB
/
session.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package githubbot
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"github.com/Sirupsen/logrus"
"github.com/gorilla/websocket"
)
type Session struct {
RoomName string
password string
conn *websocket.Conn
inbound chan *PacketEvent
outbound chan *PacketEvent
errChan chan error
msgID int
port int
secret string
logger *logrus.Logger
uptime time.Time
waiting bool
commitParent map[string]string
}
func (s *Session) connectOnce() error {
s.logger.Debugln("Connecting to euphoria via TLS...")
tlsConn, err := tls.Dial("tcp", "euphoria.io:443", &tls.Config{})
if err != nil {
s.logger.Warningln("Connection via TLS failed.")
return err
}
roomURL, _ := url.Parse(fmt.Sprintf("wss://euphoria.io/room/%s/ws", s.RoomName))
wsConn, _, err := websocket.NewClient(tlsConn, roomURL, http.Header{}, 4096, 4096)
if err != nil {
s.logger.Warningln("Upgrade of TLS connection to websocket failed.")
return err
}
s.conn = wsConn
s.logger.Debugln("Connection complete.")
return nil
}
func (s *Session) connect() error {
var err error
for i := 0; i < 5; i++ {
if err = s.connectOnce(); err == nil {
go s.sendNick()
return nil
} else {
s.logger.Infof("Error while connecting: %s\n", err)
time.Sleep(time.Duration(i+1) * time.Second * 5)
}
}
return err
}
func (s *Session) receivePacket() error {
var packet PacketEvent
err := s.conn.ReadJSON(&packet)
if err != nil {
if err := s.connect(); err != nil {
return err
}
if err := s.conn.ReadJSON(&packet); err != nil {
return nil
}
}
s.inbound <- &packet
return nil
}
func (s *Session) receiver() {
for {
err := s.receivePacket()
if err != nil {
s.logger.Fatalf("Error receiving packet: %s\n", err)
}
}
}
func (s *Session) sendPayload(payload interface{}, pType PacketType, packetID string) {
rawPayload, err := json.Marshal(payload)
if err != nil {
s.logger.Fatalf("Could not marshal payload: %s\n", err)
}
packet := &PacketEvent{
ID: packetID,
Type: pType,
}
if err := packet.Data.UnmarshalJSON(rawPayload); err != nil {
s.logger.Fatalf("Could not unmarshal raw message to packet: %s\n", err)
}
s.outbound <- packet
}
func (s *Session) sendAuth() {
s.logger.Infoln("Sending auth.")
payload := AuthCommand{
Type: "passcode",
Passcode: s.password}
s.sendPayload(payload, AuthType, strconv.Itoa(s.msgID))
s.msgID++
}
func (s *Session) sendNick() {
s.logger.Infoln("Sending nick.")
payload := NickCommand{Name: "GithubBot"}
s.sendPayload(payload, NickType, strconv.Itoa(s.msgID))
s.msgID++
}
func (s *Session) sendMessage(text string, parent string, packetID string) {
s.logger.Infof("Sending text message: '%s'", text)
payload := SendCommand{
Content: text,
Parent: parent,
}
s.sendPayload(payload, SendType, packetID)
}
func (s *Session) handlePing(p *PacketEvent) {
s.logger.Debugln("Handling ping.")
data, err := p.Payload()
if err != nil {
panic(err)
}
payload, ok := data.(*PingEvent)
if !ok {
logrus.Fatalln("Cannot assert *PingEvent as such.")
}
out := PingReply{UnixTime: payload.Time}
s.sendPayload(out, PingReplyType, strconv.Itoa(s.msgID))
s.msgID++
}
func (s *Session) handleSend(p *PacketEvent) {
s.logger.Debugln("Handling send-event.")
data, err := p.Payload()
if err != nil {
panic(err)
}
payload, ok := data.(*SendEvent)
if !ok {
logrus.Fatalln("Cannot assert *SendEvent as such.")
}
if payload.Content == "!uptime" {
since := time.Since(s.uptime)
s.sendMessage(fmt.Sprintf(
"This bot has been up for %s.",
since.String()),
p.ID, strconv.Itoa(s.msgID))
s.msgID++
}
}
func (s *Session) inboundHandler(sendReplyChan chan PacketEvent) {
for {
packet := <-s.inbound
s.logger.Infof("Receiving packet of type '%s'\n", packet.Type)
switch packet.Type {
case PingEventType:
s.handlePing(packet)
case SendEventType:
s.handleSend(packet)
case SendReplyType:
if !s.waiting {
continue
}
sendReplyChan <- *packet
default:
s.logger.Infof("Unhandled packet type '%s'", packet.Type)
}
}
}
func (s *Session) outboundHandler() {
for {
packet := <-s.outbound
s.logger.Infof("Sending packet of type '%s'\n", packet.Type)
err := s.conn.WriteJSON(packet)
if err != nil {
if err := s.connect(); err != nil {
s.logger.Fatalf("Error sending packet: %s\n", err)
}
if err := s.conn.WriteJSON(packet); err != nil {
s.logger.Fatalf("Error sending packet: %s\n", err)
}
}
}
}
func NewSession(roomName, password string, port int, secret string, logger *logrus.Logger) (*Session, error) {
inbound := make(chan *PacketEvent)
outbound := make(chan *PacketEvent)
errChan := make(chan error)
s := Session{
RoomName: roomName,
password: password,
inbound: inbound,
outbound: outbound,
errChan: errChan,
msgID: 0,
logger: logger,
port: port,
secret: secret,
uptime: time.Now(),
commitParent: make(map[string]string),
}
if err := s.connect(); err != nil {
return nil, err
}
return &s, nil
}
func (s *Session) Run() {
if s.password != "" {
go s.sendAuth()
}
sendReplyChan := make(chan PacketEvent)
go s.outboundHandler()
go s.inboundHandler(sendReplyChan)
go s.receiver()
go s.sendNick()
go s.hookServer(s.port, s.secret, sendReplyChan)
go s.ciHandler()
err := <-s.errChan
s.logger.Fatalln("Session.Run: %s", err)
}