-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathMeTopic.swift
404 lines (357 loc) · 14.2 KB
/
MeTopic.swift
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
//
// MeTopic.swift
// TinodeSDK
//
// Copyright © 2020-2022 Tinode LLC. All rights reserved.
//
import Foundation
public protocol MeTopicProto: TopicProto {
var creds: [Credential]? { get set }
func serializeCreds() -> String?
@discardableResult
func deserializeCreds(from data: String?) -> Bool
}
open class MeTopic<DP: Codable & Mergeable>: Topic<DP, PrivateType, DP, PrivateType>, MeTopicProto {
open class Listener: Topic<DP, PrivateType, DP, PrivateType>.Listener {
// Called when user credentials are updated.
open func onCredUpdated(cred: [Credential]?) {}
}
open class MetaGetBuilder: Topic<DP, PrivateType, DP, PrivateType>.MetaGetBuilder {
public func withCred() -> MetaGetBuilder {
meta.setCred()
return self
}
}
private var credentials: [Credential]?
public init(tinode: Tinode?, l: MeTopic<DP>.Listener? = nil) {
super.init(tinode: tinode, name: Tinode.kTopicMe, l: l)
}
public init(tinode: Tinode?, desc: Description<DP, PrivateType>) {
super.init(tinode: tinode, name: Tinode.kTopicMe, desc: desc)
}
public func serializeCreds() -> String? {
guard let c = self.creds else { return nil }
return Tinode.serializeObject(c)
}
public func deserializeCreds(from data: String?) -> Bool {
if let c: [Credential] = Tinode.deserializeObject(from: data) {
self.creds = c
return true
}
return false
}
override public func metaGetBuilder() -> MetaGetBuilder {
return MetaGetBuilder(parent: self)
}
override public var subsUpdated: Date? {
return tinode?.topicsUpdated
}
override func loadSubs() -> Int {
// Don't attempt to load subscriptions: 'me' subscriptions are stored as topics.
return 0
}
public var creds: [Credential]? {
get { return credentials }
set {
if let c = newValue {
credentials = c.sorted(by: <)
} else {
credentials = nil
}
}
}
public func delCredential(meth: String, val: String) -> PromisedReply<ServerMessage> {
return delCredential(Credential(meth: meth, val: val))
}
public func delCredential(_ cred: Credential) -> PromisedReply<ServerMessage> {
let tnd = tinode!
return tnd.delCredential(cred: cred)
.thenApply { [weak self] _ in
guard let me = self else { return nil }
let idx = me.findCredIndex(cred: cred, anyUnconfirmed: false)
if idx >= 0 {
me.credentials?.remove(at: idx)
// No need to sort.
me.store?.topicUpdate(topic: me)
// Notify listeners
(me.listener as! Listener).onCredUpdated(cred: me.creds)
}
return nil
}
}
public func confirmCred(meth: String, response: String) ->PromisedReply<ServerMessage> {
let cred = Credential(meth: meth, val: nil, resp: response, params: nil)
return setMeta(meta: MsgSetMeta(desc: nil, sub: nil, tags: nil, cred: cred))
}
private func findCredIndex(cred other: Credential, anyUnconfirmed: Bool) -> Int {
guard let creds = creds else { return -1 }
return creds.firstIndex {
$0.meth == other.meth && ((anyUnconfirmed && !$0.isDone) || $0.val == other.val)
} ?? -1
}
override public func topicLeft(unsub: Bool?, code: Int?, reason: String?) {
super.topicLeft(unsub: unsub, code: code, reason: reason)
if let topics = tinode?.getTopics() {
for t in topics {
t.online = false
}
}
}
override public func updateMode(update: String) -> PromisedReply<ServerMessage> {
var acs = accessMode
if acs == nil {
acs = Acs()
}
let mode = AcsHelper(ah: acs!.want)
if mode.update(from: update) {
return setSubscription(sub: MetaSetSub(user: nil, mode: mode.description))
}
// The state is unchanged, return resolved promise.
return PromisedReply<ServerMessage>(value: ServerMessage())
}
override internal func update(acsMap: [String: String]?, sub: MetaSetSub) {
var newAcs: Acs
if let acsMap = acsMap {
newAcs = Acs(from: acsMap)
} else {
newAcs = Acs()
newAcs.want = AcsHelper(str: sub.mode)
}
var changed = false
var acs = self.accessMode
if acs == nil {
acs = newAcs
changed = true
} else {
changed = acs!.merge(from: newAcs)
}
if changed {
self.accessMode = acs
self.store?.topicUpdate(topic: self)
}
}
override internal func update(ctrl: MsgServerCtrl, meta: MsgSetMeta<DP, PrivateType>) {
super.update(ctrl: ctrl, meta: meta)
if let cred = meta.cred {
routeMetaCred(cred: cred)
(listener as? MeTopic.Listener)?.onCredUpdated(cred: [cred])
}
}
public func setMsgReadRecv(from topicName: String?, what: String?, seq: Int?) {
guard let tn = topicName, let topic = tinode?.getTopic(topicName: tn), let seq = seq else { return }
if seq > 0 {
switch what {
case Tinode.kNoteRecv:
assignRecv(to: topic, recv: seq)
case Tinode.kNoteRead:
assignRead(to: topic, read: seq)
default:
break
}
}
}
override public func routeInfo(info: MsgServerInfo) {
guard let what = info.what, what != Tinode.kNoteKp, let src = info.src else { return }
if let t = tinode!.getTopic(topicName: src) as? DefaultTopic {
t.setReadRecvByRemote(from: info.from, what: what, seq: info.seq)
}
// If this is an update from the current user, update the contact with the new count too.
if tinode!.isMe(uid: info.from) {
setMsgReadRecv(from: info.src, what: what, seq: info.seq)
}
listener?.onInfo(info: info)
}
override public func routeMeta(meta: MsgServerMeta) {
if let cred = meta.cred {
routeMetaCred(cred: cred)
}
super.routeMeta(meta: meta)
}
override public func routePres(pres: MsgServerPres) {
let what = MsgServerPres.parseWhat(what: pres.what)
if what == .kTerm {
// The 'me' topic itself is detached. Mark as unsubscribed.
super.routePres(pres: pres)
return
}
if what == .kUpd {
if Tinode.kTopicMe == pres.src {
// Me's desc was updated, fetch the updated version.
getMeta(query: metaGetBuilder().withDesc().build())
} else {
// pub/priv updated: fetch subscription update.
getMeta(query: metaGetBuilder().withSub(userOrTopic: pres.src).build())
}
return
}
// "what":"tags" may have src == nil
if let topic = tinode!.getTopic(topicName: pres.src ?? "") {
switch what {
case .kOn: // topic came online
topic.online = true
case .kOff: // topic went offline
topic.online = false
topic.lastSeen = LastSeen(when: Date(), ua: nil)
case .kMsg: // new message received
topic.setSeqAndFetch(newSeq: pres.seq)
if pres.act == nil || tinode!.isMe(uid: pres.act!) {
assignRead(to: topic, read: pres.seq)
}
topic.touched = Date()
case .kAcs: // access mode changed
if pres.tgt == nil && topic.updateAccessMode(ac: pres.dacs) {
self.store?.topicUpdate(topic: topic)
}
case .kUa: // user agent changed
topic.lastSeen = LastSeen(when: Date(), ua: pres.ua)
case .kRecv: // user's other session marked some messages as received
assignRecv(to: topic, recv: pres.seq)
case .kRead: // user's other session marked some messages as read
assignRead(to: topic, read: pres.seq)
case .kGone:
if topic.deleted {
// Alredy deleted locally: clear from DB completely.
topic.expunge(hard: true)
tinode!.stopTrackingTopic(topicName: pres.src!)
} else {
// Mark as deleted.
topic.expunge(hard: false)
}
case .kDel: // messages deleted
// Explicitly ignored: 'me' topic has no messages.
break
default:
Tinode.log.error("ME.pres message - unknown what: %@", String(describing: pres.what))
}
} else {
// nil (me) or a previously unknown topic
switch what {
case .kAcs:
if pres.src != nil && pres.src != Tinode.kTopicMe {
let acs = Acs()
acs.update(from: pres.dacs)
if acs.isModeDefined {
getMeta(query: metaGetBuilder().withSub(userOrTopic: pres.src).build())
} else {
Tinode.log.error("ME.acs - unexpected access mode: %@", String(describing: pres.dacs))
}
}
case .kTags:
// Account tags updated
getMeta(query: metaGetBuilder().withTags().build())
default:
Tinode.log.error("ME.pres - topic not found: what = %@, src = %@",
String(describing: pres.what), String(describing: pres.src))
}
}
if what == MsgServerPres.What.kGone {
listener?.onSubsUpdated()
}
listener?.onPres(pres: pres)
}
fileprivate func assignRecv(to topic: TopicProto, recv seq: Int?) {
if (topic.recv ?? -1) < (seq ?? -1) {
topic.recv = seq
self.store?.setRecv(topic: topic, recv: seq!)
}
}
fileprivate func assignRead(to topic: TopicProto, read seq: Int?) {
if (topic.read ?? -1) < (seq ?? -1) {
topic.read = seq
self.store?.setRead(topic: topic, read: topic.read!)
assignRecv(to: topic, recv: topic.read)
}
}
override internal func routeMetaSub(meta: MsgServerMeta) {
if let metaSubs = meta.sub as? [Subscription<DP, PrivateType>] {
for sub in metaSubs {
if let topic = tinode!.getTopic(topicName: sub.topic!) {
if sub.deleted != nil {
if topic.deleted {
topic.expunge(hard: true)
tinode!.stopTrackingTopic(topicName: sub.topic!)
} else {
topic.expunge(hard: false)
}
} else {
if let t = topic as? DefaultTopic {
t.update(sub: sub as! Subscription<TheCard, PrivateType>)
} else if let t = topic as? DefaultMeTopic {
t.update(sub: sub as! Subscription<TheCard, PrivateType>)
} else {
Tinode.log.fault("ME.routeMetaSub - failed to update topic %@", String(describing: topic))
assert(false)
}
}
} else if sub.deleted == nil {
// This is a new topic. Register it and write to DB.
let topic = tinode!.newTopic(sub: sub)
topic.persist()
}
listener?.onMetaSub(sub: sub)
}
}
listener?.onSubsUpdated()
}
private func processOneCred(_ cred: Credential) {
guard cred.meth != nil else { return }
var changed = false
if cred.val != nil {
if creds == nil {
// Empty list. Create list with one new element.
credentials = [cred]
changed = true
} else {
// Try finding this credential among confirmed or not.
var idx = findCredIndex(cred: cred, anyUnconfirmed: false)
if idx < 0 {
// Not found.
if !cred.isDone {
// Unconfirmed credential replaces previous unconfirmed credential of the same method.
idx = findCredIndex(cred: cred, anyUnconfirmed: true)
if idx >= 0 {
// Remove previous unconfirmed credential.
credentials!.remove(at: idx)
}
}
credentials!.append(cred)
} else {
// Found. Maybe change 'done' status.
credentials?[idx].done = cred.isDone
}
changed = true
}
} else if cred.resp != nil && credentials != nil {
// Handle credential confirmation.
let idx = findCredIndex(cred: cred, anyUnconfirmed: true)
if idx >= 0 {
credentials?[idx].done = true
changed = true
}
}
if changed {
// Ensure predictable order.
credentials?.sort(by: <)
store?.topicUpdate(topic: self)
}
}
internal func routeMetaCred(cred: Credential) {
processOneCred(cred)
(listener as? Listener)?.onCredUpdated(cred: creds)
}
internal func routeMetaCred(cred: [Credential]) {
var newCreds: [Credential] = []
for c in cred {
if c.meth != nil && c.val != nil {
newCreds.append(c)
}
}
// Ensure predictable order of credentials.
newCreds.sort(by: <)
credentials = newCreds
// Save update to DB.
store?.topicUpdate(topic: self)
// Notify listeners.
(listener as? Listener)?.onCredUpdated(cred: creds)
}
}