-
Notifications
You must be signed in to change notification settings - Fork 21
/
XMTPModule.swift
1291 lines (1096 loc) · 47.2 KB
/
XMTPModule.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
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
import ExpoModulesCore
import XMTP
import LibXMTP
extension Conversation {
static func cacheKeyForTopic(clientAddress: String, topic: String) -> String {
return "\(clientAddress):\(topic)"
}
func cacheKey(_ clientAddress: String) -> String {
return Conversation.cacheKeyForTopic(clientAddress: clientAddress, topic: topic)
}
}
extension XMTP.Group {
static func cacheKeyForId(clientAddress: String, id: String) -> String {
return "\(clientAddress):\(id)"
}
func cacheKey(_ clientAddress: String) -> String {
return XMTP.Group.cacheKeyForId(clientAddress: clientAddress, id: id.toHex)
}
}
actor IsolatedManager<T> {
private var map: [String: T] = [:]
func set(_ key: String, _ object: T) {
map[key] = object
}
func get(_ key: String) -> T? {
map[key]
}
}
public class XMTPModule: Module {
var signer: ReactNativeSigner?
let clientsManager = ClientsManager()
let conversationsManager = IsolatedManager<Conversation>()
let groupsManager = IsolatedManager<XMTP.Group>()
let subscriptionsManager = IsolatedManager<Task<Void, Never>>()
private var preEnableIdentityCallbackDeferred: DispatchSemaphore?
private var preCreateIdentityCallbackDeferred: DispatchSemaphore?
actor ClientsManager {
private var clients: [String: XMTP.Client] = [:]
// A method to update the conversations
func updateClient(key: String, client: XMTP.Client) {
ContentJson.initCodecs(client: client)
clients[key] = client
}
// A method to retrieve a conversation
func getClient(key: String) -> XMTP.Client? {
return clients[key]
}
}
enum Error: Swift.Error {
case noClient, conversationNotFound(String), noMessage, invalidKeyBundle, invalidDigest, badPreparation(String), mlsNotEnabled(String), invalidString
}
public func definition() -> ModuleDefinition {
Name("XMTP")
Events(
// Auth
"sign",
"authed",
"preCreateIdentityCallback",
"preEnableIdentityCallback",
// Conversations
"conversation",
"group",
"conversationContainer",
"message",
"allGroupMessage",
// Conversation
"conversationMessage",
// Group
"groupMessage"
)
AsyncFunction("address") { (clientAddress: String) -> String in
if let client = await clientsManager.getClient(key: clientAddress) {
return client.address
} else {
return "No Client."
}
}
AsyncFunction("deleteLocalDatabase") { (clientAddress: String) in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
try client.deleteLocalDatabase()
}
//
// Auth functions
//
AsyncFunction("auth") { (address: String, environment: String, appVersion: String?, hasCreateIdentityCallback: Bool?, hasEnableIdentityCallback: Bool?, enableAlphaMls: Bool?, dbEncryptionKey: [UInt8]?, dbPath: String?) in
try requireNotProductionEnvForAlphaMLS(enableAlphaMls: enableAlphaMls, environment: environment)
let signer = ReactNativeSigner(module: self, address: address)
self.signer = signer
if(hasCreateIdentityCallback ?? false) {
preCreateIdentityCallbackDeferred = DispatchSemaphore(value: 0)
}
if(hasEnableIdentityCallback ?? false) {
preEnableIdentityCallbackDeferred = DispatchSemaphore(value: 0)
}
let preCreateIdentityCallback: PreEventCallback? = hasCreateIdentityCallback ?? false ? self.preCreateIdentityCallback : nil
let preEnableIdentityCallback: PreEventCallback? = hasEnableIdentityCallback ?? false ? self.preEnableIdentityCallback : nil
let encryptionKeyData = dbEncryptionKey == nil ? nil : Data(dbEncryptionKey!)
let options = createClientConfig(env: environment, appVersion: appVersion, preEnableIdentityCallback: preEnableIdentityCallback, preCreateIdentityCallback: preCreateIdentityCallback, mlsAlpha: enableAlphaMls == true, encryptionKey: encryptionKeyData, dbPath: dbPath)
try await clientsManager.updateClient(key: address, client: await XMTP.Client.create(account: signer, options: options))
self.signer = nil
sendEvent("authed")
}
Function("receiveSignature") { (requestID: String, signature: String) in
try signer?.handle(id: requestID, signature: signature)
}
// Generate a random wallet and set the client to that
AsyncFunction("createRandom") { (environment: String, appVersion: String?, hasCreateIdentityCallback: Bool?, hasEnableIdentityCallback: Bool?, enableAlphaMls: Bool?, dbEncryptionKey: [UInt8]?, dbPath: String?) -> String in
try requireNotProductionEnvForAlphaMLS(enableAlphaMls: enableAlphaMls, environment: environment)
let privateKey = try PrivateKey.generate()
if(hasCreateIdentityCallback ?? false) {
preCreateIdentityCallbackDeferred = DispatchSemaphore(value: 0)
}
if(hasEnableIdentityCallback ?? false) {
preEnableIdentityCallbackDeferred = DispatchSemaphore(value: 0)
}
let preCreateIdentityCallback: PreEventCallback? = hasCreateIdentityCallback ?? false ? self.preCreateIdentityCallback : nil
let preEnableIdentityCallback: PreEventCallback? = hasEnableIdentityCallback ?? false ? self.preEnableIdentityCallback : nil
let encryptionKeyData = dbEncryptionKey == nil ? nil : Data(dbEncryptionKey!)
let options = createClientConfig(env: environment, appVersion: appVersion, preEnableIdentityCallback: preEnableIdentityCallback, preCreateIdentityCallback: preCreateIdentityCallback, mlsAlpha: enableAlphaMls == true, encryptionKey: encryptionKeyData, dbPath: dbPath)
let client = try await Client.create(account: privateKey, options: options)
await clientsManager.updateClient(key: client.address, client: client)
return client.address
}
// Create a client using its serialized key bundle.
AsyncFunction("createFromKeyBundle") { (keyBundle: String, environment: String, appVersion: String?, enableAlphaMls: Bool?, dbEncryptionKey: [UInt8]?, dbPath: String?) -> String in
try requireNotProductionEnvForAlphaMLS(enableAlphaMls: enableAlphaMls, environment: environment)
do {
guard let keyBundleData = Data(base64Encoded: keyBundle),
let bundle = try? PrivateKeyBundle(serializedData: keyBundleData)
else {
throw Error.invalidKeyBundle
}
let encryptionKeyData = dbEncryptionKey == nil ? nil : Data(dbEncryptionKey!)
let options = createClientConfig(env: environment, appVersion: appVersion, mlsAlpha: enableAlphaMls == true, encryptionKey: encryptionKeyData, dbPath: dbPath)
let client = try await Client.from(bundle: bundle, options: options)
await clientsManager.updateClient(key: client.address, client: client)
return client.address
} catch {
print("ERRO! Failed to create client: \(error)")
throw error
}
}
AsyncFunction("sign") { (clientAddress: String, digest: [UInt8], keyType: String, preKeyIndex: Int) -> [UInt8] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let privateKeyBundle = client.keys
let key = keyType == "prekey" ? privateKeyBundle.preKeys[preKeyIndex] : privateKeyBundle.identityKey
let privateKey = try PrivateKey(key)
let signature = try await privateKey.sign(Data(digest))
let uint = try [UInt8](signature.serializedData())
return uint
}
AsyncFunction("exportPublicKeyBundle") { (clientAddress: String) -> [UInt8] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let bundle = try client.publicKeyBundle.serializedData()
return Array(bundle)
}
// Export the client's serialized key bundle.
AsyncFunction("exportKeyBundle") { (clientAddress: String) -> String in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let bundle = try client.privateKeyBundle.serializedData().base64EncodedString()
return bundle
}
// Export the conversation's serialized topic data.
AsyncFunction("exportConversationTopicData") { (clientAddress: String, topic: String) -> String in
guard let conversation = try await findConversation(clientAddress: clientAddress, topic: topic) else {
throw Error.conversationNotFound(topic)
}
return try conversation.toTopicData().serializedData().base64EncodedString()
}
AsyncFunction("getHmacKeys") { (clientAddress: String) -> [UInt8] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let hmacKeys = await client.conversations.getHmacKeys()
return try [UInt8](hmacKeys.serializedData())
}
// Import a conversation from its serialized topic data.
AsyncFunction("importConversationTopicData") { (clientAddress: String, topicData: String) -> String in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let data = try Xmtp_KeystoreApi_V1_TopicMap.TopicData(
serializedData: Data(base64Encoded: Data(topicData.utf8))!
)
let conversation = await client.conversations.importTopicData(data: data)
await conversationsManager.set(conversation.cacheKey(clientAddress), conversation)
return try ConversationWrapper.encode(conversation, client: client)
}
//
// Client API
AsyncFunction("canMessage") { (clientAddress: String, peerAddress: String) -> Bool in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
return try await client.canMessage(peerAddress)
}
AsyncFunction("canGroupMessage") { (clientAddress: String, peerAddresses: [String]) -> [String: Bool] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
return try await client.canMessageV3(addresses: peerAddresses)
}
AsyncFunction("staticCanMessage") { (peerAddress: String, environment: String, appVersion: String?) -> Bool in
do {
let options = createClientConfig(env: environment, appVersion: appVersion)
return try await XMTP.Client.canMessage(peerAddress, options: options)
} catch {
throw Error.noClient
}
}
AsyncFunction("encryptAttachment") { (clientAddress: String, fileJson: String) -> String in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let file = try DecryptedLocalAttachment.fromJson(fileJson)
let url = URL(string: file.fileUri)
let data = try Data(contentsOf: url!)
let attachment = Attachment(
filename: url!.lastPathComponent,
mimeType: file.mimeType,
data: data
)
let encrypted = try RemoteAttachment.encodeEncrypted(
content: attachment,
codec: AttachmentCodec(),
with: client
)
let encryptedFile = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try encrypted.payload.write(to: encryptedFile)
return try EncryptedLocalAttachment.from(
attachment: attachment,
encrypted: encrypted,
encryptedFile: encryptedFile
).toJson()
}
AsyncFunction("decryptAttachment") { (clientAddress: String, encryptedFileJson: String) -> String in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let encryptedFile = try EncryptedLocalAttachment.fromJson(encryptedFileJson)
let encryptedData = try Data(contentsOf: URL(string: encryptedFile.encryptedLocalFileUri)!)
let encrypted = EncryptedEncodedContent(
secret: encryptedFile.metadata.secret,
digest: encryptedFile.metadata.contentDigest,
salt: encryptedFile.metadata.salt,
nonce: encryptedFile.metadata.nonce,
payload: encryptedData
)
let encoded = try RemoteAttachment.decryptEncoded(encrypted: encrypted)
let attachment: Attachment = try encoded.decoded(with: client)
let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try attachment.data.write(to: file)
return try DecryptedLocalAttachment(
fileUri: file.absoluteString,
mimeType: attachment.mimeType,
filename: attachment.filename
).toJson()
}
AsyncFunction("sendEncodedContent") { (clientAddress: String, topic: String, encodedContentData: [UInt8]) -> String in
guard let conversation = try await findConversation(clientAddress: clientAddress, topic: topic) else {
throw Error.conversationNotFound("no conversation found for \(topic)")
}
let encodedContent = try EncodedContent(serializedData: Data(encodedContentData))
return try await conversation.send(encodedContent: encodedContent)
}
AsyncFunction("listConversations") { (clientAddress: String) -> [String] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let conversations = try await client.conversations.list()
return try await withThrowingTaskGroup(of: String.self) { group in
for conversation in conversations {
group.addTask {
await self.conversationsManager.set(conversation.cacheKey(clientAddress), conversation)
return try ConversationWrapper.encode(conversation, client: client)
}
}
var results: [String] = []
for try await result in group {
results.append(result)
}
return results
}
}
AsyncFunction("listGroups") { (clientAddress: String) -> [String] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let groupList = try await client.conversations.groups()
return try await withThrowingTaskGroup(of: String.self) { taskGroup in
for group in groupList {
taskGroup.addTask {
await self.groupsManager.set(group.cacheKey(clientAddress), group)
return try GroupWrapper.encode(group, client: client)
}
}
var results: [String] = []
for try await result in taskGroup {
results.append(result)
}
return results
}
}
AsyncFunction("listAll") { (clientAddress: String) -> [String] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let conversationContainerList = try await client.conversations.list(includeGroups: true)
return try await withThrowingTaskGroup(of: String.self) { taskGroup in
for conversation in conversationContainerList {
taskGroup.addTask {
await self.conversationsManager.set(conversation.cacheKey(clientAddress), conversation)
return try ConversationContainerWrapper.encode(conversation, client: client)
}
}
var results: [String] = []
for try await result in taskGroup {
results.append(result)
}
return results
}
}
AsyncFunction("loadMessages") { (clientAddress: String, topic: String, limit: Int?, before: Double?, after: Double?, direction: String?) -> [String] in
let beforeDate = before != nil ? Date(timeIntervalSince1970: TimeInterval(before!) / 1000) : nil
let afterDate = after != nil ? Date(timeIntervalSince1970: TimeInterval(after!) / 1000) : nil
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let conversation = try await findConversation(clientAddress: clientAddress, topic: topic) else {
throw Error.conversationNotFound("no conversation found for \(topic)")
}
let sortDirection: Int = (direction != nil && direction == "SORT_DIRECTION_ASCENDING") ? 1 : 2
let decryptedMessages = try await conversation.decryptedMessages(
limit: limit,
before: beforeDate,
after: afterDate,
direction: PagingInfoSortDirection(rawValue: sortDirection)
)
return decryptedMessages.compactMap { msg in
do {
return try DecodedMessageWrapper.encode(msg, client: client)
} catch {
print("discarding message, unable to encode wrapper \(msg.id)")
return nil
}
}
}
AsyncFunction("groupMessages") { (clientAddress: String, id: String, limit: Int?, before: Double?, after: Double?, direction: String?, deliveryStatus: String?) -> [String] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let beforeDate = before != nil ? Date(timeIntervalSince1970: TimeInterval(before!) / 1000) : nil
let afterDate = after != nil ? Date(timeIntervalSince1970: TimeInterval(after!) / 1000) : nil
let sortDirection: Int = (direction != nil && direction == "SORT_DIRECTION_ASCENDING") ? 1 : 2
let status: String = (deliveryStatus != nil) ? deliveryStatus!.lowercased() : "all"
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
let decryptedMessages = try await group.decryptedMessages(
before: beforeDate,
after: afterDate,
limit: limit,
direction: PagingInfoSortDirection(rawValue: sortDirection),
deliveryStatus: MessageDeliveryStatus(rawValue: status)
)
return decryptedMessages.compactMap { msg in
do {
return try DecodedMessageWrapper.encode(msg, client: client)
} catch {
print("discarding message, unable to encode wrapper \(msg.id)")
return nil
}
}
}
AsyncFunction("loadBatchMessages") { (clientAddress: String, topics: [String]) -> [String] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
var topicsList: [String: Pagination?] = [:]
topics.forEach { topicJSON in
let jsonData = topicJSON.data(using: .utf8)!
guard let jsonObj = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any],
let topic = jsonObj["topic"] as? String
else {
return // Skip this topic if it doesn't have valid JSON data or missing "topic" field
}
var limit: Int?
var before: Double?
var after: Double?
var direction: PagingInfoSortDirection = .descending
if let limitInt = jsonObj["limit"] as? Int {
limit = limitInt
}
if let beforeInt = jsonObj["before"] as? Double {
before = TimeInterval(beforeInt / 1000)
}
if let afterInt = jsonObj["after"] as? Double {
after = TimeInterval(afterInt / 1000)
}
if let directionStr = jsonObj["direction"] as? String {
let sortDirection: Int = (directionStr == "SORT_DIRECTION_ASCENDING") ? 1 : 2
direction = PagingInfoSortDirection(rawValue: sortDirection) ?? .descending
}
let page = Pagination(
limit: limit ?? nil,
before: before != nil && before! > 0 ? Date(timeIntervalSince1970: before!) : nil,
after: after != nil && after! > 0 ? Date(timeIntervalSince1970: after!) : nil,
direction: direction
)
topicsList[topic] = page
}
let decodedMessages = try await client.conversations.listBatchDecryptedMessages(topics: topicsList)
return decodedMessages.compactMap { msg in
do {
return try DecodedMessageWrapper.encode(msg, client: client)
} catch {
print("discarding message, unable to encode wrapper \(msg.id)")
return nil
}
}
}
AsyncFunction("sendMessage") { (clientAddress: String, conversationTopic: String, contentJson: String) -> String in
guard let conversation = try await findConversation(clientAddress: clientAddress, topic: conversationTopic) else {
throw Error.conversationNotFound("no conversation found for \(conversationTopic)")
}
let sending = try ContentJson.fromJson(contentJson)
return try await conversation.send(
content: sending.content,
options: SendOptions(contentType: sending.type)
)
}
AsyncFunction("sendMessageToGroup") { (clientAddress: String, id: String, contentJson: String) -> String in
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
let sending = try ContentJson.fromJson(contentJson)
return try await group.send(
content: sending.content,
options: SendOptions(contentType: sending.type)
)
}
AsyncFunction("prepareMessage") { (
clientAddress: String,
conversationTopic: String,
contentJson: String
) -> String in
guard let conversation = try await findConversation(clientAddress: clientAddress, topic: conversationTopic) else {
throw Error.conversationNotFound("no conversation found for \(conversationTopic)")
}
let sending = try ContentJson.fromJson(contentJson)
let prepared = try await conversation.prepareMessage(
content: sending.content,
options: SendOptions(contentType: sending.type)
)
let preparedAtMillis = prepared.envelopes[0].timestampNs / 1_000_000
let preparedData = try prepared.serializedData()
let preparedFile = FileManager.default.temporaryDirectory.appendingPathComponent(prepared.messageID)
try preparedData.write(to: preparedFile)
return try PreparedLocalMessage(
messageId: prepared.messageID,
preparedFileUri: preparedFile.absoluteString,
preparedAt: preparedAtMillis
).toJson()
}
AsyncFunction("prepareEncodedMessage") { (
clientAddress: String,
conversationTopic: String,
encodedContentData: [UInt8]
) -> String in
guard let conversation = try await findConversation(clientAddress: clientAddress, topic: conversationTopic) else {
throw Error.conversationNotFound("no conversation found for \(conversationTopic)")
}
let encodedContent = try EncodedContent(serializedData: Data(encodedContentData))
let prepared = try await conversation.prepareMessage(
encodedContent: encodedContent
)
let preparedAtMillis = prepared.envelopes[0].timestampNs / 1_000_000
let preparedData = try prepared.serializedData()
let preparedFile = FileManager.default.temporaryDirectory.appendingPathComponent(prepared.messageID)
try preparedData.write(to: preparedFile)
return try PreparedLocalMessage(
messageId: prepared.messageID,
preparedFileUri: preparedFile.absoluteString,
preparedAt: preparedAtMillis
).toJson()
}
AsyncFunction("sendPreparedMessage") { (clientAddress: String, preparedLocalMessageJson: String) -> String in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let local = try? PreparedLocalMessage.fromJson(preparedLocalMessageJson) else {
throw Error.badPreparation("bad prepared local message")
}
guard let preparedFileUrl = URL(string: local.preparedFileUri) else {
throw Error.badPreparation("bad prepared local message URI \(local.preparedFileUri)")
}
guard let preparedData = try? Data(contentsOf: preparedFileUrl) else {
throw Error.badPreparation("unable to load local message file")
}
guard let prepared = try? PreparedMessage.fromSerializedData(preparedData) else {
throw Error.badPreparation("unable to deserialized \(local.preparedFileUri)")
}
try await client.publish(envelopes: prepared.envelopes)
do {
try FileManager.default.removeItem(at: URL(string: local.preparedFileUri)!)
} catch { /* ignore: the sending succeeds even if we fail to rm the tmp file afterward */ }
return prepared.messageID
}
AsyncFunction("createConversation") { (clientAddress: String, peerAddress: String, contextJson: String) -> String in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
do {
let contextData = contextJson.data(using: .utf8)!
let contextObj = (try? JSONSerialization.jsonObject(with: contextData) as? [String: Any]) ?? [:]
let conversation = try await client.conversations.newConversation(with: peerAddress, context: .init(
conversationID: contextObj["conversationID"] as? String ?? "",
metadata: contextObj["metadata"] as? [String: String] ?? [:] as [String: String]
))
return try ConversationWrapper.encode(conversation, client: client)
} catch {
print("ERRRO!: \(error.localizedDescription)")
throw error
}
}
AsyncFunction("createGroup") { (clientAddress: String, peerAddresses: [String], permission: String) -> String in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let permissionLevel: GroupPermissions = {
switch permission {
case "creator_admin":
return .groupCreatorIsAdmin
default:
return .everyoneIsAdmin
}
}()
do {
let group = try await client.conversations.newGroup(with: peerAddresses, permissions: permissionLevel)
return try GroupWrapper.encode(group, client: client)
} catch {
print("ERRRO!: \(error.localizedDescription)")
throw error
}
}
AsyncFunction("listMemberAddresses") { (clientAddress: String, groupId: String) -> [String] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let group = try await findGroup(clientAddress: clientAddress, id: groupId) else {
throw Error.conversationNotFound("no group found for \(groupId)")
}
return group.memberAddresses
}
AsyncFunction("syncGroups") { (clientAddress: String) in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
try await client.conversations.sync()
}
AsyncFunction("syncGroup") { (clientAddress: String, id: String) in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
try await group.sync()
}
AsyncFunction("addGroupMembers") { (clientAddress: String, id: String, peerAddresses: [String]) in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
try await group.addMembers(addresses: peerAddresses)
}
AsyncFunction("removeGroupMembers") { (clientAddress: String, id: String, peerAddresses: [String]) in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
try await group.removeMembers(addresses: peerAddresses)
}
AsyncFunction("groupName") { (clientAddress: String, id: String) -> String in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
return try group.groupName()
}
AsyncFunction("updateGroupName") { (clientAddress: String, id: String, groupName: String) in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
try await group.updateGroupName(groupName: groupName)
}
AsyncFunction("isGroupActive") { (clientAddress: String, id: String) -> Bool in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
return try group.isActive()
}
AsyncFunction("addedByAddress") { (clientAddress: String, id: String) -> String in
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
return try group.addedByAddress()
}
AsyncFunction("isGroupAdmin") { (clientAddress: String, id: String) -> Bool in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
return try group.isAdmin()
}
AsyncFunction("processGroupMessage") { (clientAddress: String, id: String, encryptedMessage: String) -> String in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let group = try await findGroup(clientAddress: clientAddress, id: id) else {
throw Error.conversationNotFound("no group found for \(id)")
}
guard let encryptedMessageData = Data(base64Encoded: Data(encryptedMessage.utf8)) else {
throw Error.noMessage
}
let decodedMessage = try await group.processMessageDecrypted(envelopeBytes: encryptedMessageData)
return try DecodedMessageWrapper.encode(decodedMessage, client: client)
}
AsyncFunction("processWelcomeMessage") { (clientAddress: String, encryptedMessage: String) -> String in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let encryptedMessageData = Data(base64Encoded: Data(encryptedMessage.utf8)) else {
throw Error.noMessage
}
guard let group = try await client.conversations.fromWelcome(envelopeBytes: encryptedMessageData) else {
throw Error.conversationNotFound("no group found")
}
return try GroupWrapper.encode(group, client: client)
}
AsyncFunction("subscribeToConversations") { (clientAddress: String) in
try await subscribeToConversations(clientAddress: clientAddress)
}
AsyncFunction("subscribeToAllMessages") { (clientAddress: String, includeGroups: Bool) in
try await subscribeToAllMessages(clientAddress: clientAddress, includeGroups: includeGroups)
}
AsyncFunction("subscribeToAllGroupMessages") { (clientAddress: String) in
try await subscribeToAllGroupMessages(clientAddress: clientAddress)
}
AsyncFunction("subscribeToMessages") { (clientAddress: String, topic: String) in
try await subscribeToMessages(clientAddress: clientAddress, topic: topic)
}
AsyncFunction("subscribeToGroups") { (clientAddress: String) in
try await subscribeToGroups(clientAddress: clientAddress)
}
AsyncFunction("subscribeToAll") { (clientAddress: String) in
try await subscribeToAll(clientAddress: clientAddress)
}
AsyncFunction("subscribeToGroupMessages") { (clientAddress: String, id: String) in
try await subscribeToGroupMessages(clientAddress: clientAddress, id: id)
}
AsyncFunction("unsubscribeFromConversations") { (clientAddress: String) in
await subscriptionsManager.get(getConversationsKey(clientAddress: clientAddress))?.cancel()
}
AsyncFunction("unsubscribeFromAllMessages") { (clientAddress: String) in
await subscriptionsManager.get(getMessagesKey(clientAddress: clientAddress))?.cancel()
}
AsyncFunction("unsubscribeFromAllGroupMessages") { (clientAddress: String) in
await subscriptionsManager.get(getGroupMessagesKey(clientAddress: clientAddress))?.cancel()
}
AsyncFunction("unsubscribeFromMessages") { (clientAddress: String, topic: String) in
try await unsubscribeFromMessages(clientAddress: clientAddress, topic: topic)
}
AsyncFunction("unsubscribeFromGroupMessages") { (clientAddress: String, id: String) in
try await unsubscribeFromGroupMessages(clientAddress: clientAddress, id: id)
}
AsyncFunction("unsubscribeFromGroups") { (clientAddress: String) in
await subscriptionsManager.get(getGroupsKey(clientAddress: clientAddress))?.cancel()
}
AsyncFunction("registerPushToken") { (pushServer: String, token: String) in
XMTPPush.shared.setPushServer(pushServer)
do {
try await XMTPPush.shared.register(token: token)
} catch {
print("Error registering: \(error)")
}
}
AsyncFunction("subscribePushTopics") { (clientAddress: String, topics: [String]) in
do {
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let hmacKeysResult = await client.conversations.getHmacKeys()
let subscriptions = topics.map { topic -> NotificationSubscription in
let hmacKeys = hmacKeysResult.hmacKeys
let result = hmacKeys[topic]?.values.map { hmacKey -> NotificationSubscriptionHmacKey in
NotificationSubscriptionHmacKey.with { sub_key in
sub_key.key = hmacKey.hmacKey
sub_key.thirtyDayPeriodsSinceEpoch = UInt32(hmacKey.thirtyDayPeriodsSinceEpoch)
}
}
return NotificationSubscription.with { sub in
sub.hmacKeys = result ?? []
sub.topic = topic
}
}
try await XMTPPush.shared.subscribeWithMetadata(subscriptions: subscriptions)
} catch {
print("Error subscribing: \(error)")
}
}
AsyncFunction("decodeMessage") { (clientAddress: String, topic: String, encryptedMessage: String) -> String in
guard let encryptedMessageData = Data(base64Encoded: Data(encryptedMessage.utf8)) else {
throw Error.noMessage
}
let envelope = XMTP.Envelope.with { envelope in
envelope.message = encryptedMessageData
envelope.contentTopic = topic
}
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let conversation = try await findConversation(clientAddress: clientAddress, topic: topic) else {
throw Error.conversationNotFound("no conversation found for \(topic)")
}
let decodedMessage = try conversation.decrypt(envelope)
return try DecodedMessageWrapper.encode(decodedMessage, client: client)
}
AsyncFunction("isAllowed") { (clientAddress: String, address: String) -> Bool in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
return await client.contacts.isAllowed(address)
}
AsyncFunction("isDenied") { (clientAddress: String, address: String) -> Bool in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
return await client.contacts.isDenied(address)
}
AsyncFunction("denyContacts") { (clientAddress: String, addresses: [String]) in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
try await client.contacts.deny(addresses: addresses)
}
AsyncFunction("allowContacts") { (clientAddress: String, addresses: [String]) in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
try await client.contacts.allow(addresses: addresses)
}
AsyncFunction("refreshConsentList") { (clientAddress: String) -> [String] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let consentList = try await client.contacts.refreshConsentList()
return try await consentList.entriesManager.map.compactMap { entry in
try ConsentWrapper.encode(entry.value)
}
}
AsyncFunction("conversationConsentState") { (clientAddress: String, conversationTopic: String) -> String in
guard let conversation = try await findConversation(clientAddress: clientAddress, topic: conversationTopic) else {
throw Error.conversationNotFound(conversationTopic)
}
return ConsentWrapper.consentStateToString(state: await conversation.consentState())
}
AsyncFunction("groupConsentState") { (clientAddress: String, groupId: String) -> String in
guard let group = try await findGroup(clientAddress: clientAddress, id: groupId) else {
throw Error.conversationNotFound("no group found for \(groupId)")
}
return ConsentWrapper.consentStateToString(state: await XMTP.Conversation.group(group).consentState())
}
AsyncFunction("consentList") { (clientAddress: String) -> [String] in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let entries = await client.contacts.consentList.entriesManager.map
return try entries.compactMap { entry in
try ConsentWrapper.encode(entry.value)
}
}
Function("preEnableIdentityCallbackCompleted") {
DispatchQueue.global().async {
self.preEnableIdentityCallbackDeferred?.signal()
self.preEnableIdentityCallbackDeferred = nil
}
}
Function("preCreateIdentityCallbackCompleted") {
DispatchQueue.global().async {
self.preCreateIdentityCallbackDeferred?.signal()
self.preCreateIdentityCallbackDeferred = nil
}
}
AsyncFunction("allowGroups") { (clientAddress: String, groupIds: [String]) in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let groupDataIds = groupIds.compactMap { Data(hex: $0) }
try await client.contacts.allowGroup(groupIds: groupDataIds)
}
AsyncFunction("denyGroups") { (clientAddress: String, groupIds: [String]) in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
let groupDataIds = groupIds.compactMap { Data(hex: $0) }
try await client.contacts.denyGroup(groupIds: groupDataIds)
}
AsyncFunction("isGroupAllowed") { (clientAddress: String, groupId: String) -> Bool in
guard let client = await clientsManager.getClient(key: clientAddress) else {
throw Error.noClient
}
guard let groupDataId = Data(hex: groupId) else {
throw Error.invalidString
}
return try await client.contacts.isGroupAllowed(groupId: groupDataId)
}
AsyncFunction("isGroupDenied") { (clientAddress: String, groupId: String) -> Bool in
guard let client = await clientsManager.getClient(key: clientAddress) else {