/
types.go
1352 lines (1175 loc) · 35.5 KB
/
types.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 types provides data types for persisting objects in the databases.
package types
import (
"database/sql/driver"
"encoding/base32"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"sort"
"strings"
"time"
)
// StoreError satisfies Error interface but allows constant values for
// direct comparison.
type StoreError string
// Error is required by error interface.
func (s StoreError) Error() string {
return string(s)
}
const (
// ErrInternal means DB or other internal failure.
ErrInternal = StoreError("internal")
// ErrMalformed means the secret cannot be parsed or otherwise wrong.
ErrMalformed = StoreError("malformed")
// ErrFailed means authentication failed (wrong login or password, etc).
ErrFailed = StoreError("failed")
// ErrDuplicate means duplicate credential, i.e. non-unique login.
ErrDuplicate = StoreError("duplicate value")
// ErrUnsupported means an operation is not supported.
ErrUnsupported = StoreError("unsupported")
// ErrExpired means the secret has expired.
ErrExpired = StoreError("expired")
// ErrPolicy means policy violation, e.g. password too weak.
ErrPolicy = StoreError("policy")
// ErrCredentials means credentials like email or captcha must be validated.
ErrCredentials = StoreError("credentials")
// ErrUserNotFound means the user was not found.
ErrUserNotFound = StoreError("user not found")
// ErrTopicNotFound means the topic was not found.
ErrTopicNotFound = StoreError("topic not found")
// ErrNotFound means the object other then user or topic was not found.
ErrNotFound = StoreError("not found")
// ErrPermissionDenied means the operation is not permitted.
ErrPermissionDenied = StoreError("denied")
// ErrInvalidResponse means the client's response does not match server's expectation.
ErrInvalidResponse = StoreError("invalid response")
// ErrRedirected means the subscription request was redirected to another topic.
ErrRedirected = StoreError("redirected")
)
// Uid is a database-specific record id, suitable to be used as a primary key.
type Uid uint64
// ZeroUid is a constant representing uninitialized Uid.
const ZeroUid Uid = 0
// NullValue is a Unicode DEL character which indicated that the value is being deleted.
const NullValue = "\u2421"
// Lengths of various Uid representations.
const (
uidBase64Unpadded = 11
p2pBase64Unpadded = 22
)
// IsZero checks if Uid is uninitialized.
func (uid Uid) IsZero() bool {
return uid == ZeroUid
}
// Compare returns 0 if uid is equal to u2, 1 if u2 is greater than uid, -1 if u2 is smaller.
func (uid Uid) Compare(u2 Uid) int {
if uid < u2 {
return -1
} else if uid > u2 {
return 1
}
return 0
}
// MarshalBinary converts Uid to byte slice.
func (uid Uid) MarshalBinary() ([]byte, error) {
dst := make([]byte, 8)
binary.LittleEndian.PutUint64(dst, uint64(uid))
return dst, nil
}
// UnmarshalBinary reads Uid from byte slice.
func (uid *Uid) UnmarshalBinary(b []byte) error {
if len(b) < 8 {
return errors.New("Uid.UnmarshalBinary: invalid length")
}
*uid = Uid(binary.LittleEndian.Uint64(b))
return nil
}
// UnmarshalText reads Uid from string represented as byte slice.
func (uid *Uid) UnmarshalText(src []byte) error {
if len(src) != uidBase64Unpadded {
return errors.New("Uid.UnmarshalText: invalid length")
}
dec := make([]byte, base64.URLEncoding.WithPadding(base64.NoPadding).DecodedLen(uidBase64Unpadded))
count, err := base64.URLEncoding.WithPadding(base64.NoPadding).Decode(dec, src)
if count < 8 {
if err != nil {
return errors.New("Uid.UnmarshalText: failed to decode " + err.Error())
}
return errors.New("Uid.UnmarshalText: failed to decode")
}
*uid = Uid(binary.LittleEndian.Uint64(dec))
return nil
}
// MarshalText converts Uid to string represented as byte slice.
func (uid *Uid) MarshalText() ([]byte, error) {
if *uid == ZeroUid {
return []byte{}, nil
}
src := make([]byte, 8)
dst := make([]byte, base64.URLEncoding.WithPadding(base64.NoPadding).EncodedLen(8))
binary.LittleEndian.PutUint64(src, uint64(*uid))
base64.URLEncoding.WithPadding(base64.NoPadding).Encode(dst, src)
return dst, nil
}
// MarshalJSON converts Uid to double quoted ("ajjj") string.
func (uid *Uid) MarshalJSON() ([]byte, error) {
dst, _ := uid.MarshalText()
return append(append([]byte{'"'}, dst...), '"'), nil
}
// UnmarshalJSON reads Uid from a double quoted string.
func (uid *Uid) UnmarshalJSON(b []byte) error {
size := len(b)
if size != (uidBase64Unpadded + 2) {
return errors.New("Uid.UnmarshalJSON: invalid length")
} else if b[0] != '"' || b[size-1] != '"' {
return errors.New("Uid.UnmarshalJSON: unrecognized")
}
return uid.UnmarshalText(b[1 : size-1])
}
// String converts Uid to base64 string.
func (uid Uid) String() string {
buf, _ := uid.MarshalText()
return string(buf)
}
// String32 converts Uid to lowercase base32 string (suitable for file names on Windows).
func (uid Uid) String32() string {
data, _ := uid.MarshalBinary()
return strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(data))
}
// ParseUid parses string NOT prefixed with anything.
func ParseUid(s string) Uid {
var uid Uid
uid.UnmarshalText([]byte(s))
return uid
}
// ParseUid32 parses base32-encoded string into Uid.
func ParseUid32(s string) Uid {
var uid Uid
if data, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(s); err == nil {
uid.UnmarshalBinary(data)
}
return uid
}
// UserId converts Uid to string prefixed with 'usr', like usrXXXXX.
func (uid Uid) UserId() string {
return uid.PrefixId("usr")
}
// FndName generates 'fnd' topic name for the given Uid.
func (uid Uid) FndName() string {
return uid.PrefixId("fnd")
}
// PrefixId converts Uid to string prefixed with the given prefix.
func (uid Uid) PrefixId(prefix string) string {
if uid.IsZero() {
return ""
}
return prefix + uid.String()
}
// ParseUserId parses user ID of the form "usrXXXXXX".
func ParseUserId(s string) Uid {
var uid Uid
if strings.HasPrefix(s, "usr") {
(&uid).UnmarshalText([]byte(s)[3:])
}
return uid
}
// GrpToChn converts group topic name to corresponding channel name.
func GrpToChn(grp string) string {
if strings.HasPrefix(grp, "grp") {
return strings.Replace(grp, "grp", "chn", 1)
}
// Return unchanged if it's a channel already.
if strings.HasPrefix(grp, "chn") {
return grp
}
return ""
}
// IsChannel checks if the given topic name is a reference to a channel.
// The "nch" should not be considered a channel reference because it can only be used by the topic owner at the time of
// group topic creation.
func IsChannel(name string) bool {
return strings.HasPrefix(name, "chn")
}
// ChnToGrp gets group topic name from channel name.
// If it's a non-channel group topic, the name is returned unchanged.
func ChnToGrp(chn string) string {
if strings.HasPrefix(chn, "chn") {
return strings.Replace(chn, "chn", "grp", 1)
}
// Return unchanged if it's a group already.
if strings.HasPrefix(chn, "grp") {
return chn
}
return ""
}
// UidSlice is a slice of Uids sorted in ascending order.
type UidSlice []Uid
func (us UidSlice) find(uid Uid) (int, bool) {
l := len(us)
if l == 0 || us[0] > uid {
return 0, false
}
if uid > us[l-1] {
return l, false
}
idx := sort.Search(l, func(i int) bool {
return uid <= us[i]
})
return idx, idx < l && us[idx] == uid
}
// Add uid to UidSlice keeping it sorted. Duplicates are ignored.
func (us *UidSlice) Add(uid Uid) bool {
idx, found := us.find(uid)
if found {
return false
}
// Inserting without creating a temporary slice.
*us = append(*us, ZeroUid)
copy((*us)[idx+1:], (*us)[idx:])
(*us)[idx] = uid
return true
}
// Rem removes uid from UidSlice.
func (us *UidSlice) Rem(uid Uid) bool {
idx, found := us.find(uid)
if !found {
return false
}
if idx == len(*us)-1 {
*us = (*us)[:idx]
} else {
*us = append((*us)[:idx], (*us)[idx+1:]...)
}
return true
}
// Contains checks if the UidSlice contains the given UID.
func (us UidSlice) Contains(uid Uid) bool {
_, contains := us.find(uid)
return contains
}
// P2PName takes two Uids and generates a P2P topic name.
func (uid Uid) P2PName(u2 Uid) string {
if !uid.IsZero() && !u2.IsZero() {
b1, _ := uid.MarshalBinary()
b2, _ := u2.MarshalBinary()
if uid < u2 {
b1 = append(b1, b2...)
} else if uid > u2 {
b1 = append(b2, b1...)
} else {
// Explicitly disable P2P with self
return ""
}
return "p2p" + base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(b1)
}
return ""
}
// ParseP2P extracts uids from the name of a p2p topic.
func ParseP2P(p2p string) (uid1, uid2 Uid, err error) {
if strings.HasPrefix(p2p, "p2p") {
src := []byte(p2p)[3:]
if len(src) != p2pBase64Unpadded {
err = errors.New("ParseP2P: invalid length")
return
}
dec := make([]byte, base64.URLEncoding.WithPadding(base64.NoPadding).DecodedLen(p2pBase64Unpadded))
var count int
count, err = base64.URLEncoding.WithPadding(base64.NoPadding).Decode(dec, src)
if count < 16 {
if err != nil {
err = errors.New("ParseP2P: failed to decode " + err.Error())
} else {
err = errors.New("ParseP2P: invalid decoded length")
}
return
}
uid1 = Uid(binary.LittleEndian.Uint64(dec))
uid2 = Uid(binary.LittleEndian.Uint64(dec[8:]))
} else {
err = errors.New("ParseP2P: missing or invalid prefix")
}
return
}
// P2PNameForUser takes a user ID and a full name of a P2P topic and generates the name of the
// P2P topic as it should be seen by the given user.
func P2PNameForUser(uid Uid, p2p string) (string, error) {
uid1, uid2, err := ParseP2P(p2p)
if err != nil {
return "", err
}
if uid.Compare(uid1) == 0 {
return uid2.UserId(), nil
}
return uid1.UserId(), nil
}
// ObjHeader is the header shared by all stored objects.
type ObjHeader struct {
// using string to get around rethinkdb's problems with uint64;
// `bson:"_id"` tag is for mongodb to use as primary key '_id'.
Id string `bson:"_id"`
id Uid
CreatedAt time.Time
UpdatedAt time.Time
}
// Uid assigns Uid header field.
func (h *ObjHeader) Uid() Uid {
if h.id.IsZero() && h.Id != "" {
h.id.UnmarshalText([]byte(h.Id))
}
return h.id
}
// SetUid assigns given Uid to appropriate header fields.
func (h *ObjHeader) SetUid(uid Uid) {
h.id = uid
h.Id = uid.String()
}
// TimeNow returns current wall time in UTC rounded to milliseconds.
func TimeNow() time.Time {
return time.Now().UTC().Round(time.Millisecond)
}
// TimeFormatRFC3339 is a format string for writing timestamps as RFC3339.
const TimeFormatRFC3339 = "2006-01-02T15:04:05.999"
// InitTimes initializes time.Time variables in the header to current time.
func (h *ObjHeader) InitTimes() {
if h.CreatedAt.IsZero() {
h.CreatedAt = TimeNow()
}
h.UpdatedAt = h.CreatedAt
}
// MergeTimes intelligently copies time.Time variables from h2 to h.
func (h *ObjHeader) MergeTimes(h2 *ObjHeader) {
// Set the creation time to the earliest value
if h.CreatedAt.IsZero() || (!h2.CreatedAt.IsZero() && h2.CreatedAt.Before(h.CreatedAt)) {
h.CreatedAt = h2.CreatedAt
}
// Set the update time to the latest value
if h.UpdatedAt.Before(h2.UpdatedAt) {
h.UpdatedAt = h2.UpdatedAt
}
}
// StringSlice is defined so Scanner and Valuer can be attached to it.
type StringSlice []string
// Scan implements sql.Scanner interface.
func (ss *StringSlice) Scan(val interface{}) error {
if val == nil {
return nil
}
return json.Unmarshal(val.([]byte), ss)
}
// Value implements sql/driver.Valuer interface.
func (ss StringSlice) Value() (driver.Value, error) {
return json.Marshal(ss)
}
// ObjState represents information on objects state,
// such as an indication that User or Topic is suspended/soft-deleted.
type ObjState int
const (
// StateOK indicates normal user or topic.
StateOK ObjState = 0
// StateSuspended indicates suspended user or topic.
StateSuspended ObjState = 10
// StateDeleted indicates soft-deleted user or topic.
StateDeleted ObjState = 20
// StateUndefined indicates state which has not been set explicitly.
StateUndefined ObjState = 30
)
// String returns string representation of ObjState.
func (os ObjState) String() string {
switch os {
case StateOK:
return "ok"
case StateSuspended:
return "susp"
case StateDeleted:
return "del"
case StateUndefined:
return "undef"
}
return ""
}
// NewObjState parses string into an ObjState.
func NewObjState(in string) (ObjState, error) {
in = strings.ToLower(in)
switch in {
case "", "ok":
return StateOK, nil
case "susp":
return StateSuspended, nil
case "del":
return StateDeleted, nil
case "undef":
return StateUndefined, nil
}
// This is the default.
return StateOK, errors.New("failed to parse object state")
}
// MarshalJSON converts ObjState to a quoted string.
func (os ObjState) MarshalJSON() ([]byte, error) {
return append(append([]byte{'"'}, []byte(os.String())...), '"'), nil
}
// UnmarshalJSON reads ObjState from a quoted string.
func (os *ObjState) UnmarshalJSON(b []byte) error {
if b[0] != '"' || b[len(b)-1] != '"' {
return errors.New("syntax error")
}
state, err := NewObjState(string(b[1 : len(b)-1]))
if err == nil {
*os = state
}
return err
}
// Scan is an implementation of sql.Scanner interface. It expects the
// value to be a byte slice representation of an ASCII string.
func (os *ObjState) Scan(val interface{}) error {
switch intval := val.(type) {
case int64:
*os = ObjState(intval)
return nil
}
return errors.New("data is not an int64")
}
// Value is an implementation of sql.driver.Valuer interface.
func (os ObjState) Value() (driver.Value, error) {
return int64(os), nil
}
// User is a representation of a DB-stored user record.
type User struct {
ObjHeader `bson:",inline"`
State ObjState
StateAt *time.Time `json:"StateAt,omitempty" bson:",omitempty"`
// Default access to user for P2P topics (used as default modeGiven)
Access DefaultAccess
// Values for 'me' topic:
// Last time when the user joined 'me' topic, by User Agent
LastSeen *time.Time
// User agent provided when accessing the topic last time
UserAgent string
Public interface{}
Trusted interface{}
// Unique indexed tags (email, phone) for finding this user. Stored on the
// 'users' as well as indexed in 'tagunique'
Tags StringSlice
// Info on known devices, used for push notifications
Devices map[string]*DeviceDef `bson:"__devices,skip,omitempty"`
// Same for mongodb scheme. Ignore in other db backends if its not suitable.
DeviceArray []*DeviceDef `json:"-" bson:"devices"`
}
// AccessMode is a definition of access mode bits.
type AccessMode uint
// Various access mode constants
const (
ModeJoin AccessMode = 1 << iota // user can join, i.e. {sub} (J:1)
ModeRead // user can receive broadcasts ({data}, {info}) (R:2)
ModeWrite // user can Write, i.e. {pub} (W:4)
ModePres // user can receive presence updates (P:8)
ModeApprove // user can approve new members or evict existing members (A:0x10, 16)
ModeShare // user can invite new members (S:0x20, 32)
ModeDelete // user can hard-delete messages (D:0x40, 64)
ModeOwner // user is the owner (O:0x80, 128) - full access
ModeUnset // Non-zero value to indicate unknown or undefined mode (:0x100, 256),
// to make it different from ModeNone
ModeNone AccessMode = 0 // No access, requests to gain access are processed normally (N:0)
// Normal user's access to a topic ("JRWPS", 47, 0x2F)
ModeCPublic AccessMode = ModeJoin | ModeRead | ModeWrite | ModePres | ModeShare
// User's subscription to 'me' and 'fnd' ("JPS", 41, 0x29)
ModeCSelf AccessMode = ModeJoin | ModePres | ModeShare
// Owner's subscription to a generic topic ("JRWPASDO", 255, 0xFF)
ModeCFull AccessMode = ModeJoin | ModeRead | ModeWrite | ModePres | ModeApprove | ModeShare | ModeDelete | ModeOwner
// Default P2P access mode ("JRWPA", 31, 0x1F)
ModeCP2P AccessMode = ModeJoin | ModeRead | ModeWrite | ModePres | ModeApprove
// Default Auth access mode for a user ("JRWPAS", 63, 0x3F).
ModeCAuth AccessMode = ModeCP2P | ModeCPublic
// Read-only access to topic ("JR", 3)
ModeCReadOnly = ModeJoin | ModeRead
// Access to 'sys' topic by a root user ("JRWPD", 79, 0x4F)
ModeCSys = ModeJoin | ModeRead | ModeWrite | ModePres | ModeDelete
// Channel publisher: person authorized to publish content; no J: by invitation only ("RWPD", 78, 0x4E)
ModeCChnWriter = ModeRead | ModeWrite | ModePres | ModeShare
// Reader's access mode to a channel (JRP, 11, 0xB).
ModeCChnReader = ModeJoin | ModeRead | ModePres
// Admin: user who can modify access mode ("OA", dec: 144, hex: 0x90)
ModeCAdmin = ModeOwner | ModeApprove
// Sharer: flags which define user who can be notified of access mode changes ("OAS", dec: 176, hex: 0xB0)
ModeCSharer = ModeCAdmin | ModeShare
// Invalid mode to indicate an error
ModeInvalid AccessMode = 0x100000
// All possible valid bits (excluding ModeInvalid and ModeUnset) = 0xFF, 255
ModeBitmask AccessMode = ModeJoin | ModeRead | ModeWrite | ModePres | ModeApprove | ModeShare | ModeDelete | ModeOwner
)
// MarshalText converts AccessMode to ASCII byte slice.
func (m AccessMode) MarshalText() ([]byte, error) {
if m == ModeNone {
return []byte{'N'}, nil
}
if m == ModeInvalid {
return nil, errors.New("AccessMode invalid")
}
res := []byte{}
modes := []byte{'J', 'R', 'W', 'P', 'A', 'S', 'D', 'O'}
for i, chr := range modes {
if (m & (1 << uint(i))) != 0 {
res = append(res, chr)
}
}
return res, nil
}
// ParseAcs parses AccessMode from a byte array.
func ParseAcs(b []byte) (AccessMode, error) {
m0 := ModeUnset
Loop:
for i := 0; i < len(b); i++ {
switch b[i] {
case 'J', 'j':
m0 |= ModeJoin
case 'R', 'r':
m0 |= ModeRead
case 'W', 'w':
m0 |= ModeWrite
case 'A', 'a':
m0 |= ModeApprove
case 'S', 's':
m0 |= ModeShare
case 'D', 'd':
m0 |= ModeDelete
case 'P', 'p':
m0 |= ModePres
case 'O', 'o':
m0 |= ModeOwner
case 'N', 'n':
if m0 != ModeUnset {
return ModeUnset, errors.New("AccessMode: access N cannot be combined with any other")
}
m0 = ModeNone // N means explicitly no access, all bits cleared
break Loop
default:
return ModeUnset, errors.New("AccessMode: invalid character '" + string(b[i]) + "'")
}
}
return m0, nil
}
// UnmarshalText parses access mode string as byte slice.
// Does not change the mode if the string is empty or invalid.
func (m *AccessMode) UnmarshalText(b []byte) error {
m0, err := ParseAcs(b)
if err != nil {
return err
}
if m0 != ModeUnset {
*m = (m0 & ModeBitmask)
}
return nil
}
// String returns string representation of AccessMode.
func (m AccessMode) String() string {
res, err := m.MarshalText()
if err != nil {
return ""
}
return string(res)
}
// MarshalJSON converts AccessMode to a quoted string.
func (m AccessMode) MarshalJSON() ([]byte, error) {
res, err := m.MarshalText()
if err != nil {
return nil, err
}
return append(append([]byte{'"'}, res...), '"'), nil
}
// UnmarshalJSON reads AccessMode from a quoted string.
func (m *AccessMode) UnmarshalJSON(b []byte) error {
if b[0] != '"' || b[len(b)-1] != '"' {
return errors.New("syntax error")
}
return m.UnmarshalText(b[1 : len(b)-1])
}
// Scan is an implementation of sql.Scanner interface. It expects the
// value to be a byte slice representation of an ASCII string.
func (m *AccessMode) Scan(val interface{}) error {
if bb, ok := val.([]byte); ok {
return m.UnmarshalText(bb)
}
return errors.New("scan failed: data is not a byte slice")
}
// Value is an implementation of sql.driver.Valuer interface.
func (m AccessMode) Value() (driver.Value, error) {
res, err := m.MarshalText()
if err != nil {
return "", err
}
return string(res), nil
}
// BetterThan checks if grant mode allows more permissions than requested in want mode.
func (grant AccessMode) BetterThan(want AccessMode) bool {
return ModeBitmask&grant&^want != 0
}
// BetterEqual checks if grant mode allows all permissions requested in want mode.
func (grant AccessMode) BetterEqual(want AccessMode) bool {
return ModeBitmask&grant&want == want
}
// Delta between two modes as a string old.Delta(new). JRPAS -> JRWS: "+W-PA"
// Zero delta is an empty string ""
func (o AccessMode) Delta(n AccessMode) string {
// Removed bits, bits present in 'old' but missing in 'new' -> '-'
var removed string
if o2n := ModeBitmask & o &^ n; o2n > 0 {
removed = o2n.String()
if removed != "" {
removed = "-" + removed
}
}
// Added bits, bits present in 'n' but missing in 'o' -> '+'
var added string
if n2o := ModeBitmask & n &^ o; n2o > 0 {
added = n2o.String()
if added != "" {
added = "+" + added
}
}
return added + removed
}
// ApplyMutation sets of modifies access mode:
// * if `mutation` contains either '+' or '-', attempts to apply a delta change on `m`.
// * otherwise, treats it as an assignment.
func (m *AccessMode) ApplyMutation(mutation string) error {
if mutation == "" {
return nil
}
if strings.ContainsAny(mutation, "+-") {
return m.ApplyDelta(mutation)
}
return m.UnmarshalText([]byte(mutation))
}
// ApplyDelta applies the acs delta to AccessMode.
// Delta is in the same format as generated by AccessMode.Delta.
// E.g. JPRA.ApplyDelta(-PR+W) -> JWA.
func (m *AccessMode) ApplyDelta(delta string) error {
if delta == "" || delta == "N" {
// No updates.
return nil
}
m0 := *m
for next := 0; next+1 < len(delta) && next >= 0; {
ch := delta[next]
end := strings.IndexAny(delta[next+1:], "+-")
var chunk string
if end >= 0 {
end += next + 1
chunk = delta[next+1 : end]
} else {
chunk = delta[next+1:]
}
next = end
upd, err := ParseAcs([]byte(chunk))
if err != nil {
return err
}
switch ch {
case '+':
if upd != ModeUnset {
m0 |= upd & ModeBitmask
}
case '-':
if upd != ModeUnset {
m0 &^= upd & ModeBitmask
}
default:
return errors.New("Invalid acs delta string: '" + delta + "'")
}
}
*m = m0
return nil
}
// IsJoiner checks if joiner flag J is set.
func (m AccessMode) IsJoiner() bool {
return m&ModeJoin != 0
}
// IsOwner checks if owner bit O is set.
func (m AccessMode) IsOwner() bool {
return m&ModeOwner != 0
}
// IsApprover checks if approver A bit is set.
func (m AccessMode) IsApprover() bool {
return m&ModeApprove != 0
}
// IsAdmin check if owner O or approver A flag is set.
func (m AccessMode) IsAdmin() bool {
return m.IsOwner() || m.IsApprover()
}
// IsSharer checks if approver A or sharer S or owner O flag is set.
func (m AccessMode) IsSharer() bool {
return m.IsAdmin() || (m&ModeShare != 0)
}
// IsWriter checks if allowed to publish (writer flag W is set).
func (m AccessMode) IsWriter() bool {
return m&ModeWrite != 0
}
// IsReader checks if reader flag R is set.
func (m AccessMode) IsReader() bool {
return m&ModeRead != 0
}
// IsPresencer checks if user receives presence updates (P flag set).
func (m AccessMode) IsPresencer() bool {
return m&ModePres != 0
}
// IsDeleter checks if user can hard-delete messages (D flag is set).
func (m AccessMode) IsDeleter() bool {
return m&ModeDelete != 0
}
// IsZero checks if no flags are set.
func (m AccessMode) IsZero() bool {
return m == ModeNone
}
// IsInvalid checks if mode is invalid.
func (m AccessMode) IsInvalid() bool {
return m == ModeInvalid
}
// IsDefined checks if the mode is defined: not invalid and not unset.
// ModeNone is considered to be defined.
func (m AccessMode) IsDefined() bool {
return m != ModeInvalid && m != ModeUnset
}
// DefaultAccess is a per-topic default access modes
type DefaultAccess struct {
Auth AccessMode
Anon AccessMode
}
// Scan is an implementation of Scanner interface so the value can be read from SQL DBs
// It assumes the value is serialized and stored as JSON
func (da *DefaultAccess) Scan(val interface{}) error {
return json.Unmarshal(val.([]byte), da)
}
// Value implements sql's driver.Valuer interface.
func (da DefaultAccess) Value() (driver.Value, error) {
return json.Marshal(da)
}
// Credential hold data needed to validate and check validity of a credential like email or phone.
type Credential struct {
ObjHeader `bson:",inline"`
// Credential owner
User string
// Verification method (email, tel, captcha, etc)
Method string
// Credential value - `jdoe@example.com` or `+12345678901`
Value string
// Expected response
Resp string
// If credential was successfully confirmed
Done bool
// Retry count
Retries int
}
type Friendcontact struct {
// User
User string
// Firend ID
FirendID string
}
// LastSeenUA is a timestamp and a user agent of when the user was last seen.
type LastSeenUA struct {
// When is the timestamp when the user was last online.
When time.Time
// UserAgent is the client UA of the last online access.
UserAgent string
}
// Subscription to a topic
type Subscription struct {
ObjHeader `bson:",inline"`
// User who has relationship with the topic
User string
// Topic subscribed to
Topic string
DeletedAt *time.Time `bson:",omitempty"`
// Values persisted through subscription soft-deletion
// ID of the latest Soft-delete operation
DelId int
// Last SeqId reported by user as received by at least one of his sessions
RecvSeqId int
// Last SeqID reported read by the user
ReadSeqId int
// Access mode requested by this user
ModeWant AccessMode
// Access mode granted to this user
ModeGiven AccessMode
// User's private data associated with the subscription to topic
Private interface{}
// Deserialized ephemeral values
// Deserialized public value from topic or user (depends on context)
// In case of P2P topics this is the Public value of the other user.
public interface{}
// In case of P2P topics this is the Trusted value of the other user.
trusted interface{}
// deserialized SeqID from user or topic
seqId int
// Deserialized TouchedAt from topic
touchedAt time.Time
// Timestamp & user agent of when the user was last online.
lastSeenUA *LastSeenUA
// P2P only. ID of the other user
with string
// P2P only. Default access: this is the mode given by the other user to this user
modeDefault *DefaultAccess
// Topic's or user's state.
state ObjState
}
// SetPublic assigns a value to `public`, otherwise not accessible from outside the package.
func (s *Subscription) SetPublic(pub interface{}) {
s.public = pub
}
// GetPublic reads value of `public`.
func (s *Subscription) GetPublic() interface{} {
return s.public
}
// SetTrusted assigns a value to `trusted`, otherwise not accessible from outside the package.
func (s *Subscription) SetTrusted(tstd interface{}) {
s.trusted = tstd
}
// GetTrusted reads value of `trusted`.
func (s *Subscription) GetTrusted() interface{} {
return s.trusted
}
// SetWith sets other user for P2P subscriptions.
func (s *Subscription) SetWith(with string) {
s.with = with
}
// GetWith returns the other user for P2P subscriptions.
func (s *Subscription) GetWith() string {
return s.with
}
// GetTouchedAt returns touchedAt.
func (s *Subscription) GetTouchedAt() time.Time {
return s.touchedAt
}
// SetTouchedAt sets the value of touchedAt.
func (s *Subscription) SetTouchedAt(touchedAt time.Time) {
if touchedAt.After(s.touchedAt) {
s.touchedAt = touchedAt
}
}
// LastModified returns the greater of either TouchedAt or UpdatedAt.
func (s *Subscription) LastModified() time.Time {
if s.UpdatedAt.Before(s.touchedAt) {
return s.touchedAt
}
return s.UpdatedAt
}
// GetSeqId returns seqId.
func (s *Subscription) GetSeqId() int {
return s.seqId
}
// SetSeqId sets seqId field.
func (s *Subscription) SetSeqId(id int) {
s.seqId = id
}
// GetLastSeen returns lastSeen.
func (s *Subscription) GetLastSeen() *time.Time {
if s.lastSeenUA != nil {
return &s.lastSeenUA.When
}
return nil