/
socket-talk-client.go
437 lines (375 loc) · 9.43 KB
/
socket-talk-client.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package talkclient
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/mjarkk/socket-talk/src"
uuid "github.com/satori/go.uuid"
)
// CB short for CallBack are the callback options
type CB struct {
Res interface{} // The response data,
}
// SubscribeT is the global type for all subscriptions
type SubscribeT struct {
Handeler func(msg *WSMessage)
Subscription string // The non-hased subscription
}
var sockLock sync.Mutex
// Client is the main type from where it's possible to make request
type Client struct {
ServerURL string
ServerWsURL string
Connected bool
Conn *websocket.Conn
DisconnectChan chan error
ConnectChan chan struct{}
innerConnectChan chan struct{}
Subscriptions map[string]SubscribeT
Auth func([]byte) []byte
NoProxy bool
Logging bool
SendedToChan bool
}
// Options are options that can be used in the NewClient function
type Options struct {
Auth func([]byte) []byte // A function to authenticate the message if not spesified this will be ignored
ServerURL string // server url, default: http://localhost:8080/
NoProxy bool // Turn off proxy settings
Logging bool // If this is true the request will be logged
}
// NewClient creates a new client object
func NewClient(options Options) (*Client, error) {
client := &Client{
ServerURL: "http://localhost:8080/",
ServerWsURL: "ws://localhost:8080/",
Auth: options.Auth,
NoProxy: options.NoProxy,
Logging: options.Logging,
}
if options.ServerURL != "" {
if !strings.HasPrefix(options.ServerURL, "http://") && !strings.HasPrefix(options.ServerURL, "https://") {
return nil, errors.New("ServerURL must start with http:// or https://")
}
client.ServerURL = options.ServerURL
if !strings.HasSuffix(options.ServerURL, "/") {
client.ServerURL = client.ServerURL + "/"
}
client.ServerWsURL = client.ServerURL
client.ServerWsURL = strings.Replace(client.ServerWsURL, "https://", "wss://", 1)
client.ServerWsURL = strings.Replace(client.ServerWsURL, "http://", "ws://", 1)
}
client.DisconnectChan = make(chan error)
client.ConnectChan = make(chan struct{})
client.innerConnectChan = make(chan struct{})
client.Subscriptions = map[string]SubscribeT{}
go messageHandeler(client)
return client, nil
}
// Connect connects the client to a websocket
// If the client is already connected it will return nil
func (c *Client) Connect() error {
if c.Connected {
return errors.New("Already connected")
}
dailer := websocket.Dialer{}
if c.NoProxy {
dailer.Proxy = func(*http.Request) (*url.URL, error) {
return nil, nil
}
} else {
dailer.Proxy = http.ProxyFromEnvironment
}
conn, _, err := dailer.Dial(c.ServerWsURL+"socketTalk/ws", nil)
if err != nil {
return err
}
c.Connected = true
c.Conn = conn
if !c.SendedToChan {
c.ConnectChan <- struct{}{}
}
c.SendedToChan = true
c.innerConnectChan <- struct{}{}
return <-c.DisconnectChan
}
// WSMessage is a websocket message
type WSMessage struct {
Bytes []byte // The actual message
ExpectsAnswer bool // ExectsAnswer is true when the sender expects an answer back
Aswer func(data interface{}) // Aswer sends a message back to the sender
BindJSON func(v interface{}) error // Bind the json data to something, this is the same as json.Unmarshal
}
func toTimePart(in int) string {
toReturn := strconv.Itoa(in)
if len(toReturn) == 1 {
toReturn = "0" + toReturn
}
return toReturn
}
func (c *Client) log(sendOrRec bool, what string) {
if c.Logging {
direction := "←"
if sendOrRec {
direction = "→"
}
t := time.Now()
seconds := toTimePart(t.Second())
minutes := toTimePart(t.Minute())
hour := toTimePart(t.Hour())
day := toTimePart(t.Day())
month := toTimePart(int(t.Month()))
fmt.Printf(
"[SOCK-TALK] %v/%v/%v - %v:%v:%v (%v) %v\n",
t.Year(),
month,
day,
hour,
minutes,
seconds,
direction,
what,
)
}
}
// messageHandeler handles all incomming message
func messageHandeler(c *Client) {
for {
if !c.Connected {
<-c.innerConnectChan
}
_, message, err := c.Conn.ReadMessage()
if err != nil {
c.Disconnect(err)
continue
}
go func(message []byte) {
var data src.SendMeta
err := json.Unmarshal(message, &data)
if err != nil {
return
}
sub, ok := c.Subscriptions[data.Title]
if !ok {
c.log(false, data.Title)
return
}
c.log(false, sub.Subscription)
postBytes := []byte{}
if data.MessageID != "" {
postBytes, err = post(c.ServerURL+"socketTalk/get", struct {
ID string `json:"ID"`
}{
ID: data.MessageID,
}, c.NoProxy)
if err != nil {
return
}
}
sub.Handeler(&WSMessage{
Bytes: postBytes,
ExpectsAnswer: data.ExpectsAnswer,
Aswer: func(content interface{}) {
send(sendOptions{
C: c,
Title: data.Title + data.ID,
ExpectsAnswer: false,
Data: content,
}, sendOverwrites{
ID: data.ID,
})
},
BindJSON: func(v interface{}) error {
return json.Unmarshal(postBytes, &v)
},
})
}(message)
}
}
// Subscribe can subscibe to a spesific title
// Example handeler:
//
// func(msg *talkclient.WSMessage) {
// fmt.Println(string(msg.Bytes))
// return nil
// }
func (c *Client) Subscribe(title string, handeler func(msg *WSMessage)) {
c.Subscriptions[src.Hash(title)] = SubscribeT{
handeler,
title,
}
}
// Disconnect disconnects the currnet connection
func (c *Client) Disconnect(err error) {
if !c.Connected {
return
}
c.Connected = false
c.Conn.Close()
c.DisconnectChan <- err
}
// post makes a post request
func post(url string, msg interface{}, noProxy bool) ([]byte, error) {
buf := new(bytes.Buffer)
if msg != nil {
jsonData, err := json.Marshal(msg)
if err != nil {
return nil, err
}
_, err = buf.WriteString(string(jsonData))
if err != nil {
return nil, err
}
}
req, err := http.NewRequest("POST", url, buf)
if err != nil {
return nil, err
}
client := &http.Client{}
if noProxy {
var transport http.RoundTripper = &http.Transport{
Proxy: nil,
}
client.Transport = transport
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
rawOut, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return rawOut, nil
}
type sendOptions struct {
C *Client
Title string
ExpectsAnswer bool
Data interface{}
Res interface{}
}
type sendOverwrites struct {
ID string
}
type endT struct {
Bytes []byte
Err error
}
// send is the underlaying function that sends something into the network
func send(options sendOptions, overwrites ...sendOverwrites) error {
if !options.C.Connected {
return errors.New("Can't send to a closed connection")
}
messageID, err := post(options.C.ServerURL+"socketTalk/set", options.Data, options.C.NoProxy)
if err != nil {
return err
}
id := ""
if len(overwrites) > 0 {
id = overwrites[0].ID
} else {
uuid, err := uuid.NewV4()
if err != nil {
return err
}
id = uuid.String()
}
hashedTitle := src.Hash(options.Title)
sendToWS := src.SendMeta{
ID: id,
MessageID: string(messageID),
ExpectsAnswer: options.ExpectsAnswer,
Title: hashedTitle,
}
jsonData, err := json.Marshal(sendToWS)
if err != nil {
return err
}
options.C.log(true, options.Title)
if options.C.Auth == nil {
sockLock.Lock()
err = options.C.Conn.WriteMessage(1, jsonData)
sockLock.Unlock()
} else {
sockLock.Lock()
err = options.C.Conn.WriteMessage(1, options.C.Auth(jsonData))
sockLock.Unlock()
}
if err != nil {
return err
}
if !options.ExpectsAnswer {
return nil
}
end := make(chan endT)
go func() {
time.Sleep(time.Second * 30)
close(end)
}()
subID := src.Hash(hashedTitle + id)
options.C.Subscriptions[subID] = SubscribeT{
Handeler: func(msg *WSMessage) {
end <- endT{
Bytes: msg.Bytes,
}
},
Subscription: options.Title,
}
options.C.Subscriptions[src.Hash("SOCKET_TALK_AUTH_FAILED")] = SubscribeT{
Handeler: func(msg *WSMessage) {
end <- endT{
Err: errors.New("Authentication failed"),
}
},
Subscription: "SOCKET_TALK_AUTH_FAILED",
}
returnData, ok := <-end
delete(options.C.Subscriptions, subID)
if !ok {
return errors.New("Request timed out")
}
if returnData.Err != nil {
return returnData.Err
}
err = json.Unmarshal(returnData.Bytes, &options.Res)
if err != nil {
return err
}
return nil
}
// Send just sends something into the network
func (c *Client) Send(title string, data interface{}) error {
return send(sendOptions{
C: c,
Title: title,
Data: data,
Res: nil,
})
}
// SureSend sends something into the network and wait for some respone on this message
// If there is no res, it will re-send it
// Use this when you need to be sure the message will actualy be delivered
func (c *Client) SureSend(title string, data interface{}) error {
var res interface{}
return c.SendAndReceive(title, data, &res)
}
// SendAndReceive sends something into the network and waits for a response from someone
func (c *Client) SendAndReceive(title string, data interface{}, res interface{}) error {
return send(sendOptions{
C: c,
Title: title,
ExpectsAnswer: true,
Data: data,
Res: &res,
})
}