-
Notifications
You must be signed in to change notification settings - Fork 23
/
mls.rs
4969 lines (4307 loc) · 169 KB
/
mls.rs
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
pub use crate::inbox_owner::SigningError;
use crate::logger::init_logger;
use crate::{FfiSubscribeError, GenericError};
use std::{collections::HashMap, convert::TryInto, sync::Arc};
use tokio::sync::Mutex;
use xmtp_api_grpc::grpc_api_helper::Client as TonicApiClient;
use xmtp_id::associations::verify_signed_with_public_context;
use xmtp_id::scw_verifier::RemoteSignatureVerifier;
use xmtp_id::{
associations::{
builder::SignatureRequest,
generate_inbox_id as xmtp_id_generate_inbox_id,
unverified::{NewUnverifiedSmartContractWalletSignature, UnverifiedSignature},
AccountId, AssociationState, MemberIdentifier,
},
InboxId,
};
use xmtp_mls::groups::device_sync::preference_sync::UserPreferenceUpdate;
use xmtp_mls::groups::scoped_client::LocalScopedGroupClient;
use xmtp_mls::groups::HmacKey;
use xmtp_mls::storage::group::ConversationType;
use xmtp_mls::storage::group_message::SortDirection;
use xmtp_mls::storage::group_message::{ContentType, MsgQueryArgs};
use xmtp_mls::{
api::ApiClientWrapper,
builder::ClientBuilder,
client::{Client as MlsClient, ClientError},
groups::{
group_metadata::GroupMetadata,
group_mutable_metadata::MetadataField,
group_permissions::{
BasePolicies, GroupMutablePermissions, GroupMutablePermissionsError,
MembershipPolicies, MetadataBasePolicies, MetadataPolicies, PermissionsBasePolicies,
PermissionsPolicies, PolicySet,
},
intents::{PermissionPolicyOption, PermissionUpdateType},
members::PermissionLevel,
GroupMetadataOptions, MlsGroup, PreconfiguredPolicies, UpdateAdminListType,
},
identity::IdentityStrategy,
storage::{
consent_record::{ConsentState, ConsentType, StoredConsentRecord},
group::GroupQueryArgs,
group_message::{DeliveryStatus, GroupMessageKind, StoredGroupMessage},
EncryptedMessageStore, EncryptionKey, StorageOption,
},
AbortHandle, GenericStreamHandle, StreamHandle,
};
use xmtp_proto::xmtp::mls::message_contents::DeviceSyncKind;
pub type RustXmtpClient = MlsClient<TonicApiClient>;
#[derive(uniffi::Object, Clone)]
pub struct XmtpApiClient(TonicApiClient);
#[uniffi::export(async_runtime = "tokio")]
pub async fn connect_to_backend(
host: String,
is_secure: bool,
) -> Result<Arc<XmtpApiClient>, GenericError> {
init_logger();
log::info!(
host,
is_secure,
"Creating API client for host: {}, isSecure: {}",
host,
is_secure
);
let api_client = TonicApiClient::create(host, is_secure).await?;
Ok(Arc::new(XmtpApiClient(api_client)))
}
/// It returns a new client of the specified `inbox_id`.
/// Note that the `inbox_id` must be either brand new or already associated with the `account_address`.
/// i.e. `inbox_id` cannot be associated with another account address.
///
/// Prior to calling this function, it's suggested to form `inbox_id`, `account_address`, and `nonce` like below.
///
/// ```text
/// inbox_id = get_inbox_id_for_address(account_address)
/// nonce = 0
///
/// // if inbox_id is not associated, we will create new one.
/// if !inbox_id {
/// if !legacy_key { nonce = random_u64() }
/// inbox_id = generate_inbox_id(account_address, nonce)
/// } // Otherwise, we will just use the inbox and ignore the nonce.
/// db_path = $inbox_id-$env
///
/// xmtp.create_client(account_address, nonce, inbox_id, Option<legacy_signed_private_key_proto>)
/// ```
#[allow(clippy::too_many_arguments)]
#[uniffi::export(async_runtime = "tokio")]
pub async fn create_client(
api: Arc<XmtpApiClient>,
db: Option<String>,
encryption_key: Option<Vec<u8>>,
inbox_id: &InboxId,
account_address: String,
nonce: u64,
legacy_signed_private_key_proto: Option<Vec<u8>>,
history_sync_url: Option<String>,
) -> Result<Arc<FfiXmtpClient>, GenericError> {
init_logger();
log::info!(
"Creating message store with path: {:?} and encryption key: {} of length {:?}",
db,
encryption_key.is_some(),
encryption_key.as_ref().map(|k| k.len())
);
let storage_option = match db {
Some(path) => StorageOption::Persistent(path),
None => StorageOption::Ephemeral,
};
let store = match encryption_key {
Some(key) => {
let key: EncryptionKey = key
.try_into()
.map_err(|_| "Malformed 32 byte encryption key".to_string())?;
EncryptedMessageStore::new(storage_option, key).await?
}
None => EncryptedMessageStore::new_unencrypted(storage_option).await?,
};
log::info!("Creating XMTP client");
let identity_strategy = IdentityStrategy::new(
inbox_id.clone(),
account_address.clone(),
nonce,
legacy_signed_private_key_proto,
);
let mut builder = ClientBuilder::new(identity_strategy)
.api_client(Arc::unwrap_or_clone(api).0)
.store(store);
if let Some(url) = &history_sync_url {
builder = builder.history_sync_url(url);
}
let xmtp_client = builder.build().await?;
log::info!(
"Created XMTP client for inbox_id: {}",
xmtp_client.inbox_id()
);
Ok(Arc::new(FfiXmtpClient {
inner_client: Arc::new(xmtp_client),
account_address,
}))
}
#[allow(unused)]
#[uniffi::export(async_runtime = "tokio")]
pub async fn get_inbox_id_for_address(
api: Arc<XmtpApiClient>,
account_address: String,
) -> Result<Option<String>, GenericError> {
let api = ApiClientWrapper::new(Arc::new(api.0.clone()), Default::default());
let results = api
.get_inbox_ids(vec![account_address.clone()])
.await
.map_err(GenericError::from_error)?;
Ok(results.get(&account_address).cloned())
}
#[allow(unused)]
#[uniffi::export]
pub fn generate_inbox_id(account_address: String, nonce: u64) -> Result<String, GenericError> {
Ok(xmtp_id_generate_inbox_id(&account_address, &nonce)?)
}
#[derive(uniffi::Object)]
pub struct FfiSignatureRequest {
inner: Arc<Mutex<SignatureRequest>>,
scw_verifier: RemoteSignatureVerifier<TonicApiClient>,
}
#[uniffi::export(async_runtime = "tokio")]
impl FfiSignatureRequest {
// Signature that's signed by EOA wallet
pub async fn add_ecdsa_signature(&self, signature_bytes: Vec<u8>) -> Result<(), GenericError> {
let mut inner = self.inner.lock().await;
inner
.add_signature(
UnverifiedSignature::new_recoverable_ecdsa(signature_bytes),
&self.scw_verifier,
)
.await?;
Ok(())
}
// Signature that's signed by smart contract wallet
pub async fn add_scw_signature(
&self,
signature_bytes: Vec<u8>,
address: String,
chain_id: u64,
block_number: Option<u64>,
) -> Result<(), GenericError> {
let mut inner = self.inner.lock().await;
let account_id = AccountId::new_evm(chain_id, address);
let new_signature = NewUnverifiedSmartContractWalletSignature::new(
signature_bytes,
account_id,
block_number,
);
inner
.add_new_unverified_smart_contract_signature(new_signature, &self.scw_verifier)
.await?;
Ok(())
}
pub async fn is_ready(&self) -> bool {
self.inner.lock().await.is_ready()
}
pub async fn signature_text(&self) -> Result<String, GenericError> {
Ok(self.inner.lock().await.signature_text())
}
/// missing signatures that are from [MemberKind::Address]
pub async fn missing_address_signatures(&self) -> Result<Vec<String>, GenericError> {
let inner = self.inner.lock().await;
Ok(inner
.missing_address_signatures()
.iter()
.map(|member| member.to_string())
.collect())
}
}
#[derive(uniffi::Object)]
pub struct FfiXmtpClient {
inner_client: Arc<RustXmtpClient>,
#[allow(dead_code)]
account_address: String,
}
#[uniffi::export(async_runtime = "tokio")]
impl FfiXmtpClient {
pub fn inbox_id(&self) -> InboxId {
self.inner_client.inbox_id().to_string()
}
pub fn conversations(&self) -> Arc<FfiConversations> {
Arc::new(FfiConversations {
inner_client: self.inner_client.clone(),
})
}
pub fn conversation(&self, conversation_id: Vec<u8>) -> Result<FfiConversation, GenericError> {
self.inner_client
.group(conversation_id)
.map(Into::into)
.map_err(Into::into)
}
pub fn dm_conversation(
&self,
target_inbox_id: String,
) -> Result<FfiConversation, GenericError> {
let convo = self
.inner_client
.dm_group_from_target_inbox(target_inbox_id)?;
Ok(convo.into())
}
pub fn message(&self, message_id: Vec<u8>) -> Result<FfiMessage, GenericError> {
let message = self.inner_client.message(message_id)?;
Ok(message.into())
}
pub async fn can_message(
&self,
account_addresses: Vec<String>,
) -> Result<HashMap<String, bool>, GenericError> {
let inner = self.inner_client.as_ref();
let results: HashMap<String, bool> = inner.can_message(&account_addresses).await?;
Ok(results)
}
pub fn installation_id(&self) -> Vec<u8> {
self.inner_client.installation_public_key().to_vec()
}
pub fn release_db_connection(&self) -> Result<(), GenericError> {
Ok(self.inner_client.release_db_connection()?)
}
pub async fn db_reconnect(&self) -> Result<(), GenericError> {
Ok(self.inner_client.reconnect_db()?)
}
pub async fn find_inbox_id(&self, address: String) -> Result<Option<String>, GenericError> {
let inner = self.inner_client.as_ref();
let conn = self.inner_client.store().conn()?;
let result = inner.find_inbox_id_from_address(&conn, address).await?;
Ok(result)
}
/**
* Get the client's inbox state.
*
* If `refresh_from_network` is true, the client will go to the network first to refresh the state.
* Otherwise, the state will be read from the local database.
*/
pub async fn inbox_state(
&self,
refresh_from_network: bool,
) -> Result<FfiInboxState, GenericError> {
let state = self.inner_client.inbox_state(refresh_from_network).await?;
Ok(state.into())
}
/**
* Get the inbox state for each `inbox_id`.
*
* If `refresh_from_network` is true, the client will go to the network first to refresh the state.
* Otherwise, the state will be read from the local database.
*/
pub async fn addresses_from_inbox_id(
&self,
refresh_from_network: bool,
inbox_ids: Vec<String>,
) -> Result<Vec<FfiInboxState>, GenericError> {
let state = self
.inner_client
.inbox_addresses(
refresh_from_network,
inbox_ids.iter().map(String::as_str).collect(),
)
.await?;
Ok(state.into_iter().map(Into::into).collect())
}
pub async fn get_latest_inbox_state(
&self,
inbox_id: String,
) -> Result<FfiInboxState, GenericError> {
let state = self
.inner_client
.get_latest_association_state(&self.inner_client.store().conn()?, &inbox_id)
.await?;
Ok(state.into())
}
pub async fn set_consent_states(&self, records: Vec<FfiConsent>) -> Result<(), GenericError> {
let inner = self.inner_client.as_ref();
let stored_records: Vec<StoredConsentRecord> =
records.into_iter().map(StoredConsentRecord::from).collect();
inner.set_consent_states(&stored_records).await?;
Ok(())
}
pub async fn get_consent_state(
&self,
entity_type: FfiConsentEntityType,
entity: String,
) -> Result<FfiConsentState, GenericError> {
let inner = self.inner_client.as_ref();
let result = inner.get_consent_state(entity_type.into(), entity).await?;
Ok(result.into())
}
pub fn sign_with_installation_key(&self, text: &str) -> Result<Vec<u8>, GenericError> {
let inner = self.inner_client.as_ref();
Ok(inner.context().sign_with_public_context(text)?)
}
pub fn verify_signed_with_installation_key(
&self,
signature_text: &str,
signature_bytes: Vec<u8>,
) -> Result<(), GenericError> {
let inner = self.inner_client.as_ref();
let public_key = inner.installation_public_key().to_vec();
self.verify_signed_with_public_key(signature_text, signature_bytes, public_key)
}
pub fn verify_signed_with_public_key(
&self,
signature_text: &str,
signature_bytes: Vec<u8>,
public_key: Vec<u8>,
) -> Result<(), GenericError> {
let signature_bytes: [u8; 64] =
signature_bytes
.try_into()
.map_err(|v: Vec<u8>| GenericError::Generic {
err: format!(
"signature_bytes is not 64 bytes long. (Actual size: {})",
v.len()
),
})?;
let public_key: [u8; 32] =
public_key
.try_into()
.map_err(|v: Vec<u8>| GenericError::Generic {
err: format!(
"public_key is not 32 bytes long. (Actual size: {})",
v.len()
),
})?;
Ok(verify_signed_with_public_context(
signature_text,
&signature_bytes,
&public_key,
)?)
}
}
#[uniffi::export(async_runtime = "tokio")]
impl FfiXmtpClient {
pub fn signature_request(&self) -> Option<Arc<FfiSignatureRequest>> {
let scw_verifier = self.inner_client.scw_verifier().clone();
self.inner_client
.identity()
.signature_request()
.map(move |request| {
Arc::new(FfiSignatureRequest {
inner: Arc::new(Mutex::new(request)),
scw_verifier: scw_verifier.clone(),
})
})
}
pub async fn register_identity(
&self,
signature_request: Arc<FfiSignatureRequest>,
) -> Result<(), GenericError> {
let signature_request = signature_request.inner.lock().await;
self.inner_client
.register_identity(signature_request.clone())
.await?;
Ok(())
}
pub async fn send_sync_request(&self, kind: FfiDeviceSyncKind) -> Result<(), GenericError> {
let provider = self.inner_client.mls_provider()?;
self.inner_client
.send_sync_request(&provider, kind.into())
.await?;
Ok(())
}
/// Adds a wallet address to the existing client
pub async fn add_wallet(
&self,
new_wallet_address: &str,
) -> Result<Arc<FfiSignatureRequest>, GenericError> {
let signature_request = self
.inner_client
.associate_wallet(new_wallet_address.into())
.await?;
let scw_verifier = self.inner_client.scw_verifier().clone();
let request = Arc::new(FfiSignatureRequest {
inner: Arc::new(tokio::sync::Mutex::new(signature_request)),
scw_verifier: scw_verifier.clone(),
});
Ok(request)
}
pub async fn apply_signature_request(
&self,
signature_request: Arc<FfiSignatureRequest>,
) -> Result<(), GenericError> {
let signature_request = signature_request.inner.lock().await;
self.inner_client
.apply_signature_request(signature_request.clone())
.await?;
Ok(())
}
/// Revokes or removes an identity - really a wallet address - from the existing client
pub async fn revoke_wallet(
&self,
wallet_address: &str,
) -> Result<Arc<FfiSignatureRequest>, GenericError> {
let Self {
ref inner_client, ..
} = self;
let signature_request = inner_client
.revoke_wallets(vec![wallet_address.into()])
.await?;
let scw_verifier = inner_client.clone().scw_verifier().clone();
let request = Arc::new(FfiSignatureRequest {
inner: Arc::new(tokio::sync::Mutex::new(signature_request)),
scw_verifier,
});
Ok(request)
}
/**
* Revokes all installations except the one the client is currently using
*/
pub async fn revoke_all_other_installations(
&self,
) -> Result<Arc<FfiSignatureRequest>, GenericError> {
let installation_id = self.inner_client.installation_public_key();
let inbox_state = self.inner_client.inbox_state(true).await?;
let other_installation_ids = inbox_state
.installation_ids()
.into_iter()
.filter(|id| id != installation_id)
.collect();
let signature_request = self
.inner_client
.revoke_installations(other_installation_ids)
.await?;
Ok(Arc::new(FfiSignatureRequest {
inner: Arc::new(tokio::sync::Mutex::new(signature_request)),
scw_verifier: self.inner_client.scw_verifier().clone().clone(),
}))
}
}
impl From<HmacKey> for FfiHmacKey {
fn from(value: HmacKey) -> Self {
Self {
epoch: value.epoch,
key: value.key.to_vec(),
}
}
}
#[derive(uniffi::Record)]
pub struct FfiInboxState {
pub inbox_id: String,
pub recovery_address: String,
pub installations: Vec<FfiInstallation>,
pub account_addresses: Vec<String>,
}
#[derive(uniffi::Record)]
pub struct FfiHmacKey {
key: Vec<u8>,
epoch: i64,
}
#[derive(uniffi::Record)]
pub struct FfiInstallation {
pub id: Vec<u8>,
pub client_timestamp_ns: Option<u64>,
}
impl From<AssociationState> for FfiInboxState {
fn from(state: AssociationState) -> Self {
Self {
inbox_id: state.inbox_id().to_string(),
recovery_address: state.recovery_address().to_string(),
installations: state
.members()
.into_iter()
.filter_map(|m| match m.identifier {
MemberIdentifier::Address(_) => None,
MemberIdentifier::Installation(inst) => Some(FfiInstallation {
id: inst,
client_timestamp_ns: m.client_timestamp_ns,
}),
})
.collect(),
account_addresses: state.account_addresses(),
}
}
}
#[derive(uniffi::Record, Default)]
pub struct FfiListConversationsOptions {
pub created_after_ns: Option<i64>,
pub created_before_ns: Option<i64>,
pub limit: Option<i64>,
pub consent_state: Option<FfiConsentState>,
}
impl From<FfiListConversationsOptions> for GroupQueryArgs {
fn from(opts: FfiListConversationsOptions) -> GroupQueryArgs {
GroupQueryArgs::default()
.maybe_created_before_ns(opts.created_before_ns)
.maybe_created_after_ns(opts.created_after_ns)
.maybe_limit(opts.limit)
.maybe_consent_state(opts.consent_state.map(Into::into))
}
}
#[derive(uniffi::Object)]
pub struct FfiConversations {
inner_client: Arc<RustXmtpClient>,
}
#[derive(uniffi::Enum, Clone, Debug)]
pub enum FfiGroupPermissionsOptions {
AllMembers,
AdminOnly,
CustomPolicy,
}
#[derive(uniffi::Enum, Debug)]
pub enum FfiPermissionUpdateType {
AddMember,
RemoveMember,
AddAdmin,
RemoveAdmin,
UpdateMetadata,
}
impl From<&FfiPermissionUpdateType> for PermissionUpdateType {
fn from(update_type: &FfiPermissionUpdateType) -> Self {
match update_type {
FfiPermissionUpdateType::AddMember => PermissionUpdateType::AddMember,
FfiPermissionUpdateType::RemoveMember => PermissionUpdateType::RemoveMember,
FfiPermissionUpdateType::AddAdmin => PermissionUpdateType::AddAdmin,
FfiPermissionUpdateType::RemoveAdmin => PermissionUpdateType::RemoveAdmin,
FfiPermissionUpdateType::UpdateMetadata => PermissionUpdateType::UpdateMetadata,
}
}
}
#[derive(uniffi::Enum, Clone, Debug, PartialEq, Eq)]
pub enum FfiPermissionPolicy {
Allow,
Deny,
Admin,
SuperAdmin,
DoesNotExist,
Other,
}
impl TryInto<PermissionPolicyOption> for FfiPermissionPolicy {
type Error = GroupMutablePermissionsError;
fn try_into(self) -> Result<PermissionPolicyOption, Self::Error> {
match self {
FfiPermissionPolicy::Allow => Ok(PermissionPolicyOption::Allow),
FfiPermissionPolicy::Deny => Ok(PermissionPolicyOption::Deny),
FfiPermissionPolicy::Admin => Ok(PermissionPolicyOption::AdminOnly),
FfiPermissionPolicy::SuperAdmin => Ok(PermissionPolicyOption::SuperAdminOnly),
_ => Err(GroupMutablePermissionsError::InvalidPermissionPolicyOption),
}
}
}
impl TryInto<MembershipPolicies> for FfiPermissionPolicy {
type Error = GroupMutablePermissionsError;
fn try_into(self) -> Result<MembershipPolicies, Self::Error> {
match self {
FfiPermissionPolicy::Allow => Ok(MembershipPolicies::allow()),
FfiPermissionPolicy::Deny => Ok(MembershipPolicies::deny()),
FfiPermissionPolicy::Admin => Ok(MembershipPolicies::allow_if_actor_admin()),
FfiPermissionPolicy::SuperAdmin => Ok(MembershipPolicies::allow_if_actor_super_admin()),
_ => Err(GroupMutablePermissionsError::InvalidPermissionPolicyOption),
}
}
}
impl TryInto<MetadataPolicies> for FfiPermissionPolicy {
type Error = GroupMutablePermissionsError;
fn try_into(self) -> Result<MetadataPolicies, Self::Error> {
match self {
FfiPermissionPolicy::Allow => Ok(MetadataPolicies::allow()),
FfiPermissionPolicy::Deny => Ok(MetadataPolicies::deny()),
FfiPermissionPolicy::Admin => Ok(MetadataPolicies::allow_if_actor_admin()),
FfiPermissionPolicy::SuperAdmin => Ok(MetadataPolicies::allow_if_actor_super_admin()),
_ => Err(GroupMutablePermissionsError::InvalidPermissionPolicyOption),
}
}
}
impl TryInto<PermissionsPolicies> for FfiPermissionPolicy {
type Error = GroupMutablePermissionsError;
fn try_into(self) -> Result<PermissionsPolicies, Self::Error> {
match self {
FfiPermissionPolicy::Deny => Ok(PermissionsPolicies::deny()),
FfiPermissionPolicy::Admin => Ok(PermissionsPolicies::allow_if_actor_admin()),
FfiPermissionPolicy::SuperAdmin => {
Ok(PermissionsPolicies::allow_if_actor_super_admin())
}
_ => Err(GroupMutablePermissionsError::InvalidPermissionPolicyOption),
}
}
}
impl From<&MembershipPolicies> for FfiPermissionPolicy {
fn from(policies: &MembershipPolicies) -> Self {
if let MembershipPolicies::Standard(base_policy) = policies {
match base_policy {
BasePolicies::Allow => FfiPermissionPolicy::Allow,
BasePolicies::Deny => FfiPermissionPolicy::Deny,
BasePolicies::AllowSameMember => FfiPermissionPolicy::Other,
BasePolicies::AllowIfAdminOrSuperAdmin => FfiPermissionPolicy::Admin,
BasePolicies::AllowIfSuperAdmin => FfiPermissionPolicy::SuperAdmin,
}
} else {
FfiPermissionPolicy::Other
}
}
}
impl From<&MetadataPolicies> for FfiPermissionPolicy {
fn from(policies: &MetadataPolicies) -> Self {
if let MetadataPolicies::Standard(base_policy) = policies {
match base_policy {
MetadataBasePolicies::Allow => FfiPermissionPolicy::Allow,
MetadataBasePolicies::Deny => FfiPermissionPolicy::Deny,
MetadataBasePolicies::AllowIfActorAdminOrSuperAdmin => FfiPermissionPolicy::Admin,
MetadataBasePolicies::AllowIfActorSuperAdmin => FfiPermissionPolicy::SuperAdmin,
}
} else {
FfiPermissionPolicy::Other
}
}
}
impl From<&PermissionsPolicies> for FfiPermissionPolicy {
fn from(policies: &PermissionsPolicies) -> Self {
if let PermissionsPolicies::Standard(base_policy) = policies {
match base_policy {
PermissionsBasePolicies::Deny => FfiPermissionPolicy::Deny,
PermissionsBasePolicies::AllowIfActorAdminOrSuperAdmin => {
FfiPermissionPolicy::Admin
}
PermissionsBasePolicies::AllowIfActorSuperAdmin => FfiPermissionPolicy::SuperAdmin,
}
} else {
FfiPermissionPolicy::Other
}
}
}
#[derive(uniffi::Record, Clone, Debug, PartialEq, Eq)]
pub struct FfiPermissionPolicySet {
pub add_member_policy: FfiPermissionPolicy,
pub remove_member_policy: FfiPermissionPolicy,
pub add_admin_policy: FfiPermissionPolicy,
pub remove_admin_policy: FfiPermissionPolicy,
pub update_group_name_policy: FfiPermissionPolicy,
pub update_group_description_policy: FfiPermissionPolicy,
pub update_group_image_url_square_policy: FfiPermissionPolicy,
pub update_group_pinned_frame_url_policy: FfiPermissionPolicy,
}
impl From<PreconfiguredPolicies> for FfiGroupPermissionsOptions {
fn from(policy: PreconfiguredPolicies) -> Self {
match policy {
PreconfiguredPolicies::AllMembers => FfiGroupPermissionsOptions::AllMembers,
PreconfiguredPolicies::AdminsOnly => FfiGroupPermissionsOptions::AdminOnly,
}
}
}
impl TryFrom<FfiPermissionPolicySet> for PolicySet {
type Error = GroupMutablePermissionsError;
fn try_from(policy_set: FfiPermissionPolicySet) -> Result<Self, GroupMutablePermissionsError> {
let mut metadata_permissions_map: HashMap<String, MetadataPolicies> = HashMap::new();
metadata_permissions_map.insert(
MetadataField::GroupName.to_string(),
policy_set.update_group_name_policy.try_into()?,
);
metadata_permissions_map.insert(
MetadataField::Description.to_string(),
policy_set.update_group_description_policy.try_into()?,
);
metadata_permissions_map.insert(
MetadataField::GroupImageUrlSquare.to_string(),
policy_set.update_group_image_url_square_policy.try_into()?,
);
metadata_permissions_map.insert(
MetadataField::GroupPinnedFrameUrl.to_string(),
policy_set.update_group_pinned_frame_url_policy.try_into()?,
);
Ok(PolicySet {
add_member_policy: policy_set.add_member_policy.try_into()?,
remove_member_policy: policy_set.remove_member_policy.try_into()?,
add_admin_policy: policy_set.add_admin_policy.try_into()?,
remove_admin_policy: policy_set.remove_admin_policy.try_into()?,
update_metadata_policy: metadata_permissions_map,
update_permissions_policy: PermissionsPolicies::allow_if_actor_super_admin(),
})
}
}
#[derive(uniffi::Enum, Debug)]
pub enum FfiMetadataField {
GroupName,
Description,
ImageUrlSquare,
PinnedFrameUrl,
}
impl From<&FfiMetadataField> for MetadataField {
fn from(field: &FfiMetadataField) -> Self {
match field {
FfiMetadataField::GroupName => MetadataField::GroupName,
FfiMetadataField::Description => MetadataField::Description,
FfiMetadataField::ImageUrlSquare => MetadataField::GroupImageUrlSquare,
FfiMetadataField::PinnedFrameUrl => MetadataField::GroupPinnedFrameUrl,
}
}
}
#[uniffi::export(async_runtime = "tokio")]
impl FfiConversations {
pub async fn create_group(
&self,
account_addresses: Vec<String>,
opts: FfiCreateGroupOptions,
) -> Result<Arc<FfiConversation>, GenericError> {
log::info!(
"creating group with account addresses: {}",
account_addresses.join(", ")
);
if let Some(FfiGroupPermissionsOptions::CustomPolicy) = opts.permissions {
if opts.custom_permission_policy_set.is_none() {
return Err(GenericError::Generic {
err: "CustomPolicy must include policy set".to_string(),
});
}
} else if opts.custom_permission_policy_set.is_some() {
return Err(GenericError::Generic {
err: "Only CustomPolicy may specify a policy set".to_string(),
});
}
let metadata_options = opts.clone().into_group_metadata_options();
let group_permissions = match opts.permissions {
Some(FfiGroupPermissionsOptions::AllMembers) => {
Some(xmtp_mls::groups::PreconfiguredPolicies::AllMembers.to_policy_set())
}
Some(FfiGroupPermissionsOptions::AdminOnly) => {
Some(xmtp_mls::groups::PreconfiguredPolicies::AdminsOnly.to_policy_set())
}
Some(FfiGroupPermissionsOptions::CustomPolicy) => {
if let Some(policy_set) = opts.custom_permission_policy_set {
Some(policy_set.try_into()?)
} else {
None
}
}
_ => None,
};
let convo = if account_addresses.is_empty() {
self.inner_client
.create_group(group_permissions, metadata_options)?
} else {
self.inner_client
.create_group_with_members(&account_addresses, group_permissions, metadata_options)
.await?
};
Ok(Arc::new(convo.into()))
}
pub async fn create_dm(
&self,
account_address: String,
) -> Result<Arc<FfiConversation>, GenericError> {
log::info!("creating dm with target address: {}", account_address);
self.inner_client
.create_dm(account_address)
.await
.map(|g| Arc::new(g.into()))
.map_err(Into::into)
}
pub async fn process_streamed_welcome_message(
&self,
envelope_bytes: Vec<u8>,
) -> Result<Arc<FfiConversation>, GenericError> {
self.inner_client
.process_streamed_welcome_message(envelope_bytes)
.await
.map(|g| Arc::new(g.into()))
.map_err(Into::into)
}
pub async fn sync(&self) -> Result<(), GenericError> {
let inner = self.inner_client.as_ref();
let provider = inner.mls_provider()?;
inner.sync_welcomes(&provider).await?;
Ok(())
}
pub fn get_sync_group(&self) -> Result<FfiConversation, GenericError> {
let inner = self.inner_client.as_ref();
let conn = inner.store().conn()?;
let sync_group = inner.get_sync_group(&conn)?;
Ok(sync_group.into())
}
pub async fn sync_all_conversations(
&self,
consent_state: Option<FfiConsentState>,
) -> Result<u32, GenericError> {
let inner = self.inner_client.as_ref();
let provider = inner.mls_provider()?;
let consent: Option<ConsentState> = consent_state.map(|state| state.into());
let num_groups_synced: usize = inner
.sync_all_welcomes_and_groups(&provider, consent)
.await?;
// Convert usize to u32 for compatibility with Uniffi
let num_groups_synced: u32 = num_groups_synced
.try_into()
.map_err(|_| GenericError::FailedToConvertToU32)?;
Ok(num_groups_synced)
}
pub async fn list(
&self,
opts: FfiListConversationsOptions,
) -> Result<Vec<Arc<FfiConversation>>, GenericError> {
let inner = self.inner_client.as_ref();
let convo_list: Vec<Arc<FfiConversation>> = inner
.find_groups(opts.into())?
.into_iter()
.map(|group| Arc::new(group.into()))
.collect();
Ok(convo_list)
}
pub async fn list_groups(
&self,
opts: FfiListConversationsOptions,
) -> Result<Vec<Arc<FfiConversation>>, GenericError> {
let inner = self.inner_client.as_ref();
let convo_list: Vec<Arc<FfiConversation>> = inner
.find_groups(GroupQueryArgs::from(opts).conversation_type(ConversationType::Group))?
.into_iter()
.map(|group| Arc::new(group.into()))
.collect();
Ok(convo_list)
}
pub async fn list_dms(
&self,
opts: FfiListConversationsOptions,
) -> Result<Vec<Arc<FfiConversation>>, GenericError> {
let inner = self.inner_client.as_ref();
let convo_list: Vec<Arc<FfiConversation>> = inner
.find_groups(GroupQueryArgs::from(opts).conversation_type(ConversationType::Dm))?
.into_iter()
.map(|group| Arc::new(group.into()))
.collect();
Ok(convo_list)
}
pub async fn stream_groups(
&self,
callback: Arc<dyn FfiConversationCallback>,
) -> FfiStreamCloser {
let client = self.inner_client.clone();
let handle = RustXmtpClient::stream_conversations_with_callback(
client.clone(),
Some(ConversationType::Group),
move |convo| match convo {
Ok(c) => callback.on_conversation(Arc::new(c.into())),
Err(e) => callback.on_error(e.into()),
},
);
FfiStreamCloser::new(handle)
}
pub async fn stream_dms(&self, callback: Arc<dyn FfiConversationCallback>) -> FfiStreamCloser {
let client = self.inner_client.clone();
let handle = RustXmtpClient::stream_conversations_with_callback(
client.clone(),
Some(ConversationType::Dm),
move |convo| match convo {