forked from bandabh/phxgoclient
-
Notifications
You must be signed in to change notification settings - Fork 1
/
channel.go
301 lines (225 loc) · 5.85 KB
/
channel.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package phxgoclient
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"github.com/gorilla/websocket"
)
type Client struct {
Url url.URL
Socket *websocket.Conn
}
type Channel struct {
State State
Topic string
InitialPayload interface{}
Client Client
RefCount int64
Events map[Event]ChannelCallbackFunc
DataBuffer map[string]interface{}
}
type Message struct {
Topic string `json:"topic"`
Event string `json:"event"`
Payload interface{} `json:"payload"`
Ref int64 `json:"ref"`
}
type MessageResponse struct {
Topic string `json:"topic"`
Ref int `json:"ref"`
Payload Payload `json:"payload"`
Event string `json:"event"`
}
type Payload struct {
Status string `json:"status"`
Response interface{} `json:"response"`
}
func (channel *Channel) Reconnect() {
if channel.State == ErroredState {
channel.Join(channel.InitialPayload)
}
}
func (channel *Channel) ForceReconnect() error {
client, err := Connect(channel.Client.Url)
channel.Client = *client
if err != nil {
return err
}
channel.Join(channel.InitialPayload)
return nil
}
func (channel *Channel) incrementRef() int64 {
channel.RefCount = channel.RefCount + 1
return channel.RefCount
}
// To avoid a connection timeout the client needs to send the server a heartbeat event.
func (channel *Channel) heartbeat() {
if !channel.IsOpen() {
return
}
message := Message{
"phoenix", "heartbeat", nil, 0,
}
channel.Client.Socket.WriteJSON(message)
}
type ChannelCallbackFunc func(response MessageResponse) (data interface{}, err error)
func (channel *Channel) UnRegister(event Event) error {
_, ok := channel.Events[event]
if ok {
delete(channel.Events, event)
return nil
}
return errors.New("event " + event.EventToString() + " exists")
}
func (channel *Channel) IsOpen() bool {
return channel.State != ClosedState && channel.State != LeavingState
}
func (channel *Channel) Register(event Event, callback ChannelCallbackFunc) error {
_, ok := channel.Events[event]
if !ok {
channel.Events[event] = callback
return nil
}
return errors.New("event listner already exists")
}
// Observes all registered events on a channel
func (channel *Channel) Observe() (data interface{}, err error) {
if !channel.IsOpen() {
return nil, errors.New("channel is closed or in leaving state")
}
resp := channel.Read()
callbackMap, ok := channel.Events[ToEvent(resp.Event)]
if ok {
return callbackMap(resp)
}
return nil, errors.New("event not registered, or error while reading response")
}
func unwrapResponse(b []byte) (bool, MessageResponse) {
var data MessageResponse
json.Unmarshal(b, &data)
if data.Payload.Status != "" {
return true, data
}
return false, data
}
func checkIfSocketClose(err error) bool {
return strings.Contains(err.Error(), "websocket: close 1000")
}
func (channel *Channel) Read() MessageResponse {
var resp Message
err := channel.Client.Socket.ReadJSON(&resp)
prepared, _ := json.Marshal(resp)
status, response := unwrapResponse(prepared)
if err != nil {
println(err.Error())
if checkIfSocketClose(err) {
channel.ForceReconnect()
}
}
if status {
switch response.Payload.Status {
case OkStatus.StatusToString():
channel.State = JoinedState
break
case ErrorStatus.StatusToString():
channel.State = ErroredState
break
case TimeoutStatus.StatusToString():
channel.State = ErroredState
break
}
return response
}
return MessageResponse{resp.Topic, int(resp.Ref), Payload{"", resp.Payload}, resp.Event}
}
func (channel *Channel) CanPush() bool {
return channel.State == JoinedState
}
func (channel *Channel) Join(payload interface{}) *Channel {
channel.State = JoiningState
channel.InitialPayload = payload
msg_push(channel, payload, JoinEvent)
return channel
}
// RawPush, unsafe push that does not check if you can push on a channel
func (channel *Channel) RawPush(event string, payload interface{}) {
if event == "" {
event = MessageEvent.EventToString()
}
msg_push(channel, payload, ToEvent(event))
}
// Push event with payload to channel
func (channel *Channel) Push(event string, payload interface{}) error {
if channel.CanPush() {
channel.RawPush(event, payload)
return nil
} else {
channel.DataBuffer[event] = payload
return errors.New("cannot push payload to channel")
}
}
func msg_push(channel *Channel, payload interface{}, event Event) {
message := Message{
channel.Topic, event.EventToString(), payload, channel.incrementRef(),
}
channel.Client.Socket.WriteJSON(message)
}
func (channel *Channel) Leave() {
channel.ChannelLeave()
channel.State = ClosedState
}
func (client Client) MakeChannel(topic string) Channel {
channel := Channel{
ClosedState,
topic,
nil,
client,
0,
make(map[Event]ChannelCallbackFunc),
make(map[string]interface{}),
}
return channel
}
func (client Client) MakeAndJoinAChannel(topic string, payload interface{}) Channel {
ch := client.MakeChannel(topic)
ch.Join(payload)
return ch
}
func Connect(url url.URL) (*Client, error) {
strUrl, errConv := checkUrl(url)
if errConv != nil {
return nil, errors.New("failed to parse url, no proper url format")
}
socket, _, err := websocket.DefaultDialer.Dial(strUrl, nil)
client := Client{
url,
socket,
}
if err != nil {
return nil, errors.New("dial:" + err.Error())
}
return &client, nil
}
func (channel *Channel) ChannelLeave() error {
channel.State = LeavingState
return channel.Client.Close()
}
func (client *Client) Close() error {
return client.Socket.Close()
}
func checkUrl(url url.URL) (string, error) {
if url.Scheme == "" {
url.Scheme = "ws"
fmt.Errorf("scheme not defined, defaulting to ws")
}
if url.Path == "" {
url.Path = "/socket/websocket"
fmt.Errorf("path not defined, defaulting to /socket/websocket")
}
if url.Host == "" {
return url.String(), errors.New("no host specified")
}
return url.String(), nil
}