/
pres.go
502 lines (425 loc) · 15.1 KB
/
pres.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
package main
import (
"log"
"strings"
"github.com/tinode/chat/server/store"
"github.com/tinode/chat/server/store/types"
)
// presParams defines parameters for creating a presence notification.
type presParams struct {
userAgent string
seqID int
delID int
delSeq []MsgDelRange
// Uid who performed the action
actor string
// Subject of the action
target string
dWant string
dGiven string
}
type presFilters struct {
// Send messages only to users with this access mode being non-zero.
filterIn types.AccessMode
// Exclude users with this access mode being non-zero.
filterOut types.AccessMode
// Send messages to the sessions of this single user defined by ID as a string 'usrABC'.
singleUser string
// Do not send messages to sessions of this user defined by ID as a string 'usrABC'.
excludeUser string
}
func (p *presParams) packAcs() *MsgAccessMode {
if p.dWant != "" || p.dGiven != "" {
return &MsgAccessMode{Want: p.dWant, Given: p.dGiven}
}
return nil
}
// Presence: Add another user to the list of contacts to notify of presence and other changes
func (t *Topic) addToPerSubs(topic string, online, enabled bool) {
if topic == t.name {
// No need to push updates to self
return
}
if uid1, uid2, err := types.ParseP2P(topic); err == nil {
// If this is a P2P topic, index it by second user's ID
if uid1.UserId() == t.name {
topic = uid2.UserId()
} else {
topic = uid1.UserId()
}
}
t.perSubs[topic] = perSubsData{online: online, enabled: enabled}
}
// loadContacts initializes topic.perSubs to support presence notifications.
// perSubs contains (a) topics that the user wants to notify of his presence and
// (b) those which want to receive notifications from this user.
func (t *Topic) loadContacts(uid types.Uid) error {
subs, err := store.Users.GetSubs(uid, nil)
if err != nil {
return err
}
t.perSubs = make(map[string]perSubsData, len(subs))
for i := range subs {
//log.Printf("Pres loadContacts: topic[%s]: processing sub '%s'", t.name, sub.Topic)
t.addToPerSubs(subs[i].Topic, false, (subs[i].ModeGiven & subs[i].ModeWant).IsPresencer())
}
//log.Printf("Pres loadContacts: topic[%s]: total cached %d", t.name, len(t.perSubs))
return nil
}
// This topic got a request from a 'me' topic to start/stop sending presence updates.
// The originating topic reports its own status in 'what' as "on", "off", "gone" or "?unkn".
// "on" - requester came online
// "off" - requester is offline now
// "?none" - requester status is unknown, but don't request a response and don't forward to clients.
// "gone" - topic deleted or otherwise gone - equivalent of "off+remove"
// "?unkn" - requester wants to initiate online status exchange but it's own status is unknown yet. This
// notifications is not forwarded to users.
//
// If status is followed by command "+en" then the current user should accept incoming notifications
// from the user2; "+rem" means the subscription is removed. "+dis" is the opposite of "en".
// The "+en/rem/dis" command itself is stripped from the notification.
func (t *Topic) presProcReq(fromUserID, what string, wantReply bool) string {
var reqReply, onlineUpdate bool
online := &onlineUpdate
replyAs := "on"
//log.Printf("presProcReq: topic[%s]: req from='%s', what=%s, wantReply=%v",
// t.name, fromUserID, what, wantReply)
parts := strings.Split(what, "+")
what = parts[0]
cmd := ""
if len(parts) > 1 {
cmd = parts[1]
}
switch what {
case "on":
// online
*online = true
case "off":
// offline
case "?none":
// no change to online status
online = nil
what = ""
case "gone":
// offline
cmd = "rem"
case "?unkn":
// offline
reqReply = true
what = ""
default:
// All other notifications are not processed here
// log.Println("done processing what=", what)
return what
}
//log.Printf("presProcReq: topic[%s]: req from='%s', what-now=%s, cmd=%s, reqReply(?unkn)=%v",
// t.name, fromUserID, what, cmd, reqReply)
if t.cat == types.TopicCatMe {
// Find if the contact is listed.
if psd, ok := t.perSubs[fromUserID]; ok {
//log.Printf("presProcReq: topic[%s]: requester %s in list; enabled=%v, online=%v",
// t.name, fromUserID, psd.enabled, psd.online)
if cmd == "rem" {
replyAs = "off+rem"
if !psd.enabled {
// If it was disabled before, don't send a redundunt update.
what = ""
}
delete(t.perSubs, fromUserID)
} else {
switch cmd {
case "":
// No change in being enabled or disabled and not being added or removed.
if !psd.enabled || online == nil || psd.online == *online {
// Not enabled or no change in online status - remove unnecessary notification.
what = ""
}
case "en":
if !psd.enabled {
psd.enabled = true
} else if online == nil || psd.online == *online {
// Was active and no change or online before: skip unnecessary update.
what = ""
}
case "dis":
if psd.enabled {
psd.enabled = false
if !psd.online {
what = ""
}
} else {
// Was disabled and consequently offline before, still offline - skip the update.
what = ""
}
default:
panic("presProcReq: unknown command '" + cmd + "'")
}
if online != nil {
psd.online = *online
}
t.perSubs[fromUserID] = psd
}
} else if cmd != "rem" {
//log.Printf("presProcReq: topic[%s]: requester %s NOT in list, adding, online=%v, cmd='%s'",
// t.name, fromUserID, online, cmd)
// Got request from a new topic. This must be a new subscription. Record it.
// If it's unknown, recording it as offline.
t.addToPerSubs(fromUserID, onlineUpdate, cmd == "en")
if cmd != "en" {
// If the connection is not enabled, ignore the update.
what = ""
}
} else {
// Not in list and asked to be removed from the list - ignore
what = ""
}
}
// If requester's online status has not changed, do not reply, otherwise an endless loop will happen.
// wantReply is needed to ensure unnecessary {pres} is not sent:
// A[online, B:off] to B[online, A:off]: {pres A on}
// B[online, A:on] to A[online, B:off]: {pres B on}
// A[online, B:on] to B[online, A:on]: {pres A on} <<-- unnecessary, that's why wantReply is needed
if (onlineUpdate || reqReply) && wantReply {
globals.hub.route <- &ServerComMessage{
// Topic is 'me' even for group topics; group topics will use 'me' as a signal to drop the message
// without forwarding to sessions
Pres: &MsgServerPres{Topic: "me", What: replyAs, Src: t.name, wantReply: reqReply},
rcptto: fromUserID}
// log.Printf("presProcReq: topic[%s]: replying to %s with own status='%s', wantReply=%v",
// t.name, fromUserID, replyAs, reqReply)
}
//log.Println("what is '", what, "'")
return what
}
// Publish user's update to his/her users of interest on their 'me' topic
// Case A: user came online, "on", ua
// Case B: user went offline, "off", ua
// Case C: user agent change, "ua", ua
// Case D: User updated 'public', "upd"
func (t *Topic) presUsersOfInterest(what, ua string) {
// Push update to subscriptions
for topic := range t.perSubs {
globals.hub.route <- &ServerComMessage{
Pres: &MsgServerPres{
Topic: "me", What: what, Src: t.name, UserAgent: ua, wantReply: (what == "on")},
rcptto: topic}
// log.Printf("Pres A, B, C, D: User'%s' to '%s' what='%s', ua='%s'", t.name, topic, what, ua)
}
}
func (t *Topic) presEnableUser() {
if t.cat == types.TopicCatP2P {
}
}
// Report change to topic subscribers online, group or p2p
//
// Case I: User joined the topic, "on"
// Case J: User left topic, "off"
// Case K.2: User altered WANT (and maybe got default Given), "acs"
// Case L.1: Admin altered GIVEN, "acs" to affected user
// Case L.3: Admin altered GIVEN (and maybe got assigned default WANT), "acs" to admins
// Case M: Topic unaccessible (cluster failure), "left" to everyone currently online
// Case V.2: Messages soft deleted, "del" to one user only
// Case W.2: Messages hard-deleted, "del"
func (t *Topic) presSubsOnline(what, src string, params *presParams,
pf *presFilters, skipSid string) {
// If affected user is the same as the user making the change, clear 'who'
actor := params.actor
target := params.target
if actor == src {
actor = ""
}
if target == src {
target = ""
}
globals.hub.route <- &ServerComMessage{
Pres: &MsgServerPres{Topic: t.xoriginal, What: what, Src: src,
Acs: params.packAcs(), AcsActor: actor, AcsTarget: target,
SeqId: params.seqID, DelId: params.delID, DelSeq: params.delSeq,
filterIn: int(pf.filterIn), filterOut: int(pf.filterOut),
singleUser: pf.singleUser, excludeUser: pf.excludeUser},
rcptto: t.name, skipSid: skipSid}
// log.Printf("Pres K.2, L.3, W.2: topic'%s' what='%s', who='%s', acs='w:%s/g:%s'", t.name, what,
// params.who, params.dWant, params.dGiven)
}
// Send presence notification to attached sessions directly, without routing though topic.
func (t *Topic) presSubsOnlineDirect(what string) {
msg := &ServerComMessage{Pres: &MsgServerPres{Topic: t.xoriginal, What: what}}
for sess := range t.sessions {
// Check presence filters
pud, _ := t.perUser[sess.uid]
if !(pud.modeGiven & pud.modeWant).IsPresencer() {
continue
}
if t.cat == types.TopicCatP2P {
// For p2p topics topic name is dependent on receiver.
// It's OK to change the pointer here because the message will be serialized in queueOut
// before being placed into channel.
msg.Pres.Topic = t.original(sess.uid)
}
sess.queueOut(msg)
}
}
// Publish to topic subscribers's sessions currently offline in the topic, on their 'me'
// Group and P2P.
// Case E: topic came online, "on"
// Case F: topic went offline, "off"
// Case G: topic updated 'public', "upd", who
// Case H: topic deleted, "gone"
// Case K.3: user altered WANT, "acs" to admins
// Case L.4: Admin altered GIVEN, "acs" to admins
// Case T: message sent, "msg" to all with 'R'
// Case W.1: messages hard-deleted, "del" to all with 'R'
func (t *Topic) presSubsOffline(what string, params *presParams, filter *presFilters,
skipSid string, offlineOnly bool) {
var skipTopic string
if offlineOnly {
skipTopic = t.name
}
//log.Printf("presSubsOffline: topic'%s' what='%s', who='%v'", t.name, what, params)
for uid := range t.perUser {
if what != "acs" && !presOfflineFilter(t.perUser[uid].modeGiven&t.perUser[uid].modeWant, filter) {
continue
}
user := uid.UserId()
actor := params.actor
target := params.target
if actor == user {
actor = ""
}
if target == user {
target = ""
}
globals.hub.route <- &ServerComMessage{
Pres: &MsgServerPres{Topic: "me", What: what, Src: t.original(uid),
Acs: params.packAcs(), AcsActor: actor, AcsTarget: target,
SeqId: params.seqID, DelId: params.delID,
skipTopic: skipTopic},
rcptto: user, skipSid: skipSid}
}
}
// Same as presSubsOffline, but the topic has not been loaded/initialized first: offline topic, offline subscribers
func presSubsOfflineOffline(topic string, cat types.TopicCat, subs []types.Subscription, what string,
params *presParams, skipSid string) {
var count = 0
original := topic
for i := range subs {
sub := &subs[i]
if what != "acs" && !presOfflineFilter(sub.ModeWant&sub.ModeGiven, nil) {
continue
}
if cat == types.TopicCatP2P {
original = types.ParseUid(subs[(count+1)%2].User).UserId()
count++
}
user := types.ParseUid(sub.User).UserId()
actor := params.actor
target := params.target
if actor == user {
actor = ""
}
if target == user {
target = ""
}
globals.hub.route <- &ServerComMessage{
Pres: &MsgServerPres{Topic: "me", What: what, Src: original,
Acs: params.packAcs(), AcsActor: actor, AcsTarget: target,
SeqId: params.seqID, DelId: params.delID},
rcptto: user, skipSid: skipSid}
}
}
// Announce to a single user on 'me' topic
//
// Case K.1: User altered WANT (includes new subscription, deleted subscription)
// Case L.2: Sharer altered GIVEN (inludes invite, eviction)
// Case U: read/recv notification
// Case V.1: messages soft-deleted
func (t *Topic) presSingleUserOffline(uid types.Uid, what string, params *presParams, skipSid string, offlineOnly bool) {
var skipTopic string
if offlineOnly {
skipTopic = t.name
}
if pud, ok := t.perUser[uid]; ok &&
// Send access change notification regardless of P permission.
(what == "acs" || presOfflineFilter(pud.modeGiven&pud.modeWant, nil)) {
user := uid.UserId()
actor := params.actor
target := params.target
if actor == user {
actor = ""
}
if target == user {
target = ""
}
globals.hub.route <- &ServerComMessage{
Pres: &MsgServerPres{Topic: "me", What: what,
Src: t.original(uid), SeqId: params.seqID, DelId: params.delID,
Acs: params.packAcs(), AcsActor: actor, AcsTarget: target, UserAgent: params.userAgent,
wantReply: strings.HasPrefix(what, "?unkn"), skipTopic: skipTopic},
rcptto: user, skipSid: skipSid}
}
// log.Printf("Pres J.1, K, M.1, N: topic'%s' what='%s', who='%s'", t.name, what, who.UserId())
}
// Same as above, but the topic is offline (not loaded from the DB)
func presSingleUserOfflineOffline(uid types.Uid, original, what string, params *presParams, skipSid string) {
user := uid.UserId()
actor := params.actor
target := params.target
if actor == user {
actor = ""
}
if target == user {
target = ""
}
globals.hub.route <- &ServerComMessage{
Pres: &MsgServerPres{Topic: "me", What: what,
Src: original, SeqId: params.seqID, DelId: params.delID,
Acs: params.packAcs(), AcsActor: actor, AcsTarget: target},
rcptto: uid.UserId(), skipSid: skipSid}
}
// Let other sessions of a given user know what messages are now received/read
// Cases U
func (t *Topic) presPubMessageCount(uid types.Uid, recv, read int, skip string) {
var what string
var seq int
if read > 0 {
what = "read"
seq = read
} else if recv > 0 {
what = "recv"
seq = recv
}
if what != "" {
// Announce to user's other sessions on 'me' only if they are not attached to this topic.
// Attached topics will receive an {info}
t.presSingleUserOffline(uid, what, &presParams{seqID: seq}, skip, true)
}
}
// Let other sessions of a given user know that messages are now deleted
// Cases V.1, V.2
func (t *Topic) presPubMessageDelete(uid types.Uid, delID int, list []MsgDelRange, skip string) {
if len(list) == 0 && delID <= 0 {
log.Printf("Case V.1, V.2: topic[%s] invalid request - missing payload", t.name)
return
}
// This check is only needed for V.1, but it does not hurt V.2. Let's do it here for both.
pud, _ := t.perUser[uid]
if !(pud.modeGiven & pud.modeWant).IsPresencer() {
return
}
params := &presParams{delID: delID, delSeq: list}
// Case V.2
user := uid.UserId()
t.presSubsOnline("del", user, params, &presFilters{singleUser: user}, skip)
// Case V.1
t.presSingleUserOffline(uid, "del", params, skip, true)
}
// Filter by permissions: mode.IsPresencer() AND mode has at least some
// bits specified in 'filter' (or filter is ModeNone).
//
// Filtering must happen here because receiving 'me' has no access to sender's permissions.
func presOfflineFilter(mode types.AccessMode, pf *presFilters) bool {
return mode.IsPresencer() &&
(pf == nil ||
((pf.filterIn == types.ModeNone || mode&pf.filterIn != 0) &&
(pf.filterOut == types.ModeNone || mode&pf.filterOut == 0)))
}