-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubnub.go
2477 lines (2212 loc) · 84 KB
/
pubnub.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package messaging provides the implemetation to connect to pubnub api on google appengine.
// Build Date: Sep 4, 2014
// Version: 3.6
package messaging
//TODO:
//websockets instead of channels
import (
"appengine"
"appengine/urlfetch"
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/gob"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/gorilla/sessions"
"io/ioutil"
"net"
"net/http"
"net/url"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
// Enums for send response.
const (
responseAlreadySubscribed = 1 << iota //1
responseConnected //2
responseUnsubscribed //3
responseNotSubscribed //4
responseAsIs //5
responseReconnected //6
responseInternetConnIssues //7
reponseAbortMaxRetry //8
responseAsIsError //9
responseWithoutChannel //10
responseTimedOut //11
)
// Enums for diff types of connections
const (
subscribeTrans = 1 << iota
nonSubscribeTrans
presenceHeartbeatTrans
retryTrans
)
const (
//Sdk Identification Param appended to each request
sdkIdentificationParamKey = "pnsdk"
sdkIdentificationParamVal = "PubNub-Go-GAE/3.6"
// This string is appended to all presence channels
// to differentiate from the subscribe requests.
presenceSuffix = "-pnpres"
// This string is used when the server returns a malformed or non-JSON response.
invalidJSON = "Invalid JSON"
// This string is returned as a message when the http request times out.
operationTimeout = "Operation Timeout"
// This string is returned as a message when the http request is aborted.
connectionAborted = "Connection aborted"
// This string is encountered when the http request couldn't connect to the origin.
noSuchHost = "no such host"
// This string is returned as a message when network connection is not avaialbe.
networkUnavailable = "Network unavailable"
// This string is used when the http request faces connectivity issues.
closedNetworkConnection = "closed network connection"
// This string is used when the http request faces connectivity issues.
connectionResetByPeer = "connection reset by peer"
// This string is returned as a message when the http request encounters network connectivity issues.
connectionResetByPeerU = "Connection reset by peer"
// This string is used when the http request times out.
timeout = "timeout"
// This string is returned as a message when the http request times out.
timeoutU = "Timeout"
// This string is retured when the client faces issues in initializing the transport.
errorInInitializing = "Error in initializing connection: "
// This string is used when the server returns a non 200 response on publish
publishFailed = "Publish Failed"
// This string is used when we get an error on conversion from string to JSON
invalidUserStateMap = "Invalid User State Map"
)
// Store for storing a ref of CookieStore
var Store *sessions.CookieStore
var (
//sdkIdentificationParam = fmt.Sprintf("%s=%s", sdkIdentificationParamKey, url.QueryEscape(sdkIdentificationParamVal))
sdkIdentificationParam = sdkIdentificationParamKey + "=" + url.QueryEscape(sdkIdentificationParamVal)
//sdkIdentificationParam = fmt.Sprintf("%s=%s", sdkIdentificationParamKey, sdkIdentificationParamVal)
// The time after which the Publish/HereNow/DetailedHitsory/Unsubscribe/
// UnsibscribePresence/Time request will timeout.
// In seconds.
nonSubscribeTimeout uint16 = 20 //sec
// On Subscribe/Presence timeout, the number of times the reconnect attempts are made.
maxRetries = 50 //times
// The delay in the reconnect attempts on timeout.
// In seconds
retryInterval uint16 = 10 //sec
// The HTTP transport Dial timeout.
// In seconds.
connectTimeout uint16 = 10 //sec
// Root url value of pubnub api without the http/https protocol.
origin = "pubsub.pubnub.com"
// The time after which the Subscribe/Presence request will timeout.
// In seconds.
subscribeTimeout uint16 = 310 //sec
// Mutex to lock the operations on presenceHeartbeat ops
presenceHeartbeatMu sync.RWMutex
// The time after which the server expects the contact from the client.
// In seconds.
// If the server doesnt get an heartbeat request within this time, it will send
// a "timeout" message
presenceHeartbeat uint16 //sec
// The time after which the Presence Heartbeat will fire.
// In seconds.
// We apply the logic Presence Heartbeat/2-1 seconds to calculate it.
// If a user enters a value greater than the Presence Heartbeat value,
// we will reset it to this calculated value.
presenceHeartbeatInterval uint16 //sec
// If resumeOnReconnect is TRUE, then upon reconnect,
// it should use the last successfully retrieved timetoken.
// This has the effect of continuing, or “catching up” to missed traffic.
// If resumeOnReconnect is FALSE, then upon reconnect,
// it should use a 0 (zero) timetoken.
// This has the effect of continuing from “this moment onward”.
// Any messages received since the previous timeout or network error are skipped.
resumeOnReconnect = true
// 16 byte IV
valIV = "0123456789012345"
)
var (
// Global variable to store connection instance for retry requests.
retryConn net.Conn
// Mutux to lock the operations on retryTransport
retryTransportMu sync.RWMutex
// Global variable to store connection instance for presence heartbeat requests.
presenceHeartbeatConn net.Conn
// Mutux to lock the operations on presence heartbeat transport
presenceHeartbeatTransportMu sync.RWMutex
// Global variable to store connection instance for non subscribe requests
// Publish/HereNow/DetailedHitsory/Unsubscribe/UnsibscribePresence/Time.
conn net.Conn
// Global variable to store connection instance for Subscribe/Presence requests.
subscribeConn net.Conn
// Mutux to lock the operations on subscribeTransport
subscribeTransportMu sync.RWMutex
// Mutux to lock the operations on nonSubscribeTransport
nonSubscribeTransportMu sync.RWMutex
// No of retries made since disconnection.
retryCount = 0
// Mutux to lock the operations on retryCount
retryCountMu sync.RWMutex
// variable to store the proxy server if set.
proxyServer string
// variable to store the proxy port if set.
proxyPort int
// variable to store the proxy username if set.
proxyUser string
// variable to store the proxy password if set.
proxyPassword string
// Global variable to check if the proxy server if used.
proxyServerEnabled = false
)
// VersionInfo returns the version of the this code along with the build date.
func VersionInfo() string {
return "PubNub Go GAE client SDK Version: 3.6; Build Date: Sep 4, 2014;"
}
// initStore initializes the cookie store using the secret key
func initStore(secKey string) {
if Store == nil {
Store = sessions.NewCookieStore([]byte(secKey))
}
}
// SetSessionKeys initializes the Pubnub instance using the new Pubnub key.
// This is similar to New but in used to change the keys once the pubnub instance has been initialized
// it accepts
// appengine.Context
// http.ResponseWriter
// *http.Request
// publishKey
// subscribeKey
// secretKey
// cipher
// ssl
// uuid
func SetSessionKeys(context appengine.Context, w http.ResponseWriter, r *http.Request, pubKey string, subKey string, secKey string, cipher string, ssl bool, uuid string) {
initStore(secKey)
session, err := Store.Get(r, "user-session")
if err == nil {
pubInstance := NewPubnub(context, w, r, pubKey, subKey, secKey, cipher, ssl, uuid)
writeSession(context, w, r, pubInstance, session)
} else {
context.Errorf("error in set session , %s", err.Error())
}
}
// DeleteSession deletes the session that stores the pubInstance
// it accepts
// appengine.Context
// http.ResponseWriter
// *http.Request
// secret Key
func DeleteSession(context appengine.Context, w http.ResponseWriter, r *http.Request, secKey string) {
initStore(secKey)
session, err := Store.Get(r, "user-session")
if err == nil &&
session != nil &&
session.Values["pubInstance"] != nil {
session.Values["pubInstance"] = ""
session.Options = GetSessionsOptionsObject(-1)
session.Save(r, w)
context.Infof("Deleted Session %s")
}
}
// GetSessionsOptionsObject sets common Path, Age and HttpOnly options for the sessions.
// It returns the *sessions.Options object
func GetSessionsOptionsObject(age int) *sessions.Options {
return &sessions.Options{
Path: "/",
MaxAge: age,
HttpOnly: true,
}
}
// New initializes the Session and the Pubnub instance.
// It accepts:
// appengine.Context
// uuid
// http.ResponseWriter
// *http.Request
// publishKey
// subscribeKey
// secretKey
// cipher
// ssl
// It returns the Pubnub Instance
func New(context appengine.Context, uuid string, w http.ResponseWriter, r *http.Request, publishKey string, subscribeKey string, secretKey string, cipher string, ssl bool) *Pubnub {
initStore(secretKey)
session, err := Store.Get(r, "user-session")
var pubInstance *Pubnub
gob.Register(pubInstance)
if err == nil &&
session != nil &&
session.Values["pubInstance"] != nil {
if val, ok := session.Values["pubInstance"].(*Pubnub); ok {
pubInstance = val
uuidn1 := pubInstance.GetUUID()
context.Infof("retrieved instance %s", uuidn1)
}
} else {
if err != nil {
context.Errorf("Session error: %s", err.Error())
}
if session == nil {
context.Errorf("Session nil")
}
if session.Values["pubInstance"] == nil {
context.Errorf("pubInstance nil")
}
}
if pubInstance == nil {
pubKey := publishKey
subKey := subscribeKey
secKey := secretKey
context.Infof("Creating NEW session")
pubInstance = NewPubnub(context, w, r, pubKey, subKey, secKey, cipher, ssl, uuid)
writeSession(context, w, r, pubInstance, session)
}
return pubInstance
}
func writeSession(context appengine.Context, w http.ResponseWriter, r *http.Request, pubInstance *Pubnub, session *sessions.Session) {
session.Values["pubInstance"] = pubInstance
session.Options = GetSessionsOptionsObject(60 * 20)
gob.Register(pubInstance)
gob.Register(pubInstance.UserState)
err := session.Save(r, w)
if err != nil {
context.Errorf("error in saving session, %s", err.Error())
}
}
func saveSession(context appengine.Context, w http.ResponseWriter, r *http.Request, pubInstance *Pubnub) {
initStore(pubInstance.SecretKey)
gob.Register(pubInstance)
session, err := Store.Get(r, "user-session")
if err == nil &&
session != nil {
session.Values["pubInstance"] = pubInstance
writeSession(context, w, r, pubInstance, session)
} else {
if err != nil {
context.Errorf("Session error save session : %s", err.Error())
}
if session == nil {
context.Errorf("Session nil")
}
}
}
// Pubnub structure.
// origin stores the root url value of pubnub api in the current instance.
// publishKey stores the user specific Publish Key in the current instance.
// subscribeKey stores the user specific Subscribe Key in the current instance.
// secretKey stores the user specific Secret Key in the current instance.
// cipherKey stores the user specific Cipher Key in the current instance.
// authenticationKey stores the Authentication Key in the current instance.
// isSSL is true if enabled, else is false for the current instance.
// uuid is the unique identifier, it can be a custom value or is automatically generated.
// subscribedChannels keeps a list of subscribed Pubnub channels by the user in the a comma separated string.
// timeToken is the current value of the servertime. This will be used to appened in each request.
// sentTimeToken: This is the timetoken sent to the server with the request
// resetTimeToken: In case of a new request or an error this variable is set to true so that the
// timeToken will be set to 0 in the next request.
// presenceChannels: All the presence responses will be routed to this channel. It stores the response channels for
// each pubnub channel as map using the pubnub channel name as the key.
// subscribeChannels: All the subscribe responses will be routed to this channel. It stores the response channels for
// each pubnub channel as map using the pubnub channel name as the key.
// presenceErrorChannels: All the presence error responses will be routed to this channel. It stores the response channels for
// each pubnub channel as map using the pubnub channel name as the key.
// subscribeErrorChannels: All the subscribe error responses will be routed to this channel. It stores the response channels for
// each pubnub channel as map using the pubnub channel name as the key.
// newSubscribedChannels keeps a list of the new subscribed Pubnub channels by the user in the a comma
// separated string, before they are appended to the Pubnub SubscribedChannels.
// isPresenceHeartbeatRunning a variable to keep a check on the presence heartbeat's status
// Mutex to lock the operations on the instance
type Pubnub struct {
Origin string
PublishKey string
SubscribeKey string
SecretKey string
CipherKey string
AuthenticationKey string
IsSSL bool
Uuid string
subscribedChannels string
TimeToken string
SentTimeToken string
ResetTimeToken bool
UserState map[string]map[string]interface{}
}
// PubnubUnitTest structure used to expose some data for unit tests.
type PubnubUnitTest struct {
}
// NewPubnub initializes pubnub struct with the user provided values.
// And then initiates the origin by appending the protocol based upon the sslOn argument.
// Then it uses the customuuid or generates the uuid.
//
// It accepts the following parameters:
// publishKey is the user specific Publish Key. Mandatory.
// subscribeKey is the user specific Subscribe Key. Mandatory.
// secretKey is the user specific Secret Key. Accepts empty string if not used.
// cipherKey stores the user specific Cipher Key. Accepts empty string if not used.
// sslOn is true if enabled, else is false.
// customUuid is the unique identifier, it can be a custom value or sent as empty for automatic generation.
//
// returns the pointer to Pubnub instance.
func NewPubnub(context appengine.Context, w http.ResponseWriter, r *http.Request, publishKey string, subscribeKey string, secretKey string, cipherKey string, sslOn bool, customUuid string) *Pubnub {
context.Infof(fmt.Sprintf("Pubnub Init, %s", VersionInfo()))
context.Infof(fmt.Sprintf("OS: %s", runtime.GOOS))
newPubnub := &Pubnub{}
newPubnub.Origin = origin
newPubnub.PublishKey = publishKey
newPubnub.SubscribeKey = subscribeKey
newPubnub.SecretKey = secretKey
newPubnub.CipherKey = cipherKey
newPubnub.IsSSL = sslOn
newPubnub.Uuid = ""
newPubnub.subscribedChannels = ""
newPubnub.ResetTimeToken = true
newPubnub.TimeToken = "0"
newPubnub.SentTimeToken = "0"
if newPubnub.IsSSL {
newPubnub.Origin = "https://" + newPubnub.Origin
} else {
newPubnub.Origin = "http://" + newPubnub.Origin
}
context.Infof(fmt.Sprintf("Origin: %s", newPubnub.Origin))
//Generate the uuid is custmUuid is not provided
newPubnub.SetUUID(context, w, r, customUuid)
return newPubnub
}
// SetResumeOnReconnect sets the value of resumeOnReconnect.
func SetResumeOnReconnect(val bool) {
resumeOnReconnect = val
}
// SetAuthenticationKey sets the value of authentication key
func (pub *Pubnub) SetAuthenticationKey(context appengine.Context, w http.ResponseWriter, r *http.Request, val string) {
pub.AuthenticationKey = val
saveSession(context, w, r, pub)
}
// GetAuthenticationKey gets the value of authentication key
func (pub *Pubnub) GetAuthenticationKey() string {
return pub.AuthenticationKey
}
// SetUUID sets the value of UUID
func (pub *Pubnub) SetUUID(context appengine.Context, w http.ResponseWriter, r *http.Request, val string) {
if strings.TrimSpace(val) == "" {
uuid, err := GenUuid()
if err == nil {
pub.Uuid = url.QueryEscape(uuid)
} else {
context.Errorf(err.Error())
}
} else {
pub.Uuid = url.QueryEscape(val)
}
saveSession(context, w, r, pub)
}
// GetUUID returns the value of UUID
func (pub *Pubnub) GetUUID() string {
return pub.Uuid
}
// GetPresenceHeartbeatInterval gets the value of presenceHeartbeatInterval
func (pub *Pubnub) GetPresenceHeartbeatInterval() uint16 {
presenceHeartbeatMu.RLock()
defer presenceHeartbeatMu.RUnlock()
return presenceHeartbeatInterval
}
// SetSubscribeTimeout sets the value of subscribeTimeout.
func SetSubscribeTimeout(val uint16) {
subscribeTransportMu.Lock()
defer subscribeTransportMu.Unlock()
subscribeTimeout = val
}
// GetSubscribeTimeout gets the value of subscribeTimeout
func GetSubscribeTimeout() uint16 {
subscribeTransportMu.RLock()
defer subscribeTransportMu.RUnlock()
return subscribeTimeout
}
// SetRetryInterval sets the value of retryInterval.
func SetRetryInterval(val uint16) {
retryInterval = val
}
// SetMaxRetries sets the value of maxRetries.
func SetMaxRetries(val int) {
maxRetries = val
}
// SetNonSubscribeTimeout sets the value of nonsubscribeTimeout.
func SetNonSubscribeTimeout(val uint16) {
nonSubscribeTransportMu.Lock()
defer nonSubscribeTransportMu.Unlock()
nonSubscribeTimeout = val
}
// GetNonSubscribeTimeout gets the value of nonSubscribeTimeout
func GetNonSubscribeTimeout() uint16 {
nonSubscribeTransportMu.RLock()
defer nonSubscribeTransportMu.RUnlock()
return nonSubscribeTimeout
}
// SetIV sets the value of valIV.
func SetIV(val string) {
valIV = val
}
// SetConnectTimeout sets the value of connectTimeout.
func SetConnectTimeout(val uint16) {
connectTimeout = val
}
// SetOrigin sets the value of _origin. Should be called before PubnubInit
func SetOrigin(val string) {
origin = val
}
// GetSentTimeToken returns the timetoken sent to the server, is used only for unit tests
func (pubtest *PubnubUnitTest) GetSentTimeToken(pub *Pubnub) string {
return pub.SentTimeToken
}
// GetTimeToken returns the latest timetoken received from the server, is used only for unit tests
func (pubtest *PubnubUnitTest) GetTimeToken(pub *Pubnub) string {
return pub.TimeToken
}
// closePresenceHeartbeatConnection closes the presence heartbeat connection
func (pub *Pubnub) closePresenceHeartbeatConnection() {
presenceHeartbeatTransportMu.Lock()
if presenceHeartbeatConn != nil {
presenceHeartbeatConn.Close()
}
presenceHeartbeatTransportMu.Unlock()
}
// closeRetryConnection closes the retry connection
func (pub *Pubnub) closeRetryConnection() {
retryTransportMu.Lock()
if retryConn != nil {
retryConn.Close()
}
retryTransportMu.Unlock()
}
// GrantSubscribe is used to give a subscribe channel read, write permissions
// and set TTL values for it. To grant a permission set read or write as true
// to revoke all perms set read and write false and ttl as -1
//
// channel is options and if not provided will set the permissions at subkey level
//
// Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic
func (pub *Pubnub) GrantSubscribe(context appengine.Context, w http.ResponseWriter, r *http.Request, channel string, read bool, write bool, ttl int, callbackChannel chan []byte, errorChannel chan []byte) {
checkCallbackNil(callbackChannel, false, "GrantSubscribe")
checkCallbackNil(errorChannel, true, "GrantSubscribe")
pub.executePam(context, w, r, channel, read, write, ttl, callbackChannel, errorChannel, false)
}
// AuditSubscribe will make a call to display the permissions for a channel or subkey
//
// channel is options and if not provided will set the permissions at subkey level
//
// Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic
func (pub *Pubnub) AuditSubscribe(context appengine.Context, w http.ResponseWriter, r *http.Request, channel string, callbackChannel chan []byte, errorChannel chan []byte) {
checkCallbackNil(callbackChannel, false, "AuditSubscribe")
checkCallbackNil(errorChannel, true, "AuditSubscribe")
pub.executePam(context, w, r, channel, false, false, -1, callbackChannel, errorChannel, true)
}
// GrantPresence is used to give a presence channel read, write permissions
// and set TTL values for it. To grant a permission set read or write as true
// to revoke all perms set read and write false and ttl as -1
//
// channel is options and if not provided will set the permissions at subkey level
//
// Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic
func (pub *Pubnub) GrantPresence(context appengine.Context, w http.ResponseWriter, r *http.Request, channel string, read bool, write bool, ttl int, callbackChannel chan []byte, errorChannel chan []byte) {
checkCallbackNil(callbackChannel, false, "GrantPresence")
checkCallbackNil(errorChannel, true, "GrantPresence")
channel2 := convertToPresenceChannel(channel)
pub.executePam(context, w, r, channel2, read, write, ttl, callbackChannel, errorChannel, false)
}
// AuditPresence will make a call to display the permissions for a channel or subkey
//
// channel is options and if not provided will set the permissions at subkey level
//
// Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic
func (pub *Pubnub) AuditPresence(context appengine.Context, w http.ResponseWriter, r *http.Request, channel string, callbackChannel chan []byte, errorChannel chan []byte) {
checkCallbackNil(callbackChannel, false, "AuditPresence")
checkCallbackNil(errorChannel, true, "AuditPresence")
channel2 := convertToPresenceChannel(channel)
pub.executePam(context, w, r, channel2, false, false, -1, callbackChannel, errorChannel, true)
}
// removeSpacesFromChannelNames will remove the empty spaces from the channels (sent as a comma separated string)
// will return the channels in a comma separated stirng
//
func removeSpacesFromChannelNames(channel string) string {
var retChannel string
channelArray := strings.Split(channel, ",")
comma := ""
for i := 0; i < len(channelArray); i++ {
if i >= 1 {
comma = ","
}
if strings.TrimSpace(channelArray[i]) != "" {
retChannel = fmt.Sprintf("%s%s%s", retChannel, comma, channelArray[i])
}
}
return retChannel
}
// convertToPresenceChannel will add the presence suffix to the channel(s)
// multiple channels are provided as a comma separated string
// returns comma separated string
func convertToPresenceChannel(channel string) string {
var retChannel string
channelArray := strings.Split(channel, ",")
comma := ""
for i := 0; i < len(channelArray); i++ {
if i >= 1 {
comma = ","
}
if strings.TrimSpace(channelArray[i]) != "" {
retChannel = fmt.Sprintf("%s%s%s%s", retChannel, comma, channelArray[i], presenceSuffix)
}
}
return retChannel
}
func queryEscapeMultiple(q string, splitter string) string {
channelArray := strings.Split(q, splitter)
var pBuffer bytes.Buffer
count := 0
for i := 0; i < len(channelArray); i++ {
if count > 0 {
pBuffer.WriteString(splitter)
}
count++
pBuffer.WriteString(url.QueryEscape(channelArray[i]))
}
return pBuffer.String()
}
// executePam is the main method which is called for all PAM requests
//
// for audit request the isAudit parameter should be true
func (pub *Pubnub) executePam(context appengine.Context, w http.ResponseWriter, r *http.Request, channel string, read bool, write bool, ttl int, callbackChannel chan []byte, errorChannel chan []byte, isAudit bool) {
signature := ""
noChannel := true
grantOrAudit := "grant"
authParam := ""
channelParam := ""
readParam := ""
writeParam := ""
timestampParam := ""
ttlParam := ""
var params bytes.Buffer
if strings.TrimSpace(channel) != "" {
if isAudit {
channelParam = fmt.Sprintf("channel=%s", queryEscapeMultiple(channel, ","))
} else {
channelParam = fmt.Sprintf("channel=%s&", queryEscapeMultiple(channel, ","))
}
noChannel = false
}
if strings.TrimSpace(pub.SecretKey) == "" {
message := "Secret key is required"
if noChannel {
pub.sendResponseToChannel(errorChannel, "", responseWithoutChannel, message, "")
} else {
pub.sendResponseToChannel(errorChannel, channel, responseAsIsError, message, "")
}
return
}
if strings.TrimSpace(pub.AuthenticationKey) != "" {
if isAudit {
if !noChannel {
authParam = fmt.Sprintf("auth=%s&", url.QueryEscape(pub.AuthenticationKey))
} else {
authParam = fmt.Sprintf("auth=%s", url.QueryEscape(pub.AuthenticationKey))
}
} else {
authParam = fmt.Sprintf("auth=%s&", url.QueryEscape(pub.AuthenticationKey))
}
}
var pamURLBuffer bytes.Buffer
pamURLBuffer.WriteString("/v1/auth/")
filler := "&"
if (noChannel) && (strings.TrimSpace(pub.AuthenticationKey) == "") {
filler = ""
}
if isAudit {
grantOrAudit = "audit"
timestampParam = fmt.Sprintf("timestamp=%s", getUnixTimeStamp())
} else {
timestampParam = fmt.Sprintf("timestamp=%s", getUnixTimeStamp())
if read {
readParam = "r=1&"
} else {
readParam = "r=0&"
}
if write {
writeParam = "&w=1"
} else {
writeParam = "&w=0"
}
if ttl != -1 {
if isAudit {
ttlParam = fmt.Sprintf("&ttl=%s", strconv.Itoa(ttl))
} else {
ttlParam = fmt.Sprintf("ttl=%s", strconv.Itoa(ttl))
}
}
}
pamURLBuffer.WriteString(grantOrAudit)
if isAudit {
params.WriteString(fmt.Sprintf("%s%s%s%s&%s%s&uuid=%s%s%s", authParam, channelParam, filler, sdkIdentificationParam, readParam, timestampParam, pub.GetUUID(), ttlParam, writeParam))
} else {
if ttl != -1 {
params.WriteString(fmt.Sprintf("%s%s%s&%s%s&%s&uuid=%s%s", authParam, channelParam, sdkIdentificationParam, readParam, timestampParam, ttlParam, pub.GetUUID(), writeParam))
} else {
params.WriteString(fmt.Sprintf("%s%s%s&%s%s&uuid=%s%s", authParam, channelParam, sdkIdentificationParam, readParam, timestampParam, pub.GetUUID(), writeParam))
}
}
raw := fmt.Sprintf("%s\n%s\n%s\n%s", pub.SubscribeKey, pub.PublishKey, grantOrAudit, params.String())
signature = getHmacSha256(pub.SecretKey, raw)
params.WriteString("&")
params.WriteString("signature=")
params.WriteString(signature)
pamURLBuffer.WriteString("/sub-key/")
pamURLBuffer.WriteString(pub.SubscribeKey)
pamURLBuffer.WriteString("?")
pamURLBuffer.WriteString(params.String())
value, _, err := pub.httpRequest(context, w, r, pamURLBuffer.String(), nonSubscribeTrans)
if err != nil {
message := err.Error()
context.Errorf(fmt.Sprintf("PAM Error: %s", message))
if noChannel {
pub.sendResponseToChannel(errorChannel, "", responseWithoutChannel, message, "")
} else {
pub.sendResponseToChannel(errorChannel, channel, responseAsIsError, message, "")
}
} else {
callbackChannel <- []byte(fmt.Sprintf("%s", value))
}
}
// getUnixTimeStamp gets the unix timestamp
//
func getUnixTimeStamp() string {
return fmt.Sprintf("%d", time.Now().Unix())
}
// GetTime is the struct Pubnub's instance method that calls the ExecuteTime
// method to process the time request.
//.
// It accepts the following parameters:
// callbackChannel on which to send the response.
// errorChannel on which to send the error response.
//
// Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic
func (pub *Pubnub) GetTime(context appengine.Context, w http.ResponseWriter, r *http.Request, callbackChannel chan []byte, errorChannel chan []byte) {
checkCallbackNil(callbackChannel, false, "GetTime")
checkCallbackNil(errorChannel, true, "GetTime")
pub.executeTime(context, w, r, callbackChannel, errorChannel, 0)
}
// executeTime is the struct Pubnub's instance method that creates a time request and sends back the
// response to the channel.
// Closes the channel when the response is sent.
// In case we get an invalid json response the routine retries till the _maxRetries to get a valid
// response.
//
// callbackChannel on which to send the response.
// errorChannel on which the error response is sent.
// retryCount to track the retry logic.
func (pub *Pubnub) executeTime(context appengine.Context, w http.ResponseWriter, r *http.Request, callbackChannel chan []byte, errorChannel chan []byte, retryCount int) {
//context := appengine.NewContext(r)
count := retryCount
timeURL := ""
timeURL += "/time"
timeURL += "/0"
timeURL += "?"
timeURL += sdkIdentificationParam
timeURL += "&uuid="
timeURL += pub.GetUUID()
value, _, err := pub.httpRequest(context, w, r, timeURL, nonSubscribeTrans)
if err != nil {
context.Errorf(fmt.Sprintf("Time Error: %s", err.Error()))
pub.sendResponseToChannel(errorChannel, "", responseWithoutChannel, err.Error(), "")
} else {
_, _, _, errJSON := ParseJSON(value, pub.CipherKey)
if errJSON != nil && strings.Contains(errJSON.Error(), invalidJSON) {
context.Errorf(fmt.Sprintf("Time Error: %s", errJSON.Error()))
pub.sendResponseToChannel(errorChannel, "", responseWithoutChannel, errJSON.Error(), "")
if count < maxRetries {
count++
pub.executeTime(context, w, r, callbackChannel, errorChannel, count)
}
} else {
context.Infof(fmt.Sprintf("Time: %s", value))
callbackChannel <- []byte(fmt.Sprintf("%s", value))
}
}
}
// sendPublishRequest is the struct Pubnub's instance method that posts a publish request and
// sends back the response to the channel.
//
// It accepts the following parameters:
// channel: pubnub channel to publish to
// publishUrlString: The url to which the message is to be appended.
// jsonBytes: the message to be sent.
// callbackChannel: Channel on which to send the response.
// errorChannel on which the error response is sent.
func (pub *Pubnub) sendPublishRequest(context appengine.Context, w http.ResponseWriter, r *http.Request, channel string, publishURLString string, jsonBytes []byte, callbackChannel chan []byte, errorChannel chan []byte) {
//context := appengine.NewContext(r)
u := &url.URL{Path: string(jsonBytes)}
encodedPath := u.String()
context.Infof(fmt.Sprintf("Publish: json: %s, encoded: %s", string(jsonBytes), encodedPath))
publishURL := fmt.Sprintf("%s%s", publishURLString, encodedPath)
publishURL = fmt.Sprintf("%s?%s&uuid=%s%s", publishURL, sdkIdentificationParam, pub.GetUUID(), pub.addAuthParam(true))
value, responseCode, err := pub.httpRequest(context, w, r, publishURL, nonSubscribeTrans)
if (responseCode != 200) || (err != nil) {
if (value != nil) && (responseCode > 0) {
var s []interface{}
errJSON := json.Unmarshal(value, &s)
if (errJSON == nil) && (len(s) > 0) {
if message, ok := s[1].(string); ok {
pub.sendResponseToChannel(errorChannel, channel, responseAsIsError, message, strconv.Itoa(responseCode))
} else {
pub.sendResponseToChannel(errorChannel, channel, responseAsIsError, string(value), strconv.Itoa(responseCode))
}
} else {
context.Errorf(fmt.Sprintf("Publish Error: %s", errJSON.Error()))
pub.sendResponseToChannel(errorChannel, channel, responseAsIsError, string(value), strconv.Itoa(responseCode))
}
} else if (err != nil) && (responseCode > 0) {
context.Errorf(fmt.Sprintf("Publish Failed: %s, ResponseCode: %d", err.Error(), responseCode))
pub.sendResponseToChannel(errorChannel, channel, responseAsIsError, err.Error(), strconv.Itoa(responseCode))
} else if err != nil {
context.Errorf(fmt.Sprintf("Publish Failed: %s", err.Error()))
pub.sendResponseToChannel(errorChannel, channel, responseAsIsError, err.Error(), "")
} else {
context.Errorf(fmt.Sprintf("Publish Failed: ResponseCode: %d", responseCode))
pub.sendResponseToChannel(errorChannel, channel, responseAsIsError, publishFailed, strconv.Itoa(responseCode))
}
} else {
_, _, _, errJSON := ParseJSON(value, pub.CipherKey)
if errJSON != nil && strings.Contains(errJSON.Error(), invalidJSON) {
context.Errorf(fmt.Sprintf("Publish Error: %s", errJSON.Error()))
pub.sendResponseToChannel(errorChannel, channel, responseAsIsError, errJSON.Error(), "")
} else {
callbackChannel <- []byte(fmt.Sprintf("%s", value))
}
}
}
func encodeURL(urlString string) string {
var reqURL *url.URL
reqURL, urlErr := url.Parse(urlString)
if urlErr != nil {
return urlString
}
q := reqURL.Query()
reqURL.RawQuery = q.Encode()
return reqURL.String()
}
// invalidMessage takes the message in form of a interface and checks if the message is nil or empty.
// Returns true if the message is nil or empty.
// Returns false is the message is acceptable.
func invalidMessage(message interface{}) bool {
if message == nil {
return true
}
dataInterface := message.(interface{})
switch vv := dataInterface.(type) {
case string:
if strings.TrimSpace(vv) != "" {
return false
}
case []interface{}:
if vv != nil {
return false
}
default:
if vv != nil {
return false
}
}
return true
}
// invalidChannel takes the Pubnub channel and the channel as parameters.
// Multiple Pubnub channels are accepted separated by comma.
// It splits the Pubnub channel string by a comma and checks if the channel empty.
// Returns true if any one of the channel is empty. And sends a response on the Pubnub channel stating
// that there is an "Invalid Channel".
// Returns false if all the channels is acceptable.
func invalidChannel(channel string, c chan []byte) bool {
if strings.TrimSpace(channel) == "" {
return true
}
channelArray := strings.Split(channel, ",")
for i := 0; i < len(channelArray); i++ {
if strings.TrimSpace(channelArray[i]) == "" {
c <- []byte(fmt.Sprintf("Invalid Channel: %s", channel))
return true
}
}
return false
}
// Publish is the struct Pubnub's instance method that creates a publish request and calls
// SendPublishRequest to post the request.
//
// It calls the InvalidChannel and InvalidMessage methods to validate the Pubnub channels and message.
// Calls the GetHmacSha256 to generate a signature if a secretKey is to be used.
// Creates the publish url
// Calls json marshal
// Calls the EncryptString method is the cipherkey is used and calls json marshal
// Closes the channel after the response is received
//
// It accepts the following parameters:
// channel: The Pubnub channel to which the message is to be posted.
// message: message to be posted.
// callbackChannel: Channel on which to send the response back.
// errorChannel on which the error response is sent.
//
// Both callbackChannel and errorChannel are mandatory. If either is nil the code will panic
func (pub *Pubnub) Publish(context appengine.Context, w http.ResponseWriter, r *http.Request, channel string, message interface{}, callbackChannel chan []byte, errorChannel chan []byte) {
checkCallbackNil(callbackChannel, false, "Publish")
checkCallbackNil(errorChannel, true, "Publish")
if pub.PublishKey == "" {
context.Warningf(fmt.Sprintf("Publish key empty"))