1#[macro_use]
29mod macros;
30
31pub mod rt;
33pub mod files;
34#[cfg(target_arch = "wasm32")]
35pub mod webfiles;
36pub mod logging;
37pub mod error;
38pub mod traits;
39
40use crate::event_ext::FinalizeUnsignedWithId;
42use nostr_sdk::prelude::{FinalizeEventAsync, ToBech32};
43
44pub mod event_ext;
46pub mod event_json;
47pub mod tags;
48pub mod types;
49pub mod profile;
50pub mod chat;
51pub mod clock;
52pub mod boot_payload;
53pub mod compact;
54
55pub mod state;
57
58#[cfg(any(debug_assertions, feature = "bench"))]
60pub mod stats;
61
62pub mod crypto;
64
65pub mod signer;
67
68pub mod nip55;
70
71pub mod nip07;
73
74pub mod db;
76pub mod spawn_audit;
79#[cfg(test)]
80mod vault_audit;
81
82pub mod net;
84pub mod fasthash;
85pub mod event_size;
86#[cfg(not(target_arch = "wasm32"))]
87pub mod tls;
88pub mod events_tracker;
89pub mod proxy;
90pub mod negentropy;
91pub mod dm_catchup;
92pub mod live_subs;
93pub mod news;
94pub mod blossom;
95pub mod media;
96pub mod blossom_servers;
97pub mod blossom_capabilities;
98pub mod blossom_error;
99pub mod blossom_info;
100pub mod blossom_stats;
101pub mod inbox_relays;
102pub mod relay_info;
103pub mod emoji_packs;
104pub mod text_color;
105pub mod text_time;
106pub mod text_spans;
107pub mod secrets;
108pub mod emoji_usage;
109pub mod nostr_embed;
110pub mod video_poster;
111pub mod image_crop;
112pub mod image_prep;
113pub mod deep_link;
114pub mod golink;
115pub mod badges;
116pub mod history_gaps;
117pub mod bot_interface;
118pub mod webxdc;
119pub mod webxdc_permissions;
120#[cfg(feature = "xdc")]
121pub mod xdc;
122#[cfg(feature = "tor")]
123pub mod tor;
124#[cfg(all(feature = "i2p", not(target_arch = "wasm32")))]
125pub mod i2p;
126pub mod transport;
127pub mod svg;
128#[cfg(not(target_arch = "wasm32"))]
129pub mod vcache;
130
131#[derive(Debug)]
143pub struct VectorAuthenticator;
144
145impl nostr_sdk::prelude::Authenticator for VectorAuthenticator {
146 fn make_auth_event<'a>(
147 &'a self,
148 relay_url: &'a nostr_sdk::prelude::RelayUrl,
149 challenge: &'a str,
150 ) -> signer::BoxedFuture<'a, std::result::Result<nostr_sdk::prelude::Event, nostr_sdk::prelude::Error>>
151 {
152 Box::pin(async move {
153 let signer =
154 signer::active_signer().map_err(nostr_sdk::prelude::Error::other)?;
155 Ok(
156 nostr_sdk::prelude::ClientAuthentication::new(challenge, relay_url.clone())
157 .finalize_async(&signer)
158 .await?,
159 )
160 })
161 }
162}
163
164pub fn nostr_client_builder() -> nostr_sdk::prelude::ClientBuilder {
169 transport::ws::apply_transport(
170 nostr_sdk::prelude::ClientBuilder::new().authenticator(VectorAuthenticator),
171 transport::Lane::Account,
172 )
173}
174
175pub use transport::ws::{apply_transport, transport_relay_options};
176
177pub trait ClientRelayExt {
189 fn add_managed_relay<'client, 'url, U>(
191 &'client self,
192 url: U,
193 ) -> nostr_sdk::prelude::AddRelay<'client, 'url>
194 where
195 U: Into<nostr_sdk::prelude::RelayUrlArg<'url>>;
196}
197
198impl ClientRelayExt for nostr_sdk::prelude::Client {
199 fn add_managed_relay<'client, 'url, U>(
200 &'client self,
201 url: U,
202 ) -> nostr_sdk::prelude::AddRelay<'client, 'url>
203 where
204 U: Into<nostr_sdk::prelude::RelayUrlArg<'url>>,
205 {
206 self.add_relay(url).reconnect(false)
207 }
208}
209
210pub async fn resubscribe_relay_after_reconnect(
226 client: &nostr_sdk::prelude::Client,
227 relay: &nostr_sdk::prelude::RelayUrl,
228) {
229 use std::borrow::Cow;
230 crate::community::v2::realtime::note_resubscribe();
231 let Ok(Some(handle)) = client.relay(relay).await else { return };
232 let (mut sent, mut failed) = (0usize, 0usize);
233 for (id, per_relay) in client.subscriptions().await {
234 let Some(filters) = per_relay.get(relay) else { continue };
235 if filters.is_empty() {
236 continue;
237 }
238 let req = nostr_sdk::prelude::ClientMessage::Req {
239 subscription_id: Cow::Borrowed(&id),
240 filters: filters.iter().map(Cow::Borrowed).collect(),
241 };
242 match handle.send_msg(req).await {
243 Ok(()) => sent += 1,
244 Err(_) => failed += 1,
245 }
246 }
247 println!("[subs] {relay}: re-sent {sent} live sub(s), {failed} refused");
248 live_subs::heal(client).await;
250}
251
252pub fn relay_connect_timeout(clearnet: std::time::Duration) -> std::time::Duration {
260 transport::budget(transport::Op::RelayConnect, clearnet)
261}
262
263pub fn relay_request_timeout(clearnet: std::time::Duration) -> std::time::Duration {
266 transport::budget(transport::Op::RelayRequest, clearnet)
267}
268
269#[deprecated(note = "use vector_core::apply_transport(builder, lane)")]
271pub fn apply_tor_proxy(
272 builder: nostr_sdk::prelude::ClientBuilder,
273) -> nostr_sdk::prelude::ClientBuilder {
274 apply_transport(builder, transport::Lane::Account)
275}
276
277pub fn transport_aware<'c, 'e, 'u>(
280 send: nostr_sdk::client::SendEvent<'c, 'e, 'u>,
281) -> nostr_sdk::client::SendEvent<'c, 'e, 'u> {
282 let wait = relay_request_timeout(std::time::Duration::from_secs(10));
283 send.ok_timeout(wait).authentication_timeout(wait)
284}
285
286#[deprecated(note = "use vector_core::transport_relay_options()")]
288pub fn tor_relay_options() -> nostr_sdk::prelude::RelayOptions {
289 transport_relay_options()
290}
291
292pub async fn sign_builder(
297 builder: nostr_sdk::prelude::EventBuilder,
298) -> std::result::Result<nostr_sdk::prelude::Event, String> {
299 let signer = signer::active_signer()?;
300 let event = builder
301 .finalize_async(&signer)
302 .await
303 .map_err(|e| e.to_string())?;
304 event_size::check(&event)?;
305 Ok(event)
306}
307
308pub async fn sign_and_send(
312 client: &nostr_sdk::prelude::Client,
313 builder: nostr_sdk::prelude::EventBuilder,
314) -> std::result::Result<nostr_sdk::prelude::SendEventOutput, String> {
315 let event = sign_builder(builder).await?;
316 transport_aware(client.send_event(&event))
317 .await
318 .map_err(|e| e.to_string())
319}
320
321pub async fn fetch_answered(
326 client: &nostr_sdk::prelude::Client,
327 filter: nostr_sdk::prelude::Filter,
328 timeout: std::time::Duration,
329) -> std::result::Result<Vec<nostr_sdk::prelude::Event>, String> {
330 use community::transport::{fetch_relay_eose_filters, EoseFail};
331 use nostr_sdk::prelude::RelayStatus;
332 let relays = client.relays().with_capabilities(nostr_sdk::prelude::RelayCapabilities::READ).await;
333 let live: Vec<_> = relays
335 .iter()
336 .filter(|(_, r)| !matches!(r.status(), RelayStatus::Terminated | RelayStatus::Shutdown | RelayStatus::Banned))
337 .map(|(url, _)| url)
338 .collect();
339 if live.is_empty() {
340 return Err("no relays to read from".to_string());
341 }
342 let reads = live.into_iter().map(|url| {
343 let url = url.to_string();
344 let filter = filter.clone();
345 async move {
346 match fetch_relay_eose_filters(client, &url, vec![filter.clone()], timeout).await {
347 Err(EoseFail::Closed) => {
349 crate::rt::time::sleep(std::time::Duration::from_millis(800)).await;
350 fetch_relay_eose_filters(client, &url, vec![filter], timeout).await
351 }
352 other => other,
353 }
354 }
355 });
356 let mut answered = false;
357 let mut seen = std::collections::HashSet::new();
358 let mut events = Vec::new();
359 for read in futures_util::future::join_all(reads).await.into_iter().flatten() {
360 answered = true;
361 events.extend(read.into_iter().filter(|e| seen.insert(e.id)));
362 }
363 if !answered {
364 return Err("none of your relays answered".to_string());
365 }
366 Ok(events)
367}
368
369pub fn newest_replaceable(events: Vec<nostr_sdk::prelude::Event>) -> Option<nostr_sdk::prelude::Event> {
371 events.into_iter().min_by(|a, b| b.created_at.cmp(&a.created_at).then_with(|| a.id.cmp(&b.id)))
372}
373
374pub async fn send_gift_wrap<'u, I, U, T>(
380 client: &nostr_sdk::prelude::Client,
381 relays: I,
382 receiver: &nostr_sdk::prelude::PublicKey,
383 rumor: nostr_sdk::prelude::UnsignedEvent,
384 extra_tags: T,
385) -> std::result::Result<nostr_sdk::prelude::SendEventOutput, String>
386where
387 I: IntoIterator<Item = U>,
388 U: Into<nostr_sdk::prelude::RelayUrlArg<'u>>,
389 T: IntoIterator<Item = nostr_sdk::prelude::Tag>,
390{
391 let wrap = signer::gift_wrap(receiver, rumor, extra_tags).await?;
392 let targets: Vec<nostr_sdk::prelude::RelayUrlArg<'u>> =
393 relays.into_iter().map(Into::into).collect();
394 if targets.is_empty() {
395 crate::transport_aware(client.send_event(&wrap)).await.map_err(|e| e.to_string())
396 } else {
397 transport_aware(client.send_event(&wrap))
398 .to(targets)
399 .await
400 .map_err(|e| e.to_string())
401 }
402}
403
404pub fn community_relay_capabilities() -> nostr_sdk::prelude::RelayCapabilities {
417 nostr_sdk::prelude::RelayCapabilities::GOSSIP
418}
419
420pub fn discovery_relay_capabilities() -> nostr_sdk::prelude::RelayCapabilities {
426 community_relay_capabilities()
427}
428
429pub mod stored_event;
431
432pub mod rumor;
434
435pub mod sending;
437
438pub mod pinned_chats;
440pub mod rail_layout;
441pub mod start_menu;
442pub mod synced_prefs;
443pub mod notify;
444pub mod push;
445pub mod wallpaper;
446pub mod requests;
447
448pub mod deletion;
450pub mod early;
451pub mod self_destruct;
452pub mod transfer;
453
454pub mod simd;
456
457pub mod calls;
459
460pub mod community;
462
463pub mod event_handler;
465
466pub use types::{Message, Attachment, Reaction, EditEntry, ImageMetadata, SiteMetadata, LoginResult, AttachmentFile, mention, extract_mentions};
468pub use profile::{Profile, ProfileFlags, SlimProfile, Status};
469pub use chat::{Chat, ChatType, ChatMetadata, SerializableChat};
470pub use compact::{CompactMessage, CompactMessageVec, NpubInterner};
471pub use state::{
472 ChatState, MY_SECRET_KEY, STATE, ENCRYPTION_KEY,
473 nostr_client, my_public_key, has_active_session,
474 set_nostr_client, set_my_public_key,
475 take_nostr_client, clear_my_public_key,
476 set_pending_bunker_setup, pending_bunker_setup, clear_pending_bunker_setup,
477 set_pending_nip55_setup, pending_nip55_setup, clear_pending_nip55_setup,
478};
479pub use crypto::{GuardedKey, GuardedSigner};
480pub use signer::{
481 SignerKind, signer_kind, set_signer_kind, is_bunker, is_keyless,
482 BUNKER_SIGNER, bunker_signer, set_bunker_signer, take_bunker_signer,
483 build_bunker_signer, prewarm_bunker, drain_bunker_state,
484 parse_bunker_remote_pubkey, parse_bunker_relays,
485 BunkerConnectionState, bunker_state, set_bunker_state,
486 VectorAuthUrlHandler, attempt_bunker_login, WatchedBunkerSigner,
487 vector_metadata, build_nostrconnect_uri, build_nostrconnect_session,
488 VECTOR_APP_NAME, VECTOR_APP_URL, VECTOR_APP_ICON,
489};
490pub use nip55::{
491 Nip55Backend, Nip55Error, Nip55ResolverOutcome, Nip55Signer, Nip55State,
492 set_nip55_backend, nip55_backend, nip55_state, set_nip55_state, drain_nip55_state,
493 nip55_is_installed, nip55_pair, nip55_perms_json,
494 VECTOR_NIP55_SIGN_KINDS, VECTOR_NIP55_ENCRYPT_TYPES,
495};
496pub use nip07::{Nip07Backend, Nip07Signer, set_nip07_backend, nip07_backend, nip07_get_public_key};
497pub use error::{DownloadError, VectorError, Result};
498
499#[derive(Debug, Clone, Copy)]
501pub enum DownloadStep {
502 Received { bytes: u64, total: Option<u64> },
505 Opening,
507}
508pub use traits::{EventEmitter, NoOpEmitter, set_event_emitter, emit_event};
509pub use db::{set_app_data_dir, get_app_data_dir};
510pub use sending::{SendCallback, NoOpSendCallback, SendConfig, SendResult};
511pub use deletion::{delete_own_dm, delete_received_dm, DeleteOutcome};
512pub use stored_event::{StoredEvent, StoredEventBuilder, SystemEventType};
513pub use rumor::{RumorEvent, RumorContext, ConversationType, RumorProcessingResult, process_rumor};
514pub use profile::{SyncPriority, ProfileSyncHandler, NoOpProfileSyncHandler};
515pub use event_handler::{InboundEventHandler, LiveOnly, NoOpEventHandler, PreparedEvent, process_event};
516
517use std::path::PathBuf;
518use std::sync::Arc;
519
520pub struct CoreConfig {
526 pub data_dir: PathBuf,
528 pub event_emitter: Option<Box<dyn EventEmitter>>,
530}
531
532#[derive(Clone, Copy)]
554pub struct VectorCore;
555
556#[derive(Debug, Clone)]
563#[non_exhaustive]
564pub struct PostOptions {
565 pub reply_to: Option<String>,
567 pub expires_in_secs: Option<u64>,
569 pub bot: Option<String>,
571 pub caption: Option<String>,
573 pub compress: bool,
576}
577
578impl Default for PostOptions {
579 fn default() -> Self {
580 PostOptions { reply_to: None, expires_in_secs: None, bot: None, caption: None, compress: true }
581 }
582}
583
584impl PostOptions {
585 pub fn compress(mut self, on: bool) -> Self {
586 self.compress = on;
587 self
588 }
589
590 pub fn reply_to(mut self, message_id: impl Into<String>) -> Self {
591 self.reply_to = Some(message_id.into());
592 self
593 }
594
595 pub fn expires_in(mut self, secs: u64) -> Self {
596 self.expires_in_secs = Some(secs);
597 self
598 }
599
600 pub fn to_bot(mut self, bot: impl Into<String>) -> Self {
601 self.bot = Some(bot.into());
602 self
603 }
604
605 pub fn caption(mut self, text: impl Into<String>) -> Self {
606 self.caption = Some(text.into());
607 self
608 }
609}
610
611pub(crate) async fn ready_to_send(bytes: Vec<u8>, filename: &str, compress: bool) -> Result<(Vec<u8>, String)> {
616 if !compress || image::guess_format(&bytes).is_err() || crate::svg::looks_like_svg(&bytes) {
617 return Ok((bytes, filename.to_string()));
618 }
619 let prepared = crate::rt::spawn_blocking(move || {
620 crate::image_prep::prepare(&bytes, crate::image_prep::ImageUse::Photo).or_else(|e| crate::image_prep::strip(&bytes).ok_or(e))
621 })
622 .await
623 .map_err(|e| VectorError::Other(format!("image: {e}")))?
624 .map_err(|e| VectorError::Other(format!("{e}; send it uncompressed to share it as it is")))?;
625 let path = std::path::Path::new(filename);
626 let same = path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
627 let e = e.to_ascii_lowercase();
628 e == prepared.extension || (prepared.extension == "jpg" && e == "jpeg")
629 });
630 let name = if same { filename.to_string() } else { path.with_extension(prepared.extension).to_string_lossy().into_owned() };
631 Ok((prepared.bytes, name))
632}
633
634#[derive(Debug, Clone, Default)]
636#[non_exhaustive]
637pub struct NewCommunity {
638 pub description: Option<String>,
639 pub first_channel: Option<String>,
641 pub relays: Vec<String>,
643}
644
645impl NewCommunity {
646 pub fn description(mut self, text: impl Into<String>) -> Self {
647 self.description = Some(text.into());
648 self
649 }
650
651 pub fn first_channel(mut self, name: impl Into<String>) -> Self {
652 self.first_channel = Some(name.into());
653 self
654 }
655
656 pub fn relays(mut self, relays: impl IntoIterator<Item = impl Into<String>>) -> Self {
657 self.relays = relays.into_iter().map(Into::into).collect();
658 self
659 }
660}
661
662#[derive(Debug, Clone, Default)]
664#[non_exhaustive]
665pub struct NewChannel {
666 pub private: bool,
668 pub category_id: Option<String>,
669 pub view: Option<String>,
671 pub topic: Option<String>,
672}
673
674impl NewChannel {
675 pub fn private(mut self) -> Self {
676 self.private = true;
677 self
678 }
679
680 pub fn in_category(mut self, category_id: impl Into<String>) -> Self {
681 self.category_id = Some(category_id.into());
682 self
683 }
684
685 pub fn view(mut self, view: impl Into<String>) -> Self {
686 self.view = Some(view.into());
687 self
688 }
689
690 pub fn topic(mut self, topic: impl Into<String>) -> Self {
691 self.topic = Some(topic.into());
692 self
693 }
694}
695
696#[derive(Debug, Clone, serde::Serialize)]
698#[non_exhaustive]
699pub struct LinkPreview {
700 pub community_id: String,
701 pub name: String,
702 pub description: Option<String>,
703 pub icon: Option<crate::community::CommunityImage>,
705 pub joined: bool,
707 pub verified: bool,
710}
711
712enum LiveRoute {
714 Dm,
715 CommunityV2,
716}
717
718const EVERY_RELAY: &str = "*";
720
721#[derive(Default)]
723struct Owed {
724 session: u64,
725 communities: bool,
726 dms: bool,
727 relays: std::collections::HashMap<String, u64>,
728 running: bool,
729}
730
731static CATCH_UPS: std::sync::LazyLock<std::sync::Mutex<Owed>> = std::sync::LazyLock::new(Default::default);
733
734#[derive(Debug, Clone, Copy, PartialEq, Eq)]
736pub enum CatchUp {
737 Inline,
742 External,
745}
746
747const BACKFILL_CONTINUATIONS: usize = 3;
749
750#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
757pub struct BackfillCount {
758 pub fetched: usize,
759 pub new_messages: usize,
760 pub next_before: Option<u64>,
763 pub unreachable: bool,
765}
766
767impl VectorCore {
768 pub fn init(config: CoreConfig) -> Result<Self> {
770 db::set_app_data_dir(config.data_dir);
772
773 if let Some(emitter) = config.event_emitter {
775 traits::set_event_emitter(emitter);
776 }
777
778 #[cfg(not(target_arch = "wasm32"))]
780 let _ = rustls::crypto::ring::default_provider().install_default();
781
782 net::raise_fd_limit();
783
784 Ok(VectorCore)
785 }
786
787 pub fn accounts(&self) -> Result<Vec<String>> {
789 db::get_accounts().map_err(VectorError::from)
790 }
791
792 pub async fn login(&self, key: &str, password: Option<&str>) -> Result<LoginResult> {
794 use nostr_sdk::prelude::*;
795
796 let keys = if key.starts_with("nsec1") {
798 let secret = SecretKey::from_bech32(key)
799 .map_err(|e| VectorError::Nostr(format!("Invalid nsec: {}", e)))?;
800 Keys::new(secret)
801 } else {
802 Keys::from_mnemonic(key, None)
804 .map_err(|e| VectorError::Nostr(format!("Key derivation failed: {}", e)))?
805 };
806
807 let public_key = keys.public_key();
808 let npub = public_key.to_bech32()
809 .map_err(|e| VectorError::Nostr(format!("Failed to encode npub: {}", e)))?;
810
811 let secret_bytes = keys.secret_key().to_secret_bytes();
813 state::MY_SECRET_KEY.set(secret_bytes, &[&state::ENCRYPTION_KEY]);
814 state::set_my_public_key(public_key);
815
816 db::set_current_account(npub.clone())?;
818 db::init_database(&npub)?;
819
820 {
822 let nsec = keys.secret_key().to_bech32()
823 .map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))?;
824 *state::PENDING_NSEC.lock().unwrap() = Some(nsec.clone());
825
826 let existing_encrypted = db::get_pkey().ok().flatten().is_some_and(|v| !v.starts_with("nsec1"));
833 if !(state::resolve_encryption_enabled_from_db() && existing_encrypted) {
834 db::set_pkey(&nsec)?;
835 }
836 }
837
838 let has_encryption = state::resolve_encryption_enabled_from_db();
841
842 if has_encryption {
843 if let Some(pwd) = password {
844 let kdf = crate::crypto::Kdf::of_account().map_err(VectorError::Crypto)?;
849 let key = zeroize::Zeroizing::new(crate::crypto::derive_key(pwd, &kdf).await);
850 crate::crypto::install_unlocked_key(&key, &kdf).map_err(VectorError::Crypto)?;
851 }
852 }
853 state::init_encryption_enabled();
856
857 let client = crate::nostr_client_builder()
860 .monitor(Monitor::new(1024))
862 .build();
863
864 for relay in state::TRUSTED_RELAYS {
866 client.add_managed_relay(*relay).await.ok();
867 }
868
869 client.connect().await;
871
872 let _ = { state::set_nostr_client(client); Ok::<(), ()>(()) };
873
874 Ok(LoginResult { npub, has_encryption })
875 }
876
877 pub fn generate_nsec(&self) -> Result<String> {
880 use nostr_sdk::prelude::*;
881 Keys::generate().secret_key().to_bech32()
882 .map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))
883 }
884
885 pub async fn send_dm(&self, to_npub: &str, content: &str) -> Result<sending::SendResult> {
890 let config = SendConfig { self_send: false, ..SendConfig::headless() };
891 sending::send_dm(to_npub, content, None, &config, Arc::new(NoOpSendCallback)).await
892 .map_err(VectorError::Other)
893 }
894
895 pub async fn send_dm_reply(&self, to_npub: &str, replied_to: &str, content: &str) -> Result<sending::SendResult> {
897 let config = SendConfig { self_send: false, ..SendConfig::headless() };
898 sending::send_dm(to_npub, content, Some(replied_to), &config, Arc::new(NoOpSendCallback)).await
899 .map_err(VectorError::Other)
900 }
901
902 pub async fn download_attachment(&self, attachment: &Attachment) -> Result<Vec<u8>> {
909 self.download_attachment_from(attachment, None).await
910 }
911
912 pub async fn download_attachment_from(
917 &self,
918 attachment: &Attachment,
919 author_npub: Option<&str>,
920 ) -> Result<Vec<u8>> {
921 self.download_attachment_within(attachment, author_npub, 256 * 1024 * 1024)
922 .await
923 .map_err(|e| VectorError::Other(e.to_string()))
924 }
925
926 pub async fn download_attachment_within(
930 &self,
931 attachment: &Attachment,
932 author_npub: Option<&str>,
933 max_bytes: usize,
934 ) -> std::result::Result<Vec<u8>, DownloadError> {
935 self.download_attachment_reporting(attachment, author_npub, max_bytes, |_| true).await
936 }
937
938 pub async fn download_attachment_reporting<F: FnMut(DownloadStep) -> bool>(
942 &self,
943 attachment: &Attachment,
944 author_npub: Option<&str>,
945 max_bytes: usize,
946 mut step: F,
947 ) -> std::result::Result<Vec<u8>, DownloadError> {
948 use futures_util::StreamExt;
949 let max_download = max_bytes;
950 if attachment.url.is_empty() {
951 return Err(DownloadError::Unusable("attachment has no URL".into()));
952 }
953 let client = crate::net::build_http_client_with_options(
955 None,
956 Some(crate::net::transfer_stall()),
957 true,
958 )
959 .map_err(DownloadError::Unreachable)?;
960 let mut last_err = String::from("download failed");
961 let mut network_waits = 0u8;
964 let mut all_answered = true;
966 let mut candidates: Vec<String> = vec![attachment.url.clone()];
967 candidates.extend(attachment.fallback_urls.iter().cloned());
968 let mut hash_swap_tried = false;
969 let mut i = 0;
970 'sources: while i < candidates.len() {
971 let url = candidates[i].clone();
972 i += 1;
973 let extend_with_swap = |candidates: &mut Vec<String>, servers: &[String]| {
976 let extra = crate::blossom::hash_swap_candidates(&attachment.url, servers);
977 for c in extra {
978 if !candidates.contains(&c) {
979 candidates.push(c);
980 }
981 }
982 };
983 macro_rules! next_source {
984 () => {{
985 log_net_fail!("[Download] source failed ({}): {}", url, last_err);
986 if i == candidates.len() && !hash_swap_tried {
987 hash_swap_tried = true;
988 let servers = crate::blossom_servers::author_swap_servers(author_npub, false).await;
989 extend_with_swap(&mut candidates, &servers);
990 }
991 continue 'sources;
992 }};
993 }
994 if let Err(e) = crate::net::validate_url_not_private(&url) {
998 last_err = e.to_string();
999 next_source!();
1000 }
1001 macro_rules! network_changed {
1002 ($e:expr) => {{
1003 if $e.is_transient() && network_waits < 8 {
1004 network_waits += 1;
1005 match crate::net::wait_after(&$e).await {
1006 Ok(()) => {
1007 i -= 1;
1008 continue 'sources;
1009 }
1010 Err(text) => return Err(DownloadError::Unreachable(text)),
1012 }
1013 }
1014 }};
1015 }
1016 let resp = match crate::net::proxied_request(&client, reqwest::Method::GET, &url).await.send().await {
1017 Ok(r) => r,
1018 Err(e) => {
1019 network_changed!(e);
1020 last_err = format!("download: {e}");
1021 all_answered = false;
1022 next_source!();
1023 }
1024 };
1025 if !resp.status().is_success() {
1026 last_err = format!("download failed: HTTP {}", resp.status());
1027 all_answered = false;
1028 next_source!();
1029 }
1030 let mut encrypted: Vec<u8> = Vec::with_capacity(
1033 resp.content_length().map(|l| usize::try_from(l).unwrap_or(usize::MAX).min(max_download).min(4 * 1024 * 1024)).unwrap_or(64 * 1024),
1035 );
1036 let total = resp.content_length();
1037 if !step(DownloadStep::Received { bytes: 0, total }) {
1038 return Err(DownloadError::Cancelled);
1039 }
1040 let mut stream = resp.bytes_stream();
1041 loop {
1042 if total.is_some_and(|t| encrypted.len() as u64 >= t) {
1044 break;
1045 }
1046 #[cfg(target_arch = "wasm32")]
1048 let next = match crate::rt::time::timeout(crate::transport::budget(crate::transport::Op::HttpRead, crate::net::transfer_stall()), stream.next()).await {
1049 Ok(next) => next,
1050 Err(_) => {
1051 last_err = "read body: stalled".to_string();
1052 all_answered = false;
1053 next_source!();
1054 }
1055 };
1056 #[cfg(not(target_arch = "wasm32"))]
1057 let next = stream.next().await;
1058 let Some(chunk) = next else { break };
1059 let chunk = match chunk {
1060 Ok(c) => c,
1061 Err(e) => {
1062 network_changed!(e);
1063 last_err = format!("read body: {e}");
1064 all_answered = false;
1065 next_source!();
1066 }
1067 };
1068 if encrypted.len() + chunk.len() > max_download {
1069 return Err(DownloadError::TooLarge(max_download));
1070 }
1071 encrypted.extend_from_slice(&chunk);
1072 if !step(DownloadStep::Received { bytes: encrypted.len() as u64, total }) {
1073 return Err(DownloadError::Cancelled);
1074 }
1075 }
1076 if !step(DownloadStep::Opening) {
1077 return Err(DownloadError::Cancelled);
1078 }
1079 if attachment.key.is_empty() || attachment.nonce.is_empty() {
1082 let hash = crate::crypto::sha256_hex(&encrypted);
1083 if crate::blossom::plaintext_matches(&url, attachment.original_hash.as_deref(), &hash) {
1084 return Ok(encrypted);
1085 }
1086 last_err = "plaintext blob fails its hash claim".to_string();
1087 next_source!();
1088 }
1089 match crate::crypto::decrypt_data_owned(encrypted, &attachment.key, &attachment.nonce) {
1090 Ok(plain) => {
1091 if i > 1 {
1092 log_net_info!("[Download] fallback source {}/{} served {}", i, candidates.len(), url);
1093 }
1094 return Ok(plain);
1095 }
1096 Err(e) => {
1097 last_err = format!("decrypt: {e}");
1100 next_source!();
1101 }
1102 }
1103 }
1104 log_net_fail!("[Download] all {} source(s) failed for {}: {}", candidates.len(), attachment.url, last_err);
1105 Err(if all_answered { DownloadError::Unusable(last_err) } else { DownloadError::Unreachable(last_err) })
1106 }
1107
1108 pub async fn probe_attachment_size(&self, message_id: &str, attachment_id: &str) -> Option<u64> {
1112 crate::db::scoped(async move {
1113 let (chat_id, message) = self.get_message(message_id).await?;
1114 let att = message.attachments.iter().find(|a| a.id == attachment_id)?;
1115 if att.size > 0 {
1116 return Some(att.size);
1117 }
1118 if !(att.url.starts_with("https://") || att.url.starts_with("http://")) {
1119 return None;
1120 }
1121 if !message.mine && crate::requests::shielded() && state::STATE.lock().await.dm_unanswered(&chat_id) {
1122 return None;
1123 }
1124 let probe = crate::net::get_remote_file_size(&att.url);
1125 let size = crate::rt::time::timeout(crate::net::tor_http_timeout(std::time::Duration::from_secs(5)), probe).await.ok().flatten()?;
1126 if let Err(e) = db::attachments::set_attachment_size(message_id, attachment_id, size) {
1127 crate::log_warn!("[Attachments] could not record a probed size: {e}");
1128 }
1129 state::STATE.lock().await.update_attachment(&chat_id, message_id, attachment_id, |a| a.size = size);
1130 Some(size)
1131 })
1132 .await
1133 }
1134
1135 pub async fn send_file(&self, to_npub: &str, file_path: &str) -> Result<sending::SendResult> {
1137 let path = std::path::Path::new(file_path);
1138 let bytes = std::fs::read(path)
1139 .map_err(VectorError::Io)?;
1140 let filename = path.file_name()
1141 .and_then(|n| n.to_str())
1142 .unwrap_or("file");
1143 let extension = path.extension()
1144 .and_then(|e| e.to_str())
1145 .unwrap_or("bin");
1146
1147 sending::send_file_dm(
1148 to_npub,
1149 std::sync::Arc::new(bytes),
1150 filename,
1151 extension,
1152 None,
1153 None,
1154 &SendConfig::default(),
1155 Arc::new(NoOpSendCallback),
1156 ).await.map_err(VectorError::Other)
1157 }
1158
1159 pub async fn send_file_bytes(&self, to_npub: &str, bytes: Vec<u8>, filename: &str, opts: &PostOptions) -> Result<sending::SendResult> {
1163 if opts.expires_in_secs.is_some() {
1164 return Err(VectorError::Other("DMs have no per-message expiry".into()));
1165 }
1166 let (bytes, filename) = ready_to_send(bytes, filename, opts.compress).await?;
1167 let extension = std::path::Path::new(&filename).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
1168 let config = SendConfig { self_send: false, ..SendConfig::headless() };
1169 let sent = sending::send_file_dm(to_npub, std::sync::Arc::new(bytes), &filename, &extension, None, opts.reply_to.as_deref(), &config, Arc::new(NoOpSendCallback))
1170 .await
1171 .map_err(VectorError::Other)?;
1172 if let Some(caption) = opts.caption.as_deref().filter(|c| !c.trim().is_empty()) {
1174 let file_id = sent.event_id.clone().unwrap_or_else(|| sent.pending_id.clone());
1175 self.send_dm_reply(to_npub, &file_id, caption).await?;
1176 }
1177 Ok(sent)
1178 }
1179
1180 pub async fn remove_reaction(&self, reaction_id: &str) -> Result<()> {
1182 crate::db::scoped(async move {
1183 use nostr_sdk::prelude::{EventId, PublicKey, ToBech32};
1184 let session = crate::db::current_session();
1185 let (chat_id, message_id, author_npub, is_community) =
1186 Self::locate_reaction(reaction_id).await.ok_or_else(|| VectorError::NotFound(format!("reaction {reaction_id}")))?;
1187 let me = state::my_public_key().ok_or_else(|| VectorError::NotInitialized("not logged in".into()))?;
1188 if me.to_bech32().ok().as_deref() != Some(author_npub.as_str()) {
1189 return Err(VectorError::Other("only its own author can withdraw a reaction".into()));
1190 }
1191 let updated = state::STATE.lock().await.remove_reaction_from_message(&message_id, reaction_id);
1194 let _ = crate::db::events::delete_event(reaction_id).await;
1195 if let Some((_, mut message)) = updated {
1196 traits::emit_message_update(&chat_id, &message_id, &mut message).await;
1197 }
1198 if !session.is_live() {
1200 return Err(VectorError::Other("account changed while withdrawing the reaction".into()));
1201 }
1202 if is_community {
1203 use crate::community::transport::LiveTransport;
1204 let id = self.v2_community_for_channel(&chat_id)?.ok_or_else(|| VectorError::NotFound("community channel".into()))?;
1205 let community = crate::db::community::load_community_v2(&id)
1206 .map_err(VectorError::Db)?
1207 .ok_or_else(|| VectorError::NotFound("community".into()))?;
1208 let ch = crate::community::ChannelId(Self::id32(&chat_id, "channel_id")?);
1209 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1210 crate::community::v2::service::delete_own(&transport, &community, &ch, reaction_id, crate::community::v2::kind::REACTION)
1211 .await
1212 .map_err(VectorError::Other)?;
1213 } else {
1214 let rid = EventId::from_hex(reaction_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1215 let recipient = PublicKey::parse(&chat_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1216 crate::deletion::delete_own_reaction(&rid, recipient).await.map_err(VectorError::Other)?;
1217 }
1218 Ok(())
1219 })
1220 .await
1221 }
1222
1223 async fn locate_reaction(reaction_id: &str) -> Option<(String, String, String, bool)> {
1226 if let Some(found) = state::STATE.lock().await.find_reaction(reaction_id) {
1227 return Some(found);
1228 }
1229 let parent = crate::db::events::reaction_target(reaction_id).ok().flatten()?;
1230 let (chat_id, message) = crate::db::events::get_message_by_id(&parent).await.ok().flatten()?;
1231 let author = message.reactions.iter().find(|r| r.id == reaction_id)?.author_id.clone();
1232 let community = crate::db::community::community_id_for_channel(&chat_id).ok().flatten().is_some();
1233 Some((chat_id, parent, author, community))
1234 }
1235
1236 pub async fn remove_my_reaction(&self, message_id: &str, emoji: &str) -> Result<bool> {
1238 match Self::own_reaction_id(message_id, emoji).await {
1239 Some(id) => self.remove_reaction(&id).await.map(|_| true),
1240 None => Ok(false),
1241 }
1242 }
1243
1244 async fn own_reaction_id(message_id: &str, emoji: &str) -> Option<String> {
1249 use nostr_sdk::prelude::ToBech32;
1250 let me = state::my_public_key()?.to_bech32().ok()?;
1251 let resident = state::STATE.lock().await.find_message(message_id).map(|(_, m)| m);
1252 let message = match resident {
1253 Some(m) => m,
1254 None => crate::db::events::get_message_by_id(message_id).await.ok().flatten()?.1,
1255 };
1256 message.reactions.iter().find(|r| r.author_id == me && r.emoji == emoji).map(|r| r.id.clone())
1257 }
1258
1259 pub async fn send_reaction(
1264 &self,
1265 to_npub: &str,
1266 reference_id: &str,
1267 emoji: &str,
1268 emoji_url: Option<&str>,
1269 ) -> Result<String> {
1270 use nostr_sdk::prelude::*;
1271
1272 let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
1273 let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
1274
1275 if let Some(existing) = Self::own_reaction_id(reference_id, emoji).await {
1277 return Ok(existing);
1278 }
1279
1280 badges::check_new_reaction_allowance(reference_id, emoji)
1282 .await
1283 .map_err(VectorError::Other)?;
1284
1285 let reference_event = EventId::from_hex(reference_id)
1286 .map_err(|e| VectorError::Nostr(e.to_string()))?;
1287 let receiver_pubkey = PublicKey::from_bech32(to_npub)
1288 .map_err(|e| VectorError::Nostr(e.to_string()))?;
1289
1290 let custom_emoji_tag = emoji_url.and_then(|url| {
1292 if !emoji.starts_with(':') || !emoji.ends_with(':') || emoji.len() < 3 || url.is_empty() {
1293 return None;
1294 }
1295 let shortcode = &emoji[1..emoji.len() - 1];
1296 if shortcode.is_empty() { return None; }
1297 Some(Tag::custom("emoji", [shortcode.to_string(), url.to_string()]))
1298 });
1299
1300 let reaction_target = nostr_sdk::prelude::nip25::ReactionTarget {
1301 event_id: reference_event,
1302 public_key: receiver_pubkey,
1303 coordinate: None,
1304 kind: Some(Kind::PrivateDirectMessage),
1305 relay_hint: None,
1306 };
1307 let mut builder =
1308 nostr_sdk::prelude::nip25::ReactionBuilder::new(reaction_target, emoji)
1309 .into_event_builder();
1310 if let Some(tag) = custom_emoji_tag {
1311 builder = builder.tag(tag);
1312 }
1313 let rumor = builder.finalize_unsigned_with_id(my_public_key);
1314 let inner_rumor_id = rumor.id;
1315 let rumor_id = inner_rumor_id.ok_or(VectorError::Other("Failed to get rumor ID".into()))?.to_hex();
1316
1317 let outcome = inbox_relays::send_gift_wrap_retained(&client, &receiver_pubkey, rumor.clone(), [])
1321 .await.map_err(VectorError::Other)?;
1322 if !outcome.output.success.is_empty() {
1323 if let Some(rid) = inner_rumor_id {
1324 if let Err(e) = db::nip17_keys::store_wrap_key(
1325 &outcome.wrap_event_id, &rid, &receiver_pubkey,
1326 db::nip17_keys::WrapRole::Recipient,
1327 &outcome.wrap_secret, &outcome.targeted_relays,
1328 ) {
1329 crate::log_warn!("[Reaction] failed to persist wrap key: {}", e);
1330 }
1331 }
1332 }
1333
1334 let self_wrap_client = client.clone();
1337 db::spawn_bound(async move {
1338 if let Ok(self_outcome) = inbox_relays::send_gift_wrap_retained(
1339 &self_wrap_client, &my_public_key, rumor, [],
1340 ).await {
1341 if !self_outcome.output.success.is_empty() {
1342 if let Some(rid) = inner_rumor_id {
1343 let _ = db::nip17_keys::store_wrap_key(
1344 &self_outcome.wrap_event_id, &rid, &my_public_key,
1345 db::nip17_keys::WrapRole::SelfSend,
1346 &self_outcome.wrap_secret, &self_outcome.targeted_relays,
1347 );
1348 }
1349 }
1350 }
1351 });
1352
1353 let reaction = Reaction {
1355 id: rumor_id.clone(),
1356 reference_id: reference_id.to_string(),
1357 author_id: my_public_key.to_bech32().unwrap_or_else(|_| my_public_key.to_hex()),
1358 emoji: emoji.to_string(),
1359 emoji_url: emoji_url.map(|s| s.to_string()),
1360 };
1361 let msg_for_save = {
1362 let mut st = state::STATE.lock().await;
1363 match st.add_reaction_to_message(reference_id, reaction) {
1364 Some((cid, true)) => st.find_message(reference_id).map(|(_, m)| (cid, m)),
1365 _ => None,
1366 }
1367 };
1368 if let Some((cid, mut msg)) = msg_for_save {
1369 let _ = db::events::save_message(&cid, &msg).await;
1370 traits::emit_message_update(&cid, reference_id, &mut msg).await;
1371 }
1372
1373 Ok(rumor_id)
1374 }
1375
1376 pub async fn send_typing(&self, to_npub: &str) -> Result<()> {
1379 use nostr_sdk::prelude::*;
1380
1381 let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
1382 let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
1383 let pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
1384 if pubkey == my_public_key {
1386 return Ok(());
1387 }
1388
1389 let expiry = Timestamp::from_secs(crate::clock::timestamp().as_secs() + 30);
1390 let rumor = EventBuilder::new(Kind::ApplicationSpecificData, "typing")
1391 .tag(Tag::public_key(pubkey))
1392 .tag(Tag::custom("d", vec!["vector"]))
1393 .tag(Tag::expiration(expiry))
1394 .finalize_unsigned_with_id(my_public_key);
1395
1396 signer::active_signer().map_err(VectorError::Other)?;
1399 let wrap = signer::gift_wrap(&pubkey, rumor, [Tag::expiration(expiry)])
1401 .await
1402 .map_err(VectorError::Nostr)?;
1403 transport_aware(client.send_event(&wrap))
1404 .to(state::active_trusted_relays().await)
1405 .await
1406 .map_err(|e| VectorError::Nostr(e.to_string()))?;
1407 Ok(())
1408 }
1409
1410 pub async fn edit_dm(&self, to_npub: &str, message_id: &str, new_content: &str) -> Result<String> {
1414 crate::db::scoped(async move {
1415 use nostr_sdk::prelude::*;
1416
1417 let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
1418 let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
1419 let my_npub = my_public_key.to_bech32().map_err(|e| VectorError::Nostr(e.to_string()))?;
1420 let receiver_pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
1421 let reference_event = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1422
1423 let (plain, text_spans) = crate::text_spans::extract_own(new_content);
1424 let new_content = plain.as_str();
1425 let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
1427 let expiry_tags: Vec<Tag> = crate::self_destruct::edit_expiry(message_id)
1429 .await
1430 .map_err(VectorError::Other)?
1431 .map(|exp| Tag::expiration(Timestamp::from_secs(exp)))
1432 .into_iter()
1433 .collect();
1434
1435 let mut builder = EventBuilder::new(
1436 Kind::from_u16(stored_event::event_kind::MESSAGE_EDIT),
1437 new_content,
1438 ).tag(Tag::event(reference_event));
1439 for et in &emoji_tags {
1440 builder = builder.tag(Tag::custom(
1441 "emoji",
1442 [et.shortcode.clone(), et.url.clone()],
1443 ));
1444 }
1445 builder = builder.tags(crate::text_spans::to_nostr_tags(&text_spans));
1446 let rumor = builder.tags(expiry_tags.clone()).finalize_unsigned_with_id(my_public_key);
1447 let edit_id = rumor.id.ok_or(VectorError::Other("Failed to get edit rumor ID".into()))?.to_hex();
1448 let edit_ts_ms = rumor.created_at.as_secs() * 1000;
1449
1450 let msg_for_emit = {
1452 let mut st = state::STATE.lock().await;
1453 st.update_message_in_chat_with(to_npub, message_id, |msg, i| {
1454 msg.apply_edit(new_content.to_string(), edit_ts_ms, emoji_tags.clone(), text_spans.clone(), i);
1455 msg.set_preview_metadata(None);
1456 })
1457 };
1458 if let Some(mut msg) = msg_for_emit {
1459 traits::emit_message_update(to_npub, message_id, &mut msg).await;
1460 if let Ok(db_chat_id) = db::id_cache::get_chat_id_by_identifier(to_npub) {
1461 let _ = db::events::save_edit_event(
1462 &edit_id, message_id, new_content, &emoji_tags, &text_spans, db_chat_id, None, &my_npub,
1463 ).await;
1464 }
1465 }
1466
1467 inbox_relays::send_gift_wrap(&client, &receiver_pubkey, rumor.clone(), expiry_tags.clone())
1468 .await.map_err(VectorError::Other)?;
1469
1470 let self_wrap_client = client.clone();
1471 let self_wrap_session = crate::db::current_session();
1472 db::spawn_bound(async move {
1473 if !self_wrap_session.is_live() { return; }
1474 if let Ok(wrap) = signer::gift_wrap(&my_public_key, rumor, expiry_tags).await {
1475 let _ = crate::transport_aware(self_wrap_client.send_event(&wrap)).await;
1476 }
1477 });
1478
1479 Ok(edit_id)
1480 })
1481 .await
1482 }
1483
1484 pub async fn delete_dm(&self, message_id: &str) -> Result<deletion::DeleteOutcome> {
1487 use nostr_sdk::prelude::*;
1488 let rumor_id = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1489 let (chat_id, msg) = self.get_message(message_id).await.ok_or_else(|| VectorError::Other("message not found".into()))?;
1490 if !chat_id.starts_with("npub1") {
1491 return Err(VectorError::Other("not a DM".into()));
1492 }
1493 let outcome = if msg.mine { deletion::delete_own_dm(&rumor_id).await } else { deletion::delete_received_dm(&rumor_id).await }
1494 .map_err(VectorError::Other)?;
1495 state::STATE.lock().await.remove_message(message_id);
1496 let _ = crate::db::events::delete_event(message_id).await;
1497 traits::emit_event_json("message_removed", serde_json::json!({ "id": message_id, "chat_id": chat_id, "reason": "deleted" }));
1498 Ok(outcome)
1499 }
1500
1501 pub async fn get_chats(&self) -> Vec<SerializableChat> {
1503 let state = state::STATE.lock().await;
1504 state.chats.iter()
1505 .map(|c| c.to_serializable_with_last_n(1, &state.interner))
1506 .collect()
1507 }
1508
1509 pub async fn get_messages(&self, chat_id: &str, limit: usize, offset: usize) -> Vec<Message> {
1511 let state = state::STATE.lock().await;
1512 let Some(chat) = state.get_chat(chat_id) else { return Vec::new() };
1513 let msgs = chat.messages.messages();
1514 let start = offset.min(msgs.len());
1515 let end = offset.saturating_add(limit).min(msgs.len());
1516 msgs[start..end].iter().map(|m| m.to_message(&state.interner)).collect()
1517 }
1518
1519 pub async fn get_message(&self, message_id: &str) -> Option<(String, Message)> {
1528 {
1529 let state = state::STATE.lock().await;
1530 if let Some((chat, msg)) = state.find_message(message_id) {
1531 return Some((chat.id.clone(), msg));
1532 }
1533 }
1534 db::events::get_message_by_id(message_id).await.ok().flatten()
1535 }
1536
1537 pub async fn get_messages_with_attachment(&self, content_hash: &str) -> Vec<(String, Message)> {
1546 let Ok(ids) = db::attachments::events_with_attachment_hash(content_hash) else { return Vec::new() };
1547 let mut out = Vec::with_capacity(ids.len());
1548 for id in ids {
1549 if let Some(found) = self.get_message(&id).await {
1550 out.push(found);
1551 }
1552 }
1553 out
1554 }
1555
1556 pub async fn get_messages_before(
1566 &self,
1567 chat_id: &str,
1568 before: Option<(u64, &str)>,
1569 limit: usize,
1570 ) -> Vec<Message> {
1571 let state = state::STATE.lock().await;
1572 let Some(chat) = state.get_chat(chat_id) else {
1573 return Vec::new();
1574 };
1575 page_before(chat.messages.messages(), &state.interner, before, limit)
1576 }
1577
1578 pub async fn get_profile(&self, npub: &str) -> Option<SlimProfile> {
1580 let state = state::STATE.lock().await;
1581 state.get_profile(npub)
1582 .map(|p| SlimProfile::from_profile(p, &state.interner))
1583 }
1584
1585 pub async fn load_profile(&self, npub: &str) -> bool {
1587 profile::sync::load_profile(npub.to_string(), &NoOpProfileSyncHandler).await
1588 }
1589
1590 pub async fn update_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
1592 profile::sync::update_profile(
1593 name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
1594 &NoOpProfileSyncHandler,
1595 ).await
1596 }
1597
1598 pub async fn update_bot_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
1601 profile::sync::update_bot_profile(
1602 name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
1603 &NoOpProfileSyncHandler,
1604 ).await
1605 }
1606
1607 pub async fn set_stream_consent(&self, on: bool) -> Result<bool> {
1610 db::scoped_result(profile::sync::set_stream_consent(on, &NoOpProfileSyncHandler))
1611 .await
1612 .map_err(VectorError::Other)
1613 }
1614
1615 pub async fn update_status(&self, status: &str) -> bool {
1617 profile::sync::update_status(status.to_string()).await
1618 }
1619
1620 pub async fn upload_public_image(&self, file_path: &str) -> Result<String> {
1626 let path = std::path::Path::new(file_path);
1627 let bytes = std::fs::read(path).map_err(VectorError::Io)?;
1628 if bytes.is_empty() {
1629 return Err(VectorError::Other("Empty image file".into()));
1630 }
1631 let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
1632 let mime = crate::crypto::mime_from_extension(&extension);
1633 let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
1634 let signer = crate::signer::active_signer()
1635 .map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
1636 let servers = crate::blossom_servers::compute_enabled_servers();
1637 if servers.is_empty() {
1638 return Err(VectorError::Other("No Blossom servers configured".into()));
1639 }
1640 crate::blossom::upload_blob_with_failover(
1643 signer,
1644 servers,
1645 std::sync::Arc::new(bytes),
1646 Some(mime),
1647 Some(crate::net::tor_http_timeout(std::time::Duration::from_secs(20))),
1648 )
1649 .await
1650 .map_err(VectorError::Other)
1651 }
1652
1653 pub async fn block_user(&self, npub: &str) -> bool {
1655 profile::sync::block_user(npub.to_string(), &NoOpProfileSyncHandler).await
1656 }
1657
1658 pub async fn unblock_user(&self, npub: &str) -> bool {
1660 profile::sync::unblock_user(npub.to_string(), &NoOpProfileSyncHandler).await
1661 }
1662
1663 pub async fn set_nickname(&self, npub: &str, nickname: &str) -> bool {
1665 profile::sync::set_nickname(npub.to_string(), nickname.to_string(), &NoOpProfileSyncHandler).await
1666 }
1667
1668 pub async fn get_blocked_users(&self) -> Vec<SlimProfile> {
1670 profile::sync::get_blocked_users().await
1671 }
1672
1673 pub fn queue_profile_sync(&self, npub: &str, priority: SyncPriority) {
1675 profile::sync::queue_profile_sync(npub.to_string(), priority, false);
1676 }
1677
1678 pub fn my_npub(&self) -> Option<String> {
1680 state::my_public_key()
1681 .and_then(|pk| ToBech32::to_bech32(&pk).ok())
1682 }
1683
1684 pub async fn list_communities(&self) -> Vec<serde_json::Value> {
1691 let ids = crate::db::community::list_community_ids().unwrap_or_default();
1692 let me = state::my_public_key();
1693 let mut out = Vec::new();
1694 for id in ids {
1695 let Ok(Some(c)) = crate::db::community::load_community_v2(&id) else { continue };
1696 let is_owner = me.is_some_and(|m| c.owner().is_ok_and(|o| o == m));
1697 out.push(serde_json::json!({
1698 "community_id": crate::simd::hex::bytes_to_hex_32(&c.identity.community_id.0),
1699 "version": 2,
1700 "name": c.name,
1701 "description": c.description,
1702 "is_owner": is_owner,
1703 "dissolved": c.dissolved,
1708 "channels": c.layout().1.into_iter()
1714 .map(|(ch, cat)| serde_json::json!({
1715 "channel_id": crate::simd::hex::bytes_to_hex_32(&ch.id.0),
1716 "name": ch.name,
1717 "private": ch.private,
1718 "readable": !(ch.private && ch.key.is_none()),
1719 "epoch": ch.epoch.0,
1720 "category_id": cat.map(|k| crate::simd::hex::bytes_to_hex_32(&k.id)),
1721 "topic": ch.topic(),
1722 "view": ch.view().as_str(),
1723 }))
1724 .collect::<Vec<_>>(),
1725 "categories": Self::categories_json(&c),
1726 }));
1727 }
1728 out
1729 }
1730
1731 pub async fn create_community_v2(&self, name: &str) -> Result<serde_json::Value> {
1735 self.create_community_with(name, &NewCommunity::default()).await
1736 }
1737
1738 pub async fn create_community_with(&self, name: &str, opts: &NewCommunity) -> Result<serde_json::Value> {
1741 use crate::community::{v2::service as v2, transport::LiveTransport};
1742 let relays: Vec<String> = if opts.relays.is_empty() {
1743 crate::state::active_trusted_relays().await.iter().map(|s| s.to_string()).collect()
1744 } else {
1745 crate::community::v2::service::clean_relays(&[], &opts.relays).map_err(VectorError::Other)?
1746 };
1747 if relays.is_empty() {
1748 return Err(VectorError::Other("no relays available to host the Community".into()));
1749 }
1750 let session = crate::db::current_session();
1751 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1752 let mut community = v2::create_community_on_roles_v2(&transport, name, relays, opts.description.clone())
1753 .await
1754 .map_err(VectorError::Other)?;
1755 if !session.is_live() {
1756 return Err(VectorError::Other("account changed while creating the community".into()));
1757 }
1758 self.register_v2_chats(&community, &session).await;
1759 if let Some(first) = opts.first_channel.as_deref().map(str::trim).filter(|n| !n.is_empty() && *n != "general") {
1762 if let Some(ch) = community.channels.first().cloned() {
1763 let mut meta = ch.metadata();
1765 meta.name = first.to_string();
1766 match v2::edit_channel_metadata(&transport, &community, &ch.id, &meta).await {
1767 Ok(()) => {
1768 if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
1769 community = fresh;
1770 if session.is_live() {
1771 self.register_v2_chats(&community, &session).await;
1772 }
1773 }
1774 }
1775 Err(e) => crate::log_warn!("[v2:create] the first channel keeps the name general: {e}"),
1776 }
1777 }
1778 }
1779 if let Some(client) = state::nostr_client() {
1781 crate::community::v2::realtime::refresh_subscription(&client).await;
1782 }
1783 Ok(Self::v2_summary(&community))
1784 }
1785
1786 fn v2_community_for_channel(&self, channel_id: &str) -> Result<Option<crate::community::CommunityId>> {
1790 let Some(cid_hex) = crate::db::community::community_id_for_channel(channel_id).map_err(VectorError::Other)? else {
1791 return Ok(None);
1792 };
1793 let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
1794 Ok(crate::db::community::community_held(&cid).map_err(VectorError::Other)?.then_some(cid))
1795 }
1796
1797 fn v2_summary(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
1799 let me = state::my_public_key();
1800 let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
1801 serde_json::json!({
1802 "community_id": crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0),
1803 "version": 2,
1804 "name": community.name,
1805 "description": community.description,
1806 "is_owner": is_owner,
1807 "primary_channel": community.primary_channel().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)),
1812 "channels": community.layout().1.into_iter()
1813 .map(|(c, cat)| serde_json::json!({
1814 "channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
1815 "name": c.name,
1816 "private": c.private,
1817 "category_id": cat.map(|k| crate::simd::hex::bytes_to_hex_32(&k.id)),
1818 "topic": c.topic(),
1819 "view": c.view().as_str(),
1820 }))
1821 .collect::<Vec<_>>(),
1822 "categories": Self::categories_json(community),
1823 })
1824 }
1825
1826 pub fn my_channel_permissions(community: &crate::community::v2::community::CommunityV2) -> std::collections::HashMap<[u8; 32], u64> {
1829 let Some(me) = state::my_public_key() else { return Default::default() };
1830 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1831 let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
1832 if roster.everyone.is_none() {
1833 return Default::default();
1834 }
1835 let owner = community.owner().ok().map(|o| o.to_hex());
1836 community
1837 .channels
1838 .iter()
1839 .map(|c| (c.id.0, roster.channel_permissions(owner.as_deref(), &me.to_hex(), &crate::simd::hex::bytes_to_hex_32(&c.id.0), c.private).0))
1840 .collect()
1841 }
1842
1843 pub fn categories_json(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
1845 community
1846 .layout()
1847 .0
1848 .into_iter()
1849 .map(|k| serde_json::json!({ "category_id": crate::simd::hex::bytes_to_hex_32(&k.id), "name": k.name }))
1850 .collect()
1851 }
1852
1853 pub async fn register_v2_chats(&self, community: &crate::community::v2::community::CommunityV2, __session: &std::sync::Arc<crate::db::Session>) {
1859 register_v2_chats_inner(community).await
1860 }
1861}
1862
1863pub(crate) async fn register_v2_chats_inner(community: &crate::community::v2::community::CommunityV2) {
1866 crate::community::v2::changes::prime(community);
1869 crate::db::scoped(async move {
1870 let owner_npub = community.owner().ok().and_then(|p| ToBech32::to_bech32(&p).ok());
1871 let me = state::my_public_key();
1872 let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
1873 let id_hex = crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0);
1874 let Some(primary) = community.primary_channel() else { return };
1877 let primary_hex = crate::simd::hex::bytes_to_hex_32(&primary.id.0);
1878 let slims = {
1883 let mut st = state::STATE.lock().await;
1884 let mut slims = Vec::new();
1885 for ch in &community.channels {
1886 let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
1887 st.upsert_community_chat(
1888 &ch_hex,
1889 &community.name,
1890 community.description.as_deref().unwrap_or(""),
1891 &id_hex,
1892 is_owner,
1893 community.icon.is_some(),
1894 owner_npub.as_deref(),
1895 Some(community.created_at_ms),
1896 community.dissolved,
1897 &ch.name,
1898 &primary_hex,
1899 );
1900 if let Some(chat) = st.chats.iter().find(|c| c.id == ch_hex) {
1901 slims.push(crate::db::chats::SlimChatDB::from_chat(chat, &st.interner));
1902 }
1903 }
1904 slims
1905 };
1906 for slim in &slims {
1908 let _ = crate::db::chats::save_slim_chat(slim);
1909 }
1910 })
1911 .await
1912}
1913
1914const RAID_REPORT_TTL_SECS: u64 = 90;
1918
1919struct RaidReportCache;
1921
1922struct PolicyReportCache;
1923struct PolicyReportGate;
1924
1925type ReportCache<T> = std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, (u64, std::sync::Arc<T>)>>>;
1926
1927fn policy_report_cache() -> ReportCache<serde_json::Value> {
1931 crate::db::current_session().scoped::<PolicyReportCache, _>()
1932}
1933
1934fn policy_report_gate() -> std::sync::Arc<std::sync::Mutex<()>> {
1935 crate::db::current_session().scoped::<PolicyReportGate, _>()
1936}
1937
1938fn raid_report_cache() -> ReportCache<crate::community::raid::RaidReport> {
1939 crate::db::current_session().scoped::<RaidReportCache, _>()
1940}
1941
1942fn report_get<T>(cache: &ReportCache<T>, cid_hex: &str, now_secs: u64) -> Option<std::sync::Arc<T>> {
1945 let mut map = cache.lock().unwrap_or_else(|e| e.into_inner());
1946 map.retain(|_, (at, _)| now_secs.saturating_sub(*at) < RAID_REPORT_TTL_SECS);
1947 map.get(cid_hex).map(|(_, report)| report.clone())
1948}
1949
1950fn report_put<T>(cache: &ReportCache<T>, cid_hex: &str, now_secs: u64, report: std::sync::Arc<T>) {
1951 let mut map = cache.lock().unwrap_or_else(|e| e.into_inner());
1952 map.retain(|_, (at, _)| now_secs.saturating_sub(*at) < RAID_REPORT_TTL_SECS);
1953 map.insert(cid_hex.to_string(), (now_secs, report));
1954}
1955
1956fn report_once<T>(
1959 cache: &ReportCache<T>,
1960 gate: &std::sync::Mutex<()>,
1961 cid_hex: &str,
1962 now_secs: u64,
1963 compute: impl FnOnce() -> Result<std::sync::Arc<T>>,
1964) -> Result<std::sync::Arc<T>> {
1965 if let Some(hit) = report_get(cache, cid_hex, now_secs) {
1966 return Ok(hit);
1967 }
1968 let _turn = gate.lock().unwrap_or_else(|e| e.into_inner());
1969 if let Some(hit) = report_get(cache, cid_hex, now_secs) {
1970 return Ok(hit);
1971 }
1972 let report = compute()?;
1973 report_put(cache, cid_hex, now_secs, report.clone());
1974 Ok(report)
1975}
1976
1977#[cfg(test)]
1978mod report_cache_tests {
1979 use super::*;
1980
1981 #[test]
1982 fn an_expired_report_goes_on_the_next_touch() {
1983 let cache: ReportCache<u32> = Default::default();
1984 report_put(&cache, "a", 1_000, std::sync::Arc::new(1));
1985 report_put(&cache, "b", 1_050, std::sync::Arc::new(2));
1986 assert_eq!(report_get(&cache, "a", 1_000 + RAID_REPORT_TTL_SECS - 1).as_deref(), Some(&1));
1987 assert_eq!(report_get(&cache, "a", 1_000 + RAID_REPORT_TTL_SECS), None, "a report is fresh for the TTL, no longer");
1988 assert_eq!(cache.lock().unwrap().len(), 1, "the lookup dropped it");
1989 report_put(&cache, "c", 1_050 + RAID_REPORT_TTL_SECS, std::sync::Arc::new(3));
1990 let map = cache.lock().unwrap();
1991 assert!(!map.contains_key("b") && map.contains_key("c"), "and so does an insert");
1992 }
1993
1994 #[test]
1995 fn callers_that_miss_together_share_one_evaluation() {
1996 let cache: ReportCache<u32> = Default::default();
1997 let gate = std::sync::Mutex::new(());
1998 let runs = std::sync::atomic::AtomicU32::new(0);
1999 std::thread::scope(|s| {
2000 for _ in 0..4 {
2001 s.spawn(|| {
2002 let got = report_once(&cache, &gate, "a", 1_000, || {
2003 runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2004 std::thread::sleep(std::time::Duration::from_millis(50));
2005 Ok(std::sync::Arc::new(7))
2006 });
2007 assert_eq!(got.unwrap().as_ref(), &7);
2008 });
2009 }
2010 });
2011 assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1);
2012 let again = report_once(&cache, &gate, "a", 1_000 + RAID_REPORT_TTL_SECS, || Ok(std::sync::Arc::new(8)));
2013 assert_eq!(again.unwrap().as_ref(), &8, "an expired report is evaluated afresh");
2014 }
2015}
2016
2017impl VectorCore {
2018 pub async fn join_community(&self, invite_url: &str) -> Result<serde_json::Value> {
2022 use crate::community::transport::LiveTransport;
2023 crate::community::v2::invite::parse_invite_link(invite_url)
2024 .map_err(|_| VectorError::Other("not a Vector invite link".into()))?;
2025 let session = crate::db::current_session();
2026 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2027 let community = crate::community::v2::service::accept_public_link(&transport, invite_url)
2028 .await
2029 .map_err(VectorError::Other)?;
2030 self.register_v2_chats(&community, &session).await;
2031 if let Some(client) = state::nostr_client() {
2032 crate::community::v2::realtime::refresh_subscription(&client).await;
2033 }
2034 if crate::community::v2::realtime::follow_worker_running() {
2039 crate::community::v2::realtime::enqueue_follow(community.id());
2040 } else {
2041 let seed_community = community.clone();
2042 db::spawn_bound(async move {
2043 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2044 if matches!(
2045 crate::community::v2::service::sync_guestbook(&transport, &seed_community).await,
2046 Ok(fresh) if !fresh.is_empty()
2047 ) {
2048 let cid_hex = crate::simd::hex::bytes_to_hex_32(&seed_community.id().0);
2049 emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
2050 }
2051 });
2052 }
2053 Ok(Self::v2_summary(&community))
2054 }
2055
2056 pub fn list_pending_invites(&self) -> Result<Vec<serde_json::Value>> {
2059 let rows = crate::db::community::list_pending_invites().map_err(VectorError::Other)?;
2060 Ok(rows
2061 .iter()
2062 .filter_map(|p| {
2063 let v2 = crate::community::v2::invite::CommunityInvite::from_bundle_json(&p.bundle_json).ok()?;
2064 Some(serde_json::json!({
2065 "community_id": p.community_id,
2066 "name": v2.name,
2067 "inviter_npub": p.inviter_npub,
2068 "version": 2,
2069 }))
2070 })
2071 .collect())
2072 }
2073
2074 pub async fn accept_pending_invite(&self, community_id: &str) -> Result<serde_json::Value> {
2078 crate::db::scoped(async move {
2079 use crate::community::transport::LiveTransport;
2080 let bundle_json = crate::db::community::get_pending_invite(community_id)
2081 .map_err(VectorError::Other)?
2082 .ok_or_else(|| VectorError::Other(format!("no pending invite for {community_id}")))?;
2083 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2084 let session = crate::db::current_session();
2085 let inviter = crate::db::community::list_pending_invites()
2087 .ok()
2088 .and_then(|rows| rows.into_iter().find(|p| p.community_id == community_id).map(|p| p.inviter_npub));
2089 let community = match crate::community::v2::service::accept_parked_invite(&transport, &bundle_json, inviter.as_deref()).await {
2101 Ok(c) => c,
2102 Err(e) if e == crate::community::v2::service::ERR_DISSOLVED => {
2103 let relays = crate::community::v2::invite::CommunityInvite::from_bundle_json(&bundle_json)
2104 .map(|i| i.relays)
2105 .unwrap_or_default();
2106 crate::community::v2::service::retire_dead_invite(&transport, community_id, &relays).await;
2107 return Err(VectorError::Other("this community has been dissolved — the invite was removed".into()));
2108 }
2109 Err(e) => return Err(VectorError::Other(e)),
2110 };
2111 self.register_v2_chats(&community, &session).await;
2112 if let Some(client) = state::nostr_client() {
2113 crate::community::v2::realtime::refresh_subscription(&client).await;
2114 }
2115 crate::community::v2::realtime::enqueue_follow(community.id());
2116 let _ = crate::db::community::delete_pending_invite(community_id);
2117 Ok(Self::v2_summary(&community))
2118 })
2119 .await
2120 }
2121
2122
2123 fn v2_community(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
2127 use crate::community::CommunityId;
2128 if community_id.len() != 64 {
2129 return Err(VectorError::Other("malformed community id".into()));
2130 }
2131 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2132 crate::db::community::load_community_v2(&cid)
2133 .map_err(VectorError::Other)?
2134 .ok_or_else(|| VectorError::Other("community not found".into()))
2135 }
2136
2137 fn channel_id_of(channel_id: &str) -> Result<crate::community::ChannelId> {
2138 crate::simd::hex::hex_to_bytes_32_checked(channel_id)
2139 .map(crate::community::ChannelId)
2140 .ok_or_else(|| VectorError::Other("malformed channel id".into()))
2141 }
2142
2143 pub async fn create_channel(&self, community_id: &str, name: &str, private: bool) -> Result<String> {
2148 use crate::community::{v2::service, transport::LiveTransport};
2149 let community = Self::v2_community(community_id)?;
2150 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2151 let id = if private {
2152 service::create_private_channel(&transport, &community, name).await
2153 } else {
2154 service::create_public_channel(&transport, &community, name).await
2155 }
2156 .map_err(VectorError::Other)?;
2157 if let Some(client) = state::nostr_client() {
2160 crate::community::v2::realtime::refresh_subscription(&client).await;
2161 }
2162 Ok(crate::simd::hex::bytes_to_hex_32(&id.0))
2163 }
2164
2165 pub async fn create_channel_with(&self, community_id: &str, name: &str, opts: &NewChannel) -> Result<String> {
2167 use crate::community::{v2::service, transport::LiveTransport};
2168 let name = name.trim();
2169 if name.is_empty() {
2170 return Err(VectorError::Other("a channel needs a name".into()));
2171 }
2172 let view = opts.view.as_deref().map(Self::view_named).transpose()?;
2173 let session = crate::db::current_session();
2174 let community = Self::v2_community(community_id)?;
2175 let category = opts.category_id.as_deref().map(|c| Self::id32(c, "category_id")).transpose()?;
2176 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2178 let id = service::create_channel_in(&transport, &community, name, opts.private, category).await.map_err(VectorError::Other)?;
2179 let channel_id = crate::simd::hex::bytes_to_hex_32(&id.0);
2180 if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
2182 if session.is_live() {
2183 self.register_v2_chats(&fresh, &session).await;
2184 }
2185 }
2186 if view.is_some() || opts.topic.is_some() {
2189 let view = view.unwrap_or(crate::community::v2::community::ChannelView::Chat).as_str();
2190 if let Err(e) = self.edit_channel_details(community_id, &channel_id, name, opts.topic.as_deref(), view).await {
2191 crate::log_warn!("[v2:create] channel {} stands without its view or topic: {e}", &channel_id[..12]);
2192 }
2193 }
2194 if let Some(client) = state::nostr_client() {
2195 crate::community::v2::realtime::refresh_subscription(&client).await;
2196 }
2197 Ok(channel_id)
2198 }
2199
2200 pub async fn preview_public_link(&self, url: &str) -> Result<LinkPreview> {
2203 use crate::community::{transport::LiveTransport, CommunityId};
2204 crate::community::v2::invite::parse_invite_link(url).map_err(|_| VectorError::Other("not a Vector invite link".into()))?;
2205 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2206 let bundle = crate::community::v2::service::fetch_public_bundle(&transport, url).await.map_err(VectorError::Other)?;
2207 let community_id = bundle.community_id.clone();
2209 if let Ok(id) = Self::id32(&community_id, "community_id") {
2210 if let Ok(Some(local)) = crate::db::community::load_community_v2(&CommunityId(id)) {
2211 return Ok(LinkPreview {
2212 community_id,
2213 name: local.name.clone(),
2214 description: local.description.clone(),
2215 icon: local.icon.as_ref().map(|i| i.to_community_image()),
2216 joined: true,
2217 verified: true,
2218 });
2219 }
2220 }
2221 let (folded, verified) = crate::community::v2::service::preview_bundle_checked(&transport, &bundle).await.map_err(VectorError::Other)?;
2222 Ok(LinkPreview {
2223 community_id,
2224 name: folded.name.clone(),
2225 description: folded.description.clone(),
2226 icon: folded.icon.as_ref().map(|i| i.to_community_image()),
2227 joined: false,
2228 verified,
2229 })
2230 }
2231
2232 pub async fn rename_channel(&self, community_id: &str, channel_id: &str, name: &str) -> Result<()> {
2235 use crate::community::{v2::service, transport::LiveTransport};
2236 let community = Self::v2_community(community_id)?;
2237 let id = Self::channel_id_of(channel_id)?;
2238 let mut meta = community
2239 .channel(&id)
2240 .ok_or_else(|| VectorError::Other("unknown channel".into()))?
2241 .metadata();
2242 meta.name = name.to_string();
2243 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2244 service::edit_channel_metadata(&transport, &community, &id, &meta)
2245 .await
2246 .map_err(VectorError::Other)
2247 }
2248
2249 pub async fn delete_channel(&self, community_id: &str, channel_id: &str) -> Result<()> {
2252 use crate::community::{v2::service, transport::LiveTransport};
2253 let community = Self::v2_community(community_id)?;
2254 let id = Self::channel_id_of(channel_id)?;
2255 let name = community.channel(&id).map(|c| c.name.clone()).unwrap_or_default();
2256 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2257 service::delete_channel(&transport, &community, &id, &name)
2258 .await
2259 .map_err(VectorError::Other)
2260 }
2261
2262 pub async fn grant_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
2265 use crate::community::{v2::service, transport::LiveTransport};
2266 let community = Self::v2_community(community_id)?;
2267 let id = Self::channel_id_of(channel_id)?;
2268 let member = nostr_sdk::prelude::PublicKey::parse(npub)
2269 .map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
2270 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2271 service::grant_channel_access(&transport, &community, &id, &member)
2272 .await
2273 .map_err(VectorError::Other)
2274 }
2275
2276 pub async fn revoke_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
2280 use crate::community::{v2::service, transport::LiveTransport};
2281 let community = Self::v2_community(community_id)?;
2282 let id = Self::channel_id_of(channel_id)?;
2283 let member = nostr_sdk::prelude::PublicKey::parse(npub)
2284 .map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
2285 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2286 service::revoke_channel_access(&transport, &community, &id, &member)
2287 .await
2288 .map_err(VectorError::Other)
2289 }
2290
2291 pub fn member_can_read_channel(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<bool> {
2314 use nostr_sdk::prelude::PublicKey;
2315 let community = Self::v2_community(community_id)?;
2316 let id = Self::channel_id_of(channel_id)?;
2317 let ch = community.channel(&id).ok_or_else(|| VectorError::Other("unknown channel".into()))?;
2318 let who = PublicKey::parse(npub).map_err(|_| VectorError::Other(format!("invalid npub: {npub}")))?.to_hex();
2319 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
2320 if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&who) {
2321 return Ok(false);
2322 }
2323 if !ch.private {
2324 return Ok(true);
2325 }
2326 if community.owner().map(|o| o.to_hex()) == Ok(who.clone()) {
2327 return Ok(true);
2328 }
2329 let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
2330 let access_ids = roster.channel_role_ids(&crate::simd::hex::bytes_to_hex_32(&id.0));
2331 Ok(roster
2332 .grants
2333 .iter()
2334 .filter(|g| g.member == who)
2335 .any(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid))))
2336 }
2337
2338 pub fn channel_access(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
2339 use nostr_sdk::prelude::{PublicKey, ToBech32};
2340 let community = Self::v2_community(community_id)?;
2341 let id = Self::channel_id_of(channel_id)?;
2342 let ch = community
2343 .channel(&id)
2344 .ok_or_else(|| VectorError::Other("unknown channel".into()))?;
2345 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
2348 let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
2349 let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
2350 let chan_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
2351 let owner_hex = community.owner().ok().map(|o| o.to_hex());
2352 let (roles, members): (Vec<serde_json::Value>, Vec<String>) = if roster.everyone.is_some() {
2353 use crate::community::roles::{OverwriteTarget, Permissions};
2355 let scope = roster.syncs.get(&chan_hex).cloned().unwrap_or_else(|| chan_hex.clone());
2356 let roles = roster
2357 .overwrites
2358 .iter()
2359 .filter(|o| o.scope == scope && o.allow.contains(Permissions::VIEW_CHANNEL))
2360 .filter_map(|o| match &o.target {
2361 OverwriteTarget::Role(id) => roster.role(id).map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name })),
2362 _ => None,
2363 })
2364 .collect();
2365 let mut named: Vec<String> = roster.grants.iter().map(|g| g.member.clone()).collect();
2366 named.extend(roster.overwrites.iter().filter_map(|o| match &o.target {
2367 OverwriteTarget::Member(m) => Some(m.clone()),
2368 _ => None,
2369 }));
2370 named.sort();
2371 named.dedup();
2372 let members = named
2373 .into_iter()
2374 .filter(|m| !banned.contains(m) && Some(m) != owner_hex.as_ref() && roster.is_entitled(owner_hex.as_deref(), m, &chan_hex, &[], &[]))
2375 .filter_map(|m| PublicKey::from_hex(&m).ok().and_then(|pk| pk.to_bech32().ok()))
2376 .collect();
2377 (roles, members)
2378 } else {
2379 let access_ids = roster.channel_role_ids(&chan_hex);
2380 let roles = roster
2381 .channel_roles(&chan_hex)
2382 .into_iter()
2383 .map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name }))
2384 .collect();
2385 let members = roster
2386 .grants
2387 .iter()
2388 .filter(|g| !banned.contains(&g.member))
2389 .filter(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid)))
2390 .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
2391 .collect();
2392 (roles, members)
2393 };
2394 Ok(serde_json::json!({
2395 "channel_id": chan_hex,
2396 "private": ch.private,
2397 "readable": !(ch.private && ch.key.is_none()),
2398 "owner": community.owner().ok().and_then(|o| o.to_bech32().ok()),
2399 "roles": roles,
2400 "members": members,
2401 }))
2402 }
2403
2404 pub async fn create_public_invite(
2408 &self,
2409 community_id: &str,
2410 expires_at_ms: Option<u64>,
2411 label: Option<String>,
2412 ) -> Result<String> {
2413 use crate::community::CommunityId;
2414 if community_id.len() != 64 {
2415 return Err(VectorError::Other("malformed community id".into()));
2416 }
2417 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2418 let community = crate::db::community::load_community_v2(&cid)
2419 .map_err(VectorError::Other)?
2420 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2421 let base = crate::community::v2::invite::INVITE_URL_BASE.trim_end_matches("/invite");
2423 let label = Some(crate::community::v2::invite::resolve_invite_label(community_id, label).map_err(VectorError::Other)?);
2424 let minted = crate::community::v2::service::mint_public_link_sync_later(&community, base, expires_at_ms, label)
2425 .await
2426 .map_err(VectorError::Other)?;
2427 Ok(minted.url)
2428 }
2429
2430 pub async fn invite_to_community(&self, community_id: &str, invitee_npub: &str) -> Result<serde_json::Value> {
2433 crate::db::scoped(async move {
2434 use crate::community::CommunityId;
2435
2436 let my_pk = crate::state::my_public_key()
2437 .ok_or_else(|| VectorError::Other("Public key not set".into()))?;
2438
2439 if community_id.len() != 64 {
2440 return Err(VectorError::Other("malformed community id".into()));
2441 }
2442 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2443 let recipient = nostr_sdk::prelude::PublicKey::parse(invitee_npub)
2447 .map_err(|e| VectorError::Other(format!("bad invitee npub: {e}")))?;
2448 let client = crate::state::nostr_client().ok_or_else(|| VectorError::Other("Not connected".into()))?;
2449 let bundle = {
2457 let lock = crate::community::v2::realtime::follow_lock(&cid);
2458 let _rotation = lock.lock().await;
2459 let community = crate::db::community::load_community_v2(&cid)
2460 .map_err(VectorError::Other)?
2461 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2462 crate::community::v2::service::bundle_of(
2463 &community,
2464 crate::community::v2::service::BundleAudience::Member(recipient),
2465 Some(my_pk),
2466 None,
2467 None,
2468 )
2469 };
2470 let bundle_json = serde_json::to_string(&bundle).map_err(|e| VectorError::Other(e.to_string()))?;
2471 let expires_at = crate::clock::timestamp().as_secs()
2473 + crate::community::v2::invite::DIRECT_INVITE_EXPIRY_SECS;
2474 let expiry_tag = nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(expires_at));
2475 let rumor = nostr_sdk::prelude::EventBuilder::new(
2476 nostr_sdk::prelude::Kind::Custom(crate::community::v2::kind::DIRECT_INVITE),
2477 bundle_json,
2478 )
2479 .tag(expiry_tag.clone())
2480 .finalize_unsigned_with_id(my_pk);
2481 let k_tag = nostr_sdk::prelude::Tag::custom(
2482 "k",
2483 [crate::community::v2::kind::DIRECT_INVITE.to_string()],
2484 );
2485 crate::inbox_relays::send_gift_wrap(&client, &recipient, rumor, [k_tag, expiry_tag])
2486 .await
2487 .map_err(VectorError::Other)?;
2488 Ok(serde_json::json!({ "invited": invitee_npub, "version": 2 }))
2489 })
2490 .await
2491 }
2492
2493 pub fn list_public_invites(&self, community_id: &str) -> Result<Vec<crate::db::community::PublicInviteRecord>> {
2498 crate::db::community::list_public_invites(community_id).map_err(VectorError::Other)
2499 }
2500
2501 pub async fn revoke_public_invite(&self, community_id: &str, token: &str) -> Result<()> {
2506 use crate::community::{transport::LiveTransport, CommunityId};
2507 if community_id.len() != 64 {
2508 return Err(VectorError::Other("malformed community id".into()));
2509 }
2510 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2511 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2512 let community = crate::db::community::load_community_v2(&cid)
2515 .map_err(VectorError::Other)?
2516 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2517 crate::community::v2::service::revoke_public_link(&transport, &community, token)
2518 .await
2519 .map_err(VectorError::Other)
2520 }
2521
2522 pub async fn send_community_message(
2524 &self,
2525 channel_id: &str,
2526 content: &str,
2527 replied_to: Option<&str>,
2528 ) -> Result<String> {
2529 self.send_community_message_expiring(channel_id, content, replied_to, None).await
2530 }
2531
2532 pub async fn send_community_message_expiring(
2541 &self,
2542 channel_id: &str,
2543 content: &str,
2544 replied_to: Option<&str>,
2545 expires_in_secs: Option<u64>,
2546 ) -> Result<String> {
2547 let opts = PostOptions { reply_to: replied_to.map(str::to_string), expires_in_secs, ..Default::default() };
2548 self.post_community_message(channel_id, content, &opts).await
2549 }
2550
2551 pub async fn post_community_message(&self, channel_id: &str, content: &str, opts: &PostOptions) -> Result<String> {
2554 self.post_community(channel_id, content, Vec::new(), opts, std::time::Duration::from_secs(12)).await
2555 }
2556
2557 async fn post_community(
2560 &self,
2561 channel_id: &str,
2562 content: &str,
2563 mut extra_tags: Vec<nostr_sdk::prelude::Tag>,
2564 opts: &PostOptions,
2565 timeout: std::time::Duration,
2566 ) -> Result<String> {
2567 use crate::community::transport::LiveTransport;
2568 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2569 let community = crate::db::community::load_community_v2(&id)
2570 .map_err(VectorError::Other)?
2571 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2572 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2573 let transport = LiveTransport::with_timeout(timeout);
2574 let reply = match opts.reply_to.as_deref().filter(|r| !r.is_empty()) {
2577 Some(parent_id) => {
2578 let author_hex = {
2579 let st = state::STATE.lock().await;
2580 st.find_message(parent_id)
2581 .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
2582 .map(|pk| pk.to_hex())
2583 .unwrap_or_default()
2584 };
2585 Some((parent_id.to_string(), author_hex))
2586 }
2587 None => None,
2588 };
2589 let reply_ref = reply.as_ref().map(|(id, author)| (id.as_str(), author.as_str()));
2590 let (named, role_mentions) = crate::community::mentions::resolve_in(&crate::simd::hex::bytes_to_hex_32(&id.0), content);
2591 let (plain, text_spans) = crate::text_spans::extract_own(&named);
2594 let content = plain.as_str();
2595 let emoji_owned = crate::emoji_packs::resolve_outbound_emoji_tags(content);
2596 let emoji_pairs: Vec<(&str, &str)> = emoji_owned.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
2597 extra_tags.extend(crate::text_spans::to_nostr_tags(&text_spans).chain(crate::community::mentions::to_tags(&role_mentions)));
2598 if let Some(bot) = opts.bot.as_deref().filter(|b| !b.is_empty()) {
2599 let pk = nostr_sdk::prelude::PublicKey::parse(bot).map_err(|_| VectorError::Other(format!("{bot} isn't an npub or hex pubkey")))?;
2600 extra_tags.push(crate::bot_interface::bot_tag(&pk));
2601 }
2602 if let Some(secs) = opts.expires_in_secs.filter(|s| *s > 0) {
2603 let at = crate::clock::now_secs().saturating_add(secs);
2604 extra_tags.push(nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(at)));
2605 }
2606 crate::community::v2::service::send_chat_message(&transport, &community, &ch, content, reply_ref, &emoji_pairs, extra_tags)
2607 .await
2608 .map_err(VectorError::Other)
2609 }
2610
2611 pub async fn send_community_file(&self, channel_id: &str, file_path: &str) -> Result<String> {
2615 self.post_community_file(channel_id, file_path, &PostOptions::default().compress(false)).await
2616 }
2617
2618 pub async fn post_community_file(&self, channel_id: &str, file_path: &str, opts: &PostOptions) -> Result<String> {
2620 let path = std::path::Path::new(file_path);
2621 let bytes = std::fs::read(path).map_err(VectorError::Io)?;
2622 let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("file").to_string();
2623 self.post_community_bytes(channel_id, bytes, &filename, opts).await
2624 }
2625
2626 pub async fn post_community_bytes(&self, channel_id: &str, bytes: Vec<u8>, filename: &str, opts: &PostOptions) -> Result<String> {
2629 crate::db::scoped(async move {
2630 use crate::community::attachments;
2631 if bytes.is_empty() {
2632 return Err(VectorError::Other("Empty file".into()));
2633 }
2634 let (bytes, filename) = ready_to_send(bytes, filename, opts.compress).await?;
2635 let filename = filename.as_str();
2636 let extension = std::path::Path::new(filename).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
2637
2638 let id = self
2641 .v2_community_for_channel(channel_id)?
2642 .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2643 let community = crate::db::community::load_community_v2(&id)
2644 .map_err(VectorError::Other)?
2645 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2646 if community.dissolved {
2647 return Err(VectorError::Other("this community has been dissolved".into()));
2648 }
2649 let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
2650
2651 let file_hash = crate::crypto::sha256_hex(&bytes);
2652 let mime = crate::crypto::mime_from_extension(&extension);
2653 let img_meta = crate::crypto::generate_image_metadata(&bytes);
2654
2655 let params = crate::crypto::generate_encryption_params();
2657 let encrypted = crate::crypto::encrypt_data(&bytes, ¶ms)?;
2658 let encrypted_size = encrypted.len() as u64;
2659
2660 let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
2661 let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
2662 let servers = crate::blossom_servers::compute_enabled_servers();
2663 if servers.is_empty() {
2664 return Err(VectorError::Other("No Blossom servers configured".into()));
2665 }
2666 let noop_progress: crate::blossom::ProgressCallback = std::sync::Arc::new(|_, _| Ok(()));
2667 let accepted = crate::blossom::upload_blob_with_progress_and_failover(
2668 signer.clone(),
2669 servers,
2670 std::sync::Arc::new(encrypted),
2671 Some(mime),
2672 true,
2673 noop_progress,
2674 Some(3),
2675 Some(std::time::Duration::from_secs(2)),
2676 None,
2677 ).await.map_err(VectorError::Other)?;
2678 let url = accepted.url;
2680
2681 let attachment = crate::types::Attachment {
2682 id: file_hash.clone(),
2683 key: params.key.clone(),
2684 nonce: params.nonce.clone(),
2685 extension: extension.clone(),
2686 name: filename.to_string(),
2687 url,
2688 path: String::new(),
2690 size: encrypted_size,
2691 img_meta,
2692 downloading: false,
2693 downloaded: false,
2694 verified: true,
2695 webxdc_topic: extension
2697 .eq_ignore_ascii_case("xdc")
2698 .then(|| crate::webxdc::mint_topic_id(&file_hash, &author_pk.to_hex())),
2699 ..Default::default()
2700 };
2701 let imeta = vec![attachments::attachment_to_imeta(&attachment)];
2703 let caption = opts.caption.clone().unwrap_or_default();
2704 self.post_community(channel_id, &caption, imeta, opts, std::time::Duration::from_secs(30)).await
2705 })
2706 .await
2707 }
2708
2709 pub async fn send_community_typing(&self, channel_id: &str) -> Result<()> {
2711 use crate::community::transport::LiveTransport;
2712 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2713 let community = crate::db::community::load_community_v2(&id)
2714 .map_err(VectorError::Other)?
2715 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2716 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2717 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(8));
2718 crate::community::v2::service::send_typing(&transport, &community, &ch)
2719 .await
2720 .map_err(VectorError::Other)
2721 }
2722
2723 pub async fn send_community_reaction(
2726 &self,
2727 channel_id: &str,
2728 message_id: &str,
2729 emoji: &str,
2730 emoji_url: Option<&str>,
2731 ) -> Result<()> {
2732 crate::db::scoped(async move {
2733 if Self::own_reaction_id(message_id, emoji).await.is_some() {
2735 return Ok(());
2736 }
2737 let emoji_tags: Vec<crate::types::EmojiTag> = match emoji_url {
2738 Some(url) if emoji.starts_with(':') && emoji.ends_with(':') && emoji.len() >= 3 && !url.is_empty() => {
2739 vec![crate::types::EmojiTag { shortcode: emoji[1..emoji.len() - 1].to_string(), url: url.to_string() }]
2740 }
2741 _ => Vec::new(),
2742 };
2743 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2744 let community = crate::db::community::load_community_v2(&id)
2745 .map_err(VectorError::Other)?
2746 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2747 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2748 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2749 let held = {
2754 let st = state::STATE.lock().await;
2755 st.find_message(message_id)
2756 .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
2757 };
2758 let held = held.or_else(|| {
2759 crate::db::events::event_author(message_id)
2760 .ok()
2761 .flatten()
2762 .and_then(|n| nostr_sdk::prelude::PublicKey::parse(&n).ok())
2763 });
2764 let target_author = match held {
2765 Some(pk) => pk,
2766 None => crate::community::v2::service::fetch_channel(&transport, &community, &ch, 500)
2767 .await
2768 .map_err(VectorError::Other)?
2769 .iter()
2770 .find(|f| f.event.opened().rumor_id.to_hex() == message_id)
2771 .map(|f| f.event.opened().author)
2772 .ok_or_else(|| VectorError::Other("reacted-to message not found".into()))?,
2773 };
2774 let pair = emoji_tags.first().map(|t| (t.shortcode.as_str(), t.url.as_str()));
2776 crate::community::v2::service::send_reaction(
2781 &transport, &community, &ch, message_id, &target_author.to_hex(), crate::community::v2::kind::MESSAGE, emoji, pair,
2782 )
2783 .await
2784 .map(|_| ())
2785 .map_err(VectorError::Other)
2786 })
2787 .await
2788 }
2789
2790 pub async fn edit_community_message(&self, channel_id: &str, message_id: &str, new_content: &str) -> Result<()> {
2792 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2793 let (named, _) = crate::community::mentions::resolve_in(&crate::simd::hex::bytes_to_hex_32(&id.0), new_content);
2795 let (plain, text_spans) = crate::text_spans::extract_own(&named);
2796 let new_content = plain.as_str();
2797 let span_tags: Vec<nostr_sdk::prelude::Tag> = crate::text_spans::to_nostr_tags(&text_spans).collect();
2798 let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
2799 let community = crate::db::community::load_community_v2(&id)
2800 .map_err(VectorError::Other)?
2801 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2802 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2803 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2804 let emoji_pairs: Vec<(&str, &str)> = emoji_tags.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
2805 crate::community::v2::service::send_edit_tagged(&transport, &community, &ch, message_id, new_content, &emoji_pairs, span_tags)
2806 .await
2807 .map(|_| ())
2808 .map_err(VectorError::Other)
2809 }
2810
2811 pub async fn delete_community_message(&self, message_id: &str) -> Result<()> {
2815 let channel_id = self.message_chat(message_id).await?;
2816 self.delete_community_message_in(&channel_id, message_id).await
2817 }
2818
2819 pub async fn message_chat(&self, message_id: &str) -> Result<String> {
2822 if let Some((_, chat)) = state::STATE.lock().await.find_chat_for_message(message_id) {
2823 return Ok(chat);
2824 }
2825 crate::db::events::locate_message(message_id)
2826 .map_err(VectorError::Other)?
2827 .chat
2828 .ok_or_else(|| VectorError::Other("message not found (already deleted?)".into()))
2829 }
2830
2831 pub async fn delete_community_message_in(&self, channel_id: &str, message_id: &str) -> Result<()> {
2835 use crate::community::transport::LiveTransport;
2836 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2837
2838 let attachment_urls: Vec<String> = self
2841 .get_message(message_id)
2842 .await
2843 .map(|(_, msg)| msg.attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect())
2844 .unwrap_or_default();
2845 let attachment_urls =
2847 crate::db::attachments::urls_unreferenced_elsewhere(&attachment_urls, message_id).unwrap_or_default();
2848
2849 let id = self
2850 .v2_community_for_channel(channel_id)?
2851 .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2852 let community = crate::db::community::load_community_v2(&id)
2853 .map_err(VectorError::Other)?
2854 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2855 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2856 crate::community::v2::service::delete_own(&transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE)
2857 .await
2858 .map_err(VectorError::Other)?;
2859 if !attachment_urls.is_empty() {
2861 if let Some(_client) = state::nostr_client() {
2862 if let Ok(signer) = crate::signer::active_signer() {
2863 crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
2864 }
2865 }
2866 }
2867 let removed_chat = {
2868 let mut st = state::STATE.lock().await;
2869 st.remove_message(message_id).map(|(cid, _)| cid)
2870 };
2871 let _ = crate::db::events::delete_event(message_id).await;
2872 traits::emit_event_json("message_removed", serde_json::json!({
2873 "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "deleted",
2874 }));
2875 Ok(())
2876 }
2877
2878 pub async fn hide_community_message(&self, channel_id: &str, message_id: &str) -> Result<()> {
2883 use crate::community::transport::LiveTransport;
2884 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2885
2886 let author_npub = {
2889 let st = state::STATE.lock().await;
2890 st.find_message(message_id).and_then(|(_, m)| m.npub)
2891 };
2892 let author_npub = match author_npub {
2893 Some(n) => n,
2894 None => crate::db::events::event_author(message_id)
2895 .ok()
2896 .flatten()
2897 .ok_or_else(|| VectorError::Other("can't resolve the target message's author".into()))?,
2898 };
2899 let author = nostr_sdk::prelude::PublicKey::parse(&author_npub)
2900 .map_err(|_| VectorError::Other("target message has an unreadable author".into()))?;
2901
2902 let id = self
2903 .v2_community_for_channel(channel_id)?
2904 .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2905 let community = crate::db::community::load_community_v2(&id)
2906 .map_err(VectorError::Other)?
2907 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2908 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2909 crate::community::v2::service::moderation_delete(
2910 &transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE, &author,
2911 )
2912 .await
2913 .map_err(VectorError::Other)?;
2914
2915 let removed_chat = {
2916 let mut st = state::STATE.lock().await;
2917 st.remove_message(message_id).map(|(cid, _)| cid)
2918 };
2919 let _ = crate::db::events::delete_event(message_id).await;
2920 traits::emit_event_json("message_removed", serde_json::json!({
2921 "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "hidden",
2922 }));
2923 Ok(())
2924 }
2925
2926 pub async fn sync_community_channel(&self, channel_id: &str, limit: usize) -> Result<(usize, Vec<String>)> {
2931 self.sync_community_channel_before(channel_id, limit, None).await
2932 }
2933
2934 pub async fn sync_community_channel_page(
2937 &self,
2938 channel_id: &str,
2939 limit: usize,
2940 before_secs: Option<u64>,
2941 since_secs: Option<u64>,
2942 ) -> Result<(BackfillCount, Vec<String>)> {
2943 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2944 let warnings = if community::v2::realtime::follow_worker_running() {
2945 community::v2::realtime::enqueue_follow(&id);
2946 Vec::new()
2947 } else {
2948 Self::v2_inline_follow(&id).await
2949 };
2950 let count = Self::v2_backfill_channel_counted(
2951 &id, channel_id, limit, 8, since_secs, before_secs,
2952 crate::community::transport::Evidence::Fast, 12,
2953 ).await;
2954 Ok((count, warnings))
2955 }
2956
2957 pub async fn fill_community_gap(&self, channel_id: &str, before_ms: u64) -> Result<usize> {
2961 let before = before_ms / 1000;
2962 if history_gaps::gap_at(channel_id, before).is_none() {
2963 return Ok(0);
2964 }
2965 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2966 let count = Self::v2_backfill_channel_counted(
2967 &id, channel_id, 50, 2, None, Some(before),
2968 crate::community::transport::Evidence::Fast, 12,
2969 ).await;
2970 if count.next_before.is_some_and(|n| n >= before) {
2973 history_gaps::abandon(channel_id, before);
2974 }
2975 Ok(count.new_messages)
2976 }
2977
2978 pub async fn sync_community_channel_before(
2987 &self,
2988 channel_id: &str,
2989 limit: usize,
2990 before_secs: Option<u64>,
2991 ) -> Result<(usize, Vec<String>)> {
2992 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2997 let warnings = if community::v2::realtime::follow_worker_running() {
2998 community::v2::realtime::enqueue_follow(&id);
2999 Vec::new()
3000 } else {
3001 Self::v2_inline_follow(&id).await
3002 };
3003 let new = Self::v2_backfill_channel(
3008 &id, channel_id, limit, 8, None, before_secs,
3009 crate::community::transport::Evidence::Fast, 12,
3010 ).await;
3011 Ok((new, warnings))
3012 }
3013
3014 pub async fn sync_channel_events(
3029 &self,
3030 channel_id: &str,
3031 max_events: usize,
3032 until_s: Option<u64>,
3033 since_s: Option<u64>,
3034 ) -> Result<usize> {
3035 let max = max_events.clamp(1, 500);
3036 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
3037 let community = crate::db::community::load_community_v2(&id)
3038 .map_err(VectorError::Other)?
3039 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
3040 if community.dissolved {
3041 return Err(VectorError::Other("this community has been dissolved".into()));
3042 }
3043 let ch_id = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
3044 let ch = community
3045 .channel(&ch_id)
3046 .ok_or_else(|| VectorError::Other("no such channel in this community".into()))?;
3047 if ch.private && ch.key.is_none() {
3050 return Err(VectorError::Other(
3051 "this private channel has no key yet (awaiting rekey delivery)".into(),
3052 ));
3053 }
3054 let new = Self::v2_backfill_channel(
3055 &id, channel_id, max, 1, since_s, until_s,
3056 crate::community::transport::Evidence::Fast, 12,
3057 )
3058 .await;
3059 Ok(new)
3060 }
3061
3062 pub async fn get_chat_commands(&self, chat_id: &str) -> crate::bot_interface::ChatCommandsSnapshot {
3074 use crate::bot_interface::{self, ChatCommandsSnapshot};
3075 use nostr_sdk::prelude::ToBech32;
3076
3077 let mut bots: Vec<nostr_sdk::prelude::PublicKey> = Vec::new();
3078 let mut relays: Vec<String> = Vec::new();
3079 let community_hex = crate::db::community::community_id_for_channel(chat_id).ok().flatten();
3080 if let Some(cid_hex) = community_hex {
3081 let Ok(Some(community)) = Self::load_held(&cid_hex) else {
3082 return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
3083 };
3084 let members = community::v2::service::stored_memberlist(&community).unwrap_or_default();
3085 relays = community.relays.clone();
3086 let state = crate::state::STATE.lock().await;
3087 for pk in members {
3088 let Ok(npub) = pk.to_bech32();
3089 if state.get_profile(&npub).map(|p| p.flags.is_bot()).unwrap_or(false) {
3090 bots.push(pk);
3091 }
3092 }
3093 } else if chat_id.starts_with("npub1") {
3094 if let Ok(pk) = nostr_sdk::prelude::PublicKey::parse(chat_id) {
3095 let is_bot = {
3096 let state = crate::state::STATE.lock().await;
3097 state.get_profile(chat_id).map(|p| p.flags.is_bot()).unwrap_or(false)
3098 };
3099 if is_bot {
3100 bots.push(pk);
3101 if let Some(client) = crate::state::nostr_client() {
3104 relays = client.relays().await.keys().map(|u| u.to_string()).collect();
3105 }
3106 }
3107 }
3108 }
3109
3110 if bots.is_empty() {
3111 return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
3112 }
3113 relays.extend(bot_interface::DISCOVERY_RELAYS.iter().map(|s| s.to_string()));
3116 relays.sort();
3117 relays.dedup();
3118 bots.sort_by_key(|p| p.to_hex());
3121 let bot_hexes: Vec<String> = bots.iter().map(|p| p.to_hex()).collect();
3122 let commands = bot_interface::assemble_from_store(&bot_hexes);
3123 let fresh = bot_interface::commands_fresh(chat_id, &bot_hexes);
3124 if !fresh {
3125 bot_interface::spawn_commands_refresh(chat_id.to_string(), bots.clone(), relays);
3126 }
3127 ChatCommandsSnapshot { bots: bots.len(), commands, fresh }
3128 }
3129
3130 pub async fn get_community_members(&self, community_id: &str) -> Vec<serde_json::Value> {
3136 use nostr_sdk::prelude::ToBech32;
3137 let Ok(Some(community)) = Self::load_held(community_id) else { return Vec::new() };
3143 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3144 let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
3145 if cursor == 0 {
3146 if crate::community::v2::realtime::follow_worker_running() {
3147 crate::community::v2::realtime::enqueue_follow(community.id());
3148 } else {
3149 let c2 = community.clone();
3150 db::spawn_bound(async move {
3151 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
3152 if matches!(crate::community::v2::service::sync_guestbook(&transport, &c2).await, Ok(fresh) if !fresh.is_empty()) {
3153 emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
3154 }
3155 });
3156 }
3157 }
3158 let parts = crate::community::v2::service::stored_member_parts(&community, &events).unwrap_or_default();
3159 let counted = parts.counted.into_iter().filter_map(|pk| pk.to_bech32().ok()).map(|npub| serde_json::json!({ "npub": npub }));
3160 let unlisted = parts
3161 .unlisted
3162 .into_iter()
3163 .filter_map(|(pk, why)| pk.to_bech32().ok().map(|npub| serde_json::json!({ "npub": npub, "unlisted": why })));
3164 counted.chain(unlisted).collect()
3165 }
3166
3167 pub fn get_community_banned(&self, community_id: &str) -> Vec<String> {
3177 use nostr_sdk::prelude::{PublicKey, ToBech32};
3178 let cid_hex = match Self::load_held(community_id) {
3181 Ok(Some(c)) => crate::simd::hex::bytes_to_hex_32(&c.id().0),
3182 _ => community_id.to_string(),
3183 };
3184 crate::db::community::get_community_banlist(&cid_hex)
3185 .unwrap_or_default()
3186 .iter()
3187 .filter_map(|hex| PublicKey::parse(hex).ok())
3188 .filter_map(|pk| pk.to_bech32().ok())
3189 .collect()
3190 }
3191
3192 pub fn community_moderation_intel(&self, community_id: &str) -> Result<serde_json::Value> {
3199 let community = Self::load_held(community_id)?
3200 .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
3201 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3202 let report = Self::policy_console_report(&cid_hex, &community)?;
3203 let invites = crate::db::community::list_public_invites(&cid_hex).unwrap_or_default();
3204 let banlist = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
3205 let caps = self.community_capabilities(community_id).unwrap_or_else(|_| serde_json::json!({}));
3206 let owner_b32 = community.owner().map_err(VectorError::Other)?.to_bech32().unwrap_or_default();
3207 let unlisted: Vec<String> = crate::db::community::get_guestbook_shared(&cid_hex)
3209 .ok()
3210 .and_then(|(events, _)| crate::community::v2::service::stored_member_parts(&community, &events).ok())
3211 .map(|p| p.unlisted.into_keys().filter_map(|pk| pk.to_bech32().ok()).collect())
3212 .unwrap_or_default();
3213
3214 Ok(serde_json::json!({
3215 "community_id": cid_hex,
3216 "name": community.name,
3217 "owner_npub": owner_b32,
3218 "epoch": community.root_epoch.0,
3219 "report": &*report,
3220 "unlisted": unlisted,
3221 "invites": invites.iter().map(|i| serde_json::json!({
3222 "token": i.token,
3223 "label": i.label,
3224 "created_at": i.created_at,
3225 "expires_at": i.expires_at,
3226 "join_count": i.join_count,
3227 })).collect::<Vec<_>>(),
3228 "banlist_count": banlist.len(),
3229 "banlist_max": crate::community::v2::roles::MAX_BANLIST,
3230 "capabilities": caps,
3231 "channels": community.channels.iter().map(|c| serde_json::json!({
3234 "id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
3235 "name": c.name,
3236 })).collect::<Vec<_>>(),
3237 }))
3238 }
3239
3240 pub fn screen_community_message(
3249 &self,
3250 channel_id: &str,
3251 author_npub: &str,
3252 text: &str,
3253 ) -> Result<serde_json::Value> {
3254 use nostr_sdk::prelude::PublicKey;
3255 let Some(id) = self.v2_community_for_channel(channel_id)? else {
3256 return Ok(serde_json::json!({ "findings": [] }));
3257 };
3258 let community = crate::db::community::load_community_v2(&id)
3259 .map_err(VectorError::Other)?
3260 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
3261 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3262 let owner = community.owner().map_err(VectorError::Other)?;
3263 let author = PublicKey::parse(author_npub).map_err(|_| VectorError::Other("unreadable author".into()))?;
3264
3265 use crate::community::roles::Permissions;
3268 const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3269 | Permissions::MANAGE_CHANNELS
3270 | Permissions::MANAGE_METADATA
3271 | Permissions::KICK
3272 | Permissions::BAN
3273 | Permissions::MANAGE_MESSAGES;
3274 let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3275 let hex = author.to_hex();
3276 let roles: Vec<String> =
3277 roster.grants.iter().find(|g| g.member == hex).map(|g| g.role_ids.clone()).unwrap_or_default();
3278 let is_staff = roles
3279 .iter()
3280 .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0));
3281
3282 let now_ms = crate::clock::now_ms();
3283 let findings = crate::community::policy::harness::screen_message(
3284 &cid_hex, &owner, &author, &roles, is_staff, channel_id, text, now_ms,
3285 );
3286 Ok(serde_json::json!({ "findings": findings }))
3287 }
3288
3289 pub fn check_community_raid(&self, community_id: &str) -> Result<serde_json::Value> {
3293 let Some(community) = Self::load_held(community_id)? else {
3294 return Ok(serde_json::json!({ "detected": false }));
3295 };
3296 let caps = self.community_capabilities(community_id)?;
3300 if caps["ban"].as_bool() != Some(true) {
3301 return Ok(serde_json::json!({ "detected": false }));
3302 }
3303 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3304 let report = Self::policy_console_report(&cid_hex, &community)?;
3305 let biggest = report["cohorts"].get(0);
3306 Ok(serde_json::json!({
3307 "detected": report["raid_detected"].as_bool().unwrap_or(false),
3308 "suspects": report["suspects"].as_u64().unwrap_or(0),
3309 "cohort": biggest.and_then(|c| c["size"].as_u64()).unwrap_or(0),
3310 "sample": biggest
3311 .and_then(|c| c["sample"].as_str())
3312 .map(|s| s.chars().take(60).collect::<String>())
3313 .unwrap_or_default(),
3314 }))
3315 }
3316
3317 fn raid_report(cid_hex: &str) -> Result<std::sync::Arc<crate::community::raid::RaidReport>> {
3321 use crate::community::raid;
3322 use crate::community::v2::guestbook::GuestbookEntry;
3323 use nostr_sdk::prelude::PublicKey;
3324 use std::collections::{HashMap, HashSet};
3325
3326 let now_secs = crate::clock::now_secs();
3327 if let Some(report) = report_get(&raid_report_cache(), cid_hex, now_secs) {
3328 return Ok(report);
3329 }
3330 let community = crate::db::community::load_community_v2(&crate::community::CommunityId(
3331 crate::simd::hex::hex_to_bytes_32(cid_hex),
3332 ))
3333 .map_err(VectorError::Other)?
3334 .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
3335 let owner_b32 = community.owner().map_err(VectorError::Other)?.to_bech32().unwrap_or_default();
3336 let me_b32 = state::my_public_key().and_then(|p| p.to_bech32().ok()).unwrap_or_default();
3337
3338 let roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
3340 let staff: HashSet<String> = roster
3341 .grants
3342 .iter()
3343 .filter(|g| !g.role_ids.is_empty())
3344 .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
3345 .collect();
3346
3347 let members: Vec<String> = crate::community::v2::service::stored_memberlist(&community)
3349 .unwrap_or_default()
3350 .into_iter()
3351 .filter_map(|pk| pk.to_bech32().ok())
3352 .collect();
3353
3354 let (events, _cursor) = crate::db::community::get_guestbook(cid_hex).unwrap_or_default();
3356 let mut joined_at: HashMap<String, u64> = HashMap::new();
3357 let mut invite_label: HashMap<String, String> = HashMap::new();
3358 for e in &events {
3359 let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
3360 let Ok(b32) = member.to_bech32();
3361 let slot = joined_at.entry(b32.clone()).or_insert(*at_ms);
3363 *slot = (*slot).min(*at_ms);
3364 if let Some((_creator, label)) = invited_by {
3365 invite_label.entry(b32).or_insert_with(|| label.clone());
3366 }
3367 }
3368
3369 let footprints: HashMap<String, crate::db::community::AuthorFootprint> =
3370 crate::db::community::community_author_footprints(cid_hex)
3371 .unwrap_or_default()
3372 .into_iter()
3373 .map(|f| (f.npub.clone(), f))
3374 .collect();
3375
3376 const TEXT_WINDOW: usize = 4_000;
3379 let mut texts: HashMap<String, Vec<String>> = HashMap::new();
3380 for (npub, _at, text) in crate::db::community::community_recent_texts(cid_hex, TEXT_WINDOW).unwrap_or_default() {
3381 texts.entry(npub).or_default().push(text);
3382 }
3383
3384 let signals: Vec<raid::MemberSignals> = members
3385 .iter()
3386 .map(|npub| {
3387 let f = footprints.get(npub);
3388 raid::MemberSignals {
3389 npub: npub.clone(),
3390 joined_at_ms: joined_at.get(npub).copied().unwrap_or(0),
3391 invite_label: invite_label.get(npub).cloned(),
3392 messages: f.map(|f| f.messages).unwrap_or(0),
3393 first_secs: f.map(|f| f.first_secs).unwrap_or(0),
3394 last_secs: f.map(|f| f.last_secs).unwrap_or(0),
3395 texts: texts.get(npub).cloned().unwrap_or_default(),
3396 is_owner: *npub == owner_b32,
3397 is_admin: staff.contains(npub),
3398 is_me: *npub == me_b32,
3399 }
3400 })
3401 .collect();
3402
3403 let params = raid::RaidParams {
3404 known_shortcodes: crate::emoji_packs::known_shortcodes(),
3405 ..Default::default()
3406 };
3407 let report = std::sync::Arc::new(raid::assess(&signals, now_secs, ¶ms));
3408 report_put(&raid_report_cache(), cid_hex, now_secs, report.clone());
3409 Ok(report)
3410 }
3411
3412 pub fn policy_presets(&self) -> Result<serde_json::Value> {
3414 let presets: Vec<serde_json::Value> = crate::community::policy::presets::all()
3415 .into_iter()
3416 .map(|p| {
3417 serde_json::json!({
3418 "id": p.id,
3419 "name": p.name,
3420 "description": p.description,
3421 "example": p.example,
3422 "caveat": p.caveat,
3423 "dials": p.dials,
3424 "rules": crate::community::policy::presets::describe(&p.policy),
3428 "bytes": serde_json::to_string(&p.policy).unwrap_or_default(),
3429 })
3430 })
3431 .collect();
3432 let rule_kinds: Vec<serde_json::Value> = crate::community::policy::presets::rule_kinds()
3436 .into_iter()
3437 .map(|k| {
3438 serde_json::json!({
3439 "id": k.id,
3440 "label": k.label,
3441 "description": k.description,
3442 "input": k.input,
3443 "input_label": k.input_label,
3444 "input_hint": k.input_hint,
3445 "rule": k.rule,
3446 })
3447 })
3448 .collect();
3449 Ok(serde_json::json!({ "presets": presets, "rule_kinds": rule_kinds }))
3450 }
3451
3452 pub fn preview_community_policy(&self, community_id: &str, bytes: &str) -> Result<serde_json::Value> {
3456 use crate::community::v2::guestbook::GuestbookEntry;
3457 let community = Self::load_held(community_id)?
3458 .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3459 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3460 let owner = community.owner().map_err(VectorError::Other)?;
3461 let me = state::my_public_key();
3462
3463 use crate::community::roles::Permissions;
3464 const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3465 | Permissions::MANAGE_CHANNELS
3466 | Permissions::MANAGE_METADATA
3467 | Permissions::KICK
3468 | Permissions::BAN
3469 | Permissions::MANAGE_MESSAGES;
3470 let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3471 let staff: std::collections::HashSet<String> = roster
3472 .grants
3473 .iter()
3474 .filter(|g| {
3475 g.role_ids
3476 .iter()
3477 .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0))
3478 })
3479 .map(|g| g.member.clone())
3480 .collect();
3481 let roles_of: std::collections::HashMap<String, Vec<String>> =
3482 roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
3483
3484 let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
3485 let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
3486 let mut invite_label: std::collections::HashMap<String, String> = std::collections::HashMap::new();
3487 for e in events.iter() {
3488 let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
3489 let hex = member.to_hex();
3490 let slot = joined_at.entry(hex.clone()).or_insert(*at_ms);
3491 *slot = (*slot).min(*at_ms);
3492 if let Some((_c, label)) = invited_by {
3493 invite_label.entry(hex).or_insert_with(|| label.clone());
3494 }
3495 }
3496 let members: Vec<crate::community::policy::harness::MemberRow> =
3497 crate::community::v2::service::stored_memberlist(&community)
3498 .unwrap_or_default()
3499 .into_iter()
3500 .map(|pk| {
3501 let hex = pk.to_hex();
3502 (
3503 pk,
3504 joined_at.get(&hex).copied(),
3505 staff.contains(&hex),
3506 roles_of.get(&hex).cloned().unwrap_or_default(),
3507 invite_label.get(&hex).cloned(),
3508 )
3509 })
3510 .collect();
3511
3512 let now_ms = crate::clock::now_ms();
3513 let assembled =
3514 crate::community::policy::harness::assemble(&cid_hex, &owner, me.as_ref(), &members, now_ms)
3515 .map_err(VectorError::Other)?;
3516 let preview = crate::community::policy::harness::preview_policy(&assembled, bytes, now_ms);
3517 serde_json::to_value(preview).map_err(|e| VectorError::Other(e.to_string()))
3518 }
3519
3520 pub fn list_community_policies(&self, community_id: &str) -> Result<serde_json::Value> {
3523 let community = Self::load_held(community_id)?
3524 .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3525 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3526 let stored = crate::db::community::get_community_policies(&cid_hex).map_err(VectorError::Other)?;
3527 let rows: Vec<serde_json::Value> = stored
3528 .iter()
3529 .map(|p| {
3530 let verdict = serde_json::from_str::<crate::community::policy::document::Policy>(&p.bytes)
3534 .map_err(|e| e.to_string())
3535 .and_then(|doc| doc.validate().map_err(|r| format!("{r:?}")));
3536 serde_json::json!({
3537 "policy_id": p.policy_id,
3538 "hash": p.hash,
3539 "enabled": p.enabled,
3540 "updated_at": p.updated_at,
3541 "bytes": p.bytes,
3542 "valid": verdict.is_ok(),
3543 "error": verdict.err(),
3544 })
3545 })
3546 .collect();
3547 Ok(serde_json::json!({
3548 "community_id": cid_hex,
3549 "policies": rows,
3550 "using_builtin": !stored
3555 .iter()
3556 .any(|p| p.policy_id == crate::community::policy::harness::DEFAULTS_POLICY_ID),
3557 }))
3558 }
3559
3560 pub fn set_community_policy(&self, community_id: &str, policy_id: &str, bytes: &str, enabled: bool) -> Result<serde_json::Value> {
3563 let community = Self::load_held(community_id)?
3564 .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3565 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3566 if bytes.len() > crate::community::policy::types::caps::MAX_POLICY_BYTES {
3567 return Err(VectorError::Other("policy exceeds the maximum document size".into()));
3568 }
3569 let doc: crate::community::policy::document::Policy =
3570 serde_json::from_str(bytes).map_err(|e| VectorError::Other(format!("policy is not valid JSON: {e}")))?;
3571 doc.validate().map_err(|r| VectorError::Other(format!("policy rejected: {r:?}")))?;
3572
3573 let hash = crate::community::policy::harness::hash_policy_bytes(bytes.as_bytes());
3574 let hash_hex = crate::simd::hex::bytes_to_hex_32(&hash.0);
3575 let now_secs = crate::clock::now_secs();
3576 crate::db::community::set_community_policy(&cid_hex, policy_id, bytes, &hash_hex, enabled, now_secs)
3577 .map_err(VectorError::Other)?;
3578 Self::invalidate_raid_report(&cid_hex);
3581 Ok(serde_json::json!({ "policy_id": policy_id, "hash": hash_hex, "enabled": enabled }))
3582 }
3583
3584 pub fn delete_community_policy(&self, community_id: &str, policy_id: &str) -> Result<()> {
3585 let community = Self::load_held(community_id)?
3586 .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3587 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3588 crate::db::community::delete_community_policy(&cid_hex, policy_id).map_err(VectorError::Other)?;
3589 Self::invalidate_raid_report(&cid_hex);
3590 Ok(())
3591 }
3592
3593 pub fn builtin_policy_json(&self) -> Result<String> {
3596 serde_json::to_string_pretty(&crate::community::policy::harness::default_policy())
3597 .map_err(|e| VectorError::Other(e.to_string()))
3598 }
3599
3600 fn policy_console_report(cid_hex: &str, community: &crate::community::v2::community::CommunityV2) -> Result<std::sync::Arc<serde_json::Value>> {
3608 let now_secs = crate::clock::now_secs();
3609 report_once(&policy_report_cache(), &policy_report_gate(), cid_hex, now_secs, || {
3610 Self::evaluate_policy_console(cid_hex, community, now_secs)
3611 })
3612 }
3613
3614 fn evaluate_policy_console(
3615 cid_hex: &str,
3616 community: &crate::community::v2::community::CommunityV2,
3617 now_secs: u64,
3618 ) -> Result<std::sync::Arc<serde_json::Value>> {
3619 use crate::community::v2::guestbook::GuestbookEntry;
3620 let owner = community.owner().map_err(VectorError::Other)?;
3621 let me = state::my_public_key();
3622
3623 use crate::community::roles::Permissions;
3627 const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3628 | Permissions::MANAGE_CHANNELS
3629 | Permissions::MANAGE_METADATA
3630 | Permissions::KICK
3631 | Permissions::BAN
3632 | Permissions::MANAGE_MESSAGES;
3633 let roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
3634 let staff: std::collections::HashSet<String> = roster
3635 .grants
3636 .iter()
3637 .filter(|g| {
3638 g.role_ids
3639 .iter()
3640 .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0))
3641 })
3642 .map(|g| g.member.clone())
3643 .collect();
3644 let roles_of: std::collections::HashMap<String, Vec<String>> =
3645 roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
3646
3647 let (events, _cursor) = crate::db::community::get_guestbook(cid_hex).unwrap_or_default();
3648 let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
3649 let mut invite_label: std::collections::HashMap<String, String> = std::collections::HashMap::new();
3650 for e in &events {
3651 let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
3652 let hex = member.to_hex();
3653 let slot = joined_at.entry(hex.clone()).or_insert(*at_ms);
3655 *slot = (*slot).min(*at_ms);
3656 if let Some((_creator, label)) = invited_by {
3657 invite_label.entry(hex).or_insert_with(|| label.clone());
3658 }
3659 }
3660
3661 let members: Vec<crate::community::policy::harness::MemberRow> =
3662 crate::community::v2::service::stored_memberlist(community)
3663 .unwrap_or_default()
3664 .into_iter()
3665 .map(|pk| {
3666 let hex = pk.to_hex();
3667 (
3668 pk,
3669 joined_at.get(&hex).copied(),
3670 staff.contains(&hex),
3671 roles_of.get(&hex).cloned().unwrap_or_default(),
3672 invite_label.get(&hex).cloned(),
3673 )
3674 })
3675 .collect();
3676
3677 let now_ms = now_secs.saturating_mul(1000);
3678 let assembled =
3679 crate::community::policy::harness::assemble(cid_hex, &owner, me.as_ref(), &members, now_ms)
3680 .map_err(VectorError::Other)?;
3681 Ok(std::sync::Arc::new(
3682 crate::community::policy::harness::evaluate_for_console(cid_hex, &assembled, now_ms)
3683 .map_err(VectorError::Other)?,
3684 ))
3685 }
3686
3687 pub fn policy_side_by_side(&self, community_id: &str) -> Result<serde_json::Value> {
3691 use crate::community::v2::guestbook::GuestbookEntry;
3692 use nostr_sdk::prelude::PublicKey;
3693 let community = Self::load_held(community_id)?
3694 .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
3695 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3696 let owner = community.owner().map_err(VectorError::Other)?;
3697
3698 use crate::community::roles::Permissions;
3701 const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3702 | Permissions::MANAGE_CHANNELS
3703 | Permissions::MANAGE_METADATA
3704 | Permissions::KICK
3705 | Permissions::BAN
3706 | Permissions::MANAGE_MESSAGES;
3707 let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3708 let staff: std::collections::HashSet<String> = roster
3709 .grants
3710 .iter()
3711 .filter(|g| {
3712 g.role_ids.iter().any(|rid| {
3713 roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0)
3714 })
3715 })
3716 .map(|g| g.member.clone())
3717 .collect();
3718 let roles_of: std::collections::HashMap<String, Vec<String>> =
3719 roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
3720
3721 let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
3722 let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
3723 for e in events.iter() {
3724 let GuestbookEntry::Join { member, at_ms, .. } = &e.entry else { continue };
3725 let hex = member.to_hex();
3726 let slot = joined_at.entry(hex).or_insert(*at_ms);
3727 *slot = (*slot).min(*at_ms);
3728 }
3729
3730 let members: Vec<(PublicKey, Option<u64>, bool, Vec<String>)> =
3731 crate::community::v2::service::stored_memberlist(&community)
3732 .unwrap_or_default()
3733 .into_iter()
3734 .map(|pk| {
3735 let hex = pk.to_hex();
3736 (pk, joined_at.get(&hex).copied(), staff.contains(&hex), roles_of.get(&hex).cloned().unwrap_or_default())
3737 })
3738 .collect();
3739
3740 let assessments: Vec<(String, String)> = Self::raid_report(&cid_hex)
3742 .map(|r| {
3743 r.members
3744 .iter()
3745 .map(|m| (m.npub.clone(), format!("{:?}", m.verdict).to_lowercase()))
3746 .collect()
3747 })
3748 .unwrap_or_default();
3749
3750 let now_ms = crate::clock::now_ms();
3751 let diff = crate::community::policy::harness::run_side_by_side(
3752 &cid_hex, &owner, &members, &assessments, now_ms,
3753 )
3754 .map_err(VectorError::Other)?;
3755 serde_json::to_value(diff).map_err(|e| VectorError::Other(e.to_string()))
3756 }
3757
3758 pub fn invalidate_raid_report(community_id: &str) {
3762 policy_report_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(community_id);
3763 raid_report_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(community_id);
3764 }
3765
3766 pub async fn refound_community(&self, community_id: &str, retain: &[&str]) -> Result<()> {
3774 let community = Self::load_held(community_id)?
3775 .ok_or_else(|| VectorError::Other("re-founding requires a Concord v2 community".into()))?;
3776 let removed = Self::members_to_remove(&community, retain)?;
3777 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
3778 crate::community::v2::service::refound_community(&transport, &community, &removed)
3779 .await
3780 .map_err(VectorError::Other)?;
3781 Self::invalidate_raid_report(community_id);
3783 Ok(())
3784 }
3785
3786 fn members_to_remove(
3804 community: &crate::community::v2::community::CommunityV2,
3805 retain: &[&str],
3806 ) -> Result<Vec<nostr_sdk::prelude::PublicKey>> {
3807 use nostr_sdk::prelude::PublicKey;
3808 let keep: std::collections::HashSet<PublicKey> =
3809 retain.iter().filter_map(|n| PublicKey::parse(n).ok()).collect();
3810 if keep.is_empty() {
3811 return Ok(Vec::new());
3812 }
3813 let me = state::my_public_key();
3814 let owner = community.owner().ok();
3815 Ok(crate::community::v2::service::stored_memberlist(community)
3816 .map_err(VectorError::Other)?
3817 .into_iter()
3818 .filter(|pk| !keep.contains(pk))
3819 .filter(|pk| Some(*pk) != me && Some(*pk) != owner)
3820 .collect())
3821 }
3822
3823 pub async fn purge_and_refound(
3839 &self,
3840 community_id: &str,
3841 retain: &[&str],
3842 on_progress: &(dyn Fn(usize, usize) + Sync),
3843 ) -> Result<serde_json::Value> {
3844 let community = Self::load_held(community_id)?
3845 .ok_or_else(|| VectorError::Other("re-founding requires a Concord v2 community".into()))?;
3846 let removed = Self::members_to_remove(&community, retain)?;
3847 let keep: Vec<nostr_sdk::prelude::PublicKey> = retain
3852 .iter()
3853 .filter_map(|n| nostr_sdk::prelude::PublicKey::parse(n).ok())
3854 .collect();
3855 log_info!("[Moderation] purge: {} to remove, {} retained", removed.len(), keep.len());
3856 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
3857 if keep.is_empty() {
3868 crate::community::v2::service::refound_community(&transport, &community, &removed)
3869 .await
3870 .map_err(VectorError::Other)?;
3871 } else {
3872 crate::community::v2::service::refound_community_retaining(&transport, &community, &removed, &keep)
3873 .await
3874 .map_err(VectorError::Other)?;
3875 }
3876 let fresh = Self::load_held(community_id)?
3880 .ok_or_else(|| VectorError::Other("community gone during the purge".into()))?;
3881 let sweep = crate::community::v2::service::kick_members(&transport, &fresh, &removed, on_progress)
3882 .await
3883 .map_err(VectorError::Other)?;
3884 let _ = crate::community::v2::service::sync_guestbook(&transport, &fresh).await;
3887 log_info!(
3888 "[Moderation] purge: rotated to epoch {}, kicked {}/{} ({} refused, {} failed)",
3889 fresh.root_epoch.0,
3890 sweep.kicked.len(),
3891 removed.len(),
3892 sweep.refused.len(),
3893 sweep.failed.len()
3894 );
3895 Ok(serde_json::json!({
3896 "kicked": sweep.kicked.len(),
3897 "refused": sweep.refused.len(),
3898 "failed": sweep.failed.len(),
3899 "rotated": true,
3900 }))
3901 }
3902
3903 pub async fn kick_community_members(
3906 &self,
3907 community_id: &str,
3908 npubs: &[&str],
3909 on_progress: &(dyn Fn(usize, usize) + Sync),
3910 ) -> Result<serde_json::Value> {
3911 let community = Self::load_held(community_id)?
3912 .ok_or_else(|| VectorError::Other("kicking requires a Concord v2 community".into()))?;
3913 use nostr_sdk::prelude::PublicKey;
3914 let targets: Vec<PublicKey> = npubs.iter().filter_map(|n| PublicKey::parse(n).ok()).collect();
3915 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
3916 let sweep = crate::community::v2::service::kick_members(&transport, &community, &targets, on_progress)
3917 .await
3918 .map_err(VectorError::Other)?;
3919 let _ = crate::community::v2::service::sync_guestbook(&transport, &community).await;
3920 log_info!(
3921 "[Moderation] kick sweep: {}/{} kicked ({} refused, {} failed)",
3922 sweep.kicked.len(),
3923 targets.len(),
3924 sweep.refused.len(),
3925 sweep.failed.len()
3926 );
3927 Self::invalidate_raid_report(community_id);
3928 Ok(serde_json::json!({
3929 "kicked": sweep.kicked.len(),
3930 "refused": sweep.refused.iter().map(|(_, why)| why.clone()).collect::<Vec<_>>(),
3931 "failed": sweep.failed.len(),
3932 }))
3933 }
3934
3935 pub async fn revoke_all_public_invites(&self, community_id: &str) -> Result<(usize, usize)> {
3940 let tokens: Vec<String> = crate::db::community::list_public_invites(community_id)
3941 .map_err(VectorError::Other)?
3942 .into_iter()
3943 .map(|i| i.token)
3944 .collect();
3945 let mut revoked = 0usize;
3946 let mut failed = 0usize;
3947 for token in &tokens {
3948 match self.revoke_public_invite(community_id, token).await {
3949 Ok(()) => revoked += 1,
3950 Err(_) => failed += 1,
3951 }
3952 }
3953 Ok((revoked, failed))
3954 }
3955
3956 pub async fn v2_inline_follow(id: &crate::community::CommunityId) -> Vec<String> {
3964 crate::db::scoped(async move {
3965 use crate::community::transport::LiveTransport;
3966 let session = crate::db::current_session();
3967 let lock = crate::community::v2::realtime::follow_lock(id);
3972 let _guard = lock.lock().await;
3973 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3974 let mut warnings: Vec<String> = Vec::new();
3975 let Ok(Some(community)) = crate::db::community::load_community_v2(id) else {
3976 warnings.push("v2 community not found".to_string());
3977 return warnings;
3978 };
3979 let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
3980 match crate::community::v2::service::follow_rekeys(&transport, &community, &session).await {
3981 Ok(f) if f.dissolved => return warnings,
3983 Ok(f) if f.self_removed => {
3984 let _ = crate::db::community::delete_community_retain_keys(&cid_hex);
3992 return warnings;
3993 }
3994 Ok(_) => {}
3995 Err(e) => warnings.push(format!("v2 rekey follow failed: {e}")),
3996 }
3997 if let Ok(Some(fresh)) = crate::db::community::load_community_v2(id) {
3998 match crate::community::v2::service::follow_control(&transport, &fresh).await {
3999 Ok(control) if control.moved() => {
4008 if let Ok(Some(latest)) = crate::db::community::load_community_v2(id) {
4009 if let Err(e) = crate::community::v2::service::follow_rekeys(&transport, &latest, &session).await {
4010 warnings.push(format!("v2 rekey follow failed: {e}"));
4011 }
4012 }
4013 }
4014 Ok(_) => {}
4015 Err(e) => warnings.push(format!("v2 control follow failed: {e}")),
4016 }
4017 }
4018 if let Some(me) = crate::my_public_key() {
4023 if crate::db::community::is_author_banned(&cid_hex, &me) {
4024 let _ = crate::db::community::delete_community_retain_keys(&cid_hex);
4025 return warnings;
4026 }
4027 }
4028 let quiet = crate::event_handler::NoOpEventHandler;
4030 if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
4031 crate::community::v2::service::owe_new_departures(&folded);
4032 }
4033 crate::community::v2::realtime::settle_owed_retractions(id, &transport, &quiet).await;
4034 if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
4035 crate::community::v2::service::rejudge_held(&folded, &quiet).await;
4036 }
4037 warnings
4038 })
4039 .await
4040 }
4041
4042 #[allow(clippy::too_many_arguments)]
4053 pub(crate) async fn v2_backfill_channel(
4054 id: &crate::community::CommunityId,
4055 channel_id: &str,
4056 limit: usize,
4057 max_pages: usize,
4058 since: Option<u64>,
4059 until: Option<u64>,
4060 evidence: crate::community::transport::Evidence,
4061 transport_secs: u64,
4062 ) -> usize {
4063 let (mut new, mut until) = (0, until);
4066 let mut waiting = Vec::new();
4067 for _ in 0..BACKFILL_CONTINUATIONS {
4068 let (count, still) = Self::v2_backfill_window(id, channel_id, limit, max_pages, since, until, evidence, transport_secs).await;
4069 new += count.new_messages;
4070 waiting.extend(still);
4071 match count.next_before {
4072 Some(next) if until.is_none_or(|u| next < u) => until = Some(next),
4073 _ => break,
4074 }
4075 }
4076 if !waiting.is_empty() {
4079 if let Some(me) = state::my_public_key() {
4080 Self::v2_ingest_chat_page_waiting(channel_id, me, crate::db::current_session(), waiting).await;
4081 }
4082 }
4083 new
4084 }
4085
4086 #[allow(clippy::too_many_arguments)]
4091 pub(crate) async fn v2_backfill_channel_counted(
4092 id: &crate::community::CommunityId,
4093 channel_id: &str,
4094 limit: usize,
4095 max_pages: usize,
4096 since: Option<u64>,
4097 until: Option<u64>,
4098 evidence: crate::community::transport::Evidence,
4099 transport_secs: u64,
4100 ) -> BackfillCount {
4101 Self::v2_backfill_window(id, channel_id, limit, max_pages, since, until, evidence, transport_secs).await.0
4102 }
4103
4104 #[allow(clippy::too_many_arguments)]
4107 async fn v2_backfill_window(
4108 id: &crate::community::CommunityId,
4109 channel_id: &str,
4110 limit: usize,
4111 max_pages: usize,
4112 since: Option<u64>,
4113 until: Option<u64>,
4114 evidence: crate::community::transport::Evidence,
4115 transport_secs: u64,
4116 ) -> (BackfillCount, Vec<crate::community::v2::service::FetchedEvent>) {
4117 let session = crate::db::current_session();
4120 let Some(my_pk) = state::my_public_key() else { return (BackfillCount::default(), Vec::new()) };
4121 if crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false) {
4125 return (BackfillCount::default(), Vec::new());
4126 }
4127 let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return (BackfillCount::default(), Vec::new()) };
4128 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4129 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(transport_secs));
4130 let held = std::sync::atomic::AtomicUsize::new(0);
4131 let began = crate::clock::now_secs();
4132 let floor = crate::history_gaps::floor(channel_id, until, began);
4133 let reach = crate::history_gaps::reach(since, floor);
4134 let Ok((page, next_before, complete)) = crate::community::v2::service::fetch_channel_history_paged(
4135 &transport,
4136 &community,
4137 &ch,
4138 limit.max(50),
4139 max_pages,
4140 reach,
4141 until,
4142 evidence,
4143 |page, settled, next| {
4145 crate::community::v2::service::catch_up_pages_on(page, settled, next, floor, |id| crate::db::events::event_exists(id).unwrap_or(false))
4146 },
4147 |wraps| {
4149 if until.is_some() {
4150 return Default::default();
4151 }
4152 let hex: Vec<String> = wraps.iter().map(|w| w.to_hex()).collect();
4153 let settled = crate::db::events::community_wraps_settled(&hex);
4154 let skip: std::collections::HashSet<_> = wraps.iter().zip(&hex).filter(|(_, h)| settled.contains(*h)).map(|(w, _)| *w).collect();
4155 held.fetch_add(skip.len(), std::sync::atomic::Ordering::Relaxed);
4156 skip
4157 },
4158 )
4159 .await
4160 else {
4161 return (BackfillCount { unreachable: true, ..Default::default() }, Vec::new());
4162 };
4163 let fetched = page.len() + held.into_inner();
4164 let (new_messages, waiting) = Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await;
4165 crate::history_gaps::note_walk(channel_id, until, next_before, floor, |t| crate::db::events::newest_message_before(channel_id, t));
4167 if until.is_none() && since.is_none() && complete {
4170 crate::history_gaps::prove(channel_id, began);
4171 }
4172 (BackfillCount { fetched, new_messages, next_before, unreachable: false }, waiting)
4173 }
4174
4175 pub(crate) async fn v2_ingest_chat_page(
4179 channel_id: &str,
4180 my_pk: nostr_sdk::prelude::PublicKey,
4181 session: std::sync::Arc<crate::db::Session>,
4182 page: Vec<crate::community::v2::service::FetchedEvent>,
4183 ) -> usize {
4184 Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await.0
4185 }
4186
4187 async fn v2_ingest_chat_page_waiting(
4189 channel_id: &str,
4190 my_pk: nostr_sdk::prelude::PublicKey,
4191 session: std::sync::Arc<crate::db::Session>,
4192 page: Vec<crate::community::v2::service::FetchedEvent>,
4193 ) {
4194 Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await;
4195 }
4196
4197 async fn v2_ingest_chat_page_keeping(
4200 channel_id: &str,
4201 my_pk: nostr_sdk::prelude::PublicKey,
4202 session: std::sync::Arc<crate::db::Session>,
4203 page: Vec<crate::community::v2::service::FetchedEvent>,
4204 ) -> (usize, Vec<crate::community::v2::service::FetchedEvent>) {
4205 crate::db::scoped(async move {
4206 use crate::community::v2::inbound::ChatPersist;
4207 let judged_on = crate::community::v2::service::writers_head(channel_id);
4208 let page = crate::community::v2::service::rejudge_page(channel_id, page);
4209 let since = page.iter().map(|f| f.event.opened().at_ms).min();
4210 let posted: Vec<(nostr_sdk::prelude::PublicKey, u64)> = page.iter().filter(|f| matches!(f.event, crate::community::v2::chat::ChatEvent::Message { .. } | crate::community::v2::chat::ChatEvent::Edit { .. })).map(|f| (f.event.opened().author, f.event.opened().at_ms)).collect();
4211 let mut new = 0usize;
4212 let mut unapplied: Vec<usize> = Vec::new();
4213 let mut outcomes: Vec<ChatPersist> = Vec::with_capacity(page.len());
4215 let mut sources: Vec<usize> = Vec::with_capacity(page.len());
4217 let stored = crate::db::events::existing_event_ids(&crate::community::v2::inbound::page_event_ids(page.iter().map(|f| &f.event))).unwrap_or_default();
4218 for (i, f) in page.iter().enumerate() {
4219 if let crate::community::v2::chat::ChatEvent::Webxdc { opened } = &f.event {
4224 if opened.author != my_pk {
4225 if let Some((topic, addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) {
4226 let Ok(npub) = ToBech32::to_bech32(&opened.author);
4227 crate::community::v2::inbound::persist_webxdc_signal(
4228 channel_id,
4229 &npub,
4230 &topic,
4231 addr.as_deref(),
4232 &opened.rumor_id.to_hex(),
4233 opened.at_ms / 1000,
4234 )
4235 .await;
4236 }
4237 }
4238 continue;
4239 }
4240 crate::community::v2::inbound::hydrate_target(&f.event, channel_id).await;
4241 let outcome = {
4242 let mut st = state::STATE.lock().await;
4243 crate::community::v2::inbound::apply_page_event_to_state(&mut st, &f.event, channel_id, &my_pk, &stored)
4244 };
4245 match outcome {
4246 Some(outcome) => {
4247 if matches!(outcome, ChatPersist::New(_)) {
4248 new += 1;
4249 }
4250 outcomes.push(outcome);
4251 sources.push(i);
4252 }
4253 None if matches!(f.event, crate::community::v2::chat::ChatEvent::Reaction { .. } | crate::community::v2::chat::ChatEvent::Edit { .. } | crate::community::v2::chat::ChatEvent::Delete { .. }) => unapplied.push(i),
4254 None => {}
4255 }
4256 }
4257 for o in &mut outcomes {
4264 if let ChatPersist::New(m) | ChatPersist::Updated { message: m, .. } = o {
4265 crate::db::attachments::verify_message_attachments(m, Some(channel_id)).await;
4266 }
4267 }
4268 crate::community::v2::inbound::persist_chat_page(channel_id, &outcomes, &session).await;
4269 if let Some(since) = since {
4270 crate::community::v2::service::owe_if_moved(channel_id, judged_on, since);
4271 }
4272 crate::community::v2::service::owe_if_departed(channel_id, &posted);
4273 {
4277 let quoted: Vec<&mut crate::types::Message> = outcomes
4278 .iter_mut()
4279 .filter_map(|o| match o {
4280 ChatPersist::New(m)
4281 | ChatPersist::Updated { message: m, .. }
4282 | ChatPersist::ReactionRemoved { message: m, .. } => Some(m),
4283 ChatPersist::Removed { .. } => None,
4284 })
4285 .collect();
4286 let _ = crate::db::events::populate_reply_contexts(quoted).await;
4287 }
4288 for outcome in &outcomes {
4294 match outcome {
4295 ChatPersist::New(msg) => crate::traits::emit_message_new(channel_id, msg),
4296 ChatPersist::Updated { message, .. }
4297 | ChatPersist::ReactionRemoved { message, .. } => {
4298 let mut message = message.clone();
4299 let target_id = message.id.clone();
4300 crate::traits::emit_message_update(channel_id, &target_id, &mut message).await;
4301 }
4302 ChatPersist::Removed { id: target_id, .. } => crate::traits::emit_event(
4303 "message_removed",
4304 &serde_json::json!({ "id": target_id, "chat_id": channel_id, "reason": "deleted" }),
4305 ),
4306 }
4307 }
4308 if let Some(listener) = crate::news::listener() {
4311 for (outcome, i) in outcomes.into_iter().zip(sources) {
4312 let event = &page[i].event;
4313 let at = match &outcome {
4314 ChatPersist::New(m) => m.at,
4315 _ => event.opened().at_ms,
4316 };
4317 if crate::news::is_news(at) {
4318 crate::community::v2::inbound::notify_chat_outcome(&*listener, channel_id, event, outcome, true).await;
4319 }
4320 }
4321 }
4322 let mut waiting = Vec::new();
4323 for i in unapplied {
4324 let f = &page[i];
4325 if crate::community::v2::inbound::awaits_target(&f.event).await {
4326 waiting.push(crate::community::v2::service::FetchedEvent { event: f.event.clone(), epoch: f.epoch, wrap: f.wrap.clone() });
4327 }
4328 }
4329 (new, waiting)
4330 })
4331 .await
4332 }
4333
4334 fn unheld_id(community_id: &str) -> Result<crate::community::CommunityId> {
4338 crate::simd::hex::hex_to_bytes_32_checked(community_id)
4339 .map(crate::community::CommunityId)
4340 .ok_or_else(|| VectorError::Other("malformed community id".into()))
4341 }
4342
4343 fn load_held(community_id: &str) -> Result<Option<crate::community::v2::community::CommunityV2>> {
4344 if community_id.len() != 64 {
4345 return Ok(None);
4346 }
4347 let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
4348 crate::db::community::load_community_v2(&cid).map_err(VectorError::Other)
4349 }
4350
4351 pub fn community_capabilities(&self, community_id: &str) -> Result<serde_json::Value> {
4359 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4360 use crate::community::roles::Permissions;
4361 let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
4362 let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
4363 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4364 let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
4367 if banned.contains(&me) && me != owner_hex {
4368 return Ok(serde_json::json!({
4369 "manage_metadata": false, "manage_channels": false, "create_invite": false, "kick": false,
4370 "ban": false, "manage_messages": false, "manage_roles": false, "manage_admin_role": false,
4371 "pin_messages": false, "control_write": false, "moderate_members": false, "view_audit_log": false,
4372 "manage_nicknames": false, "change_nickname": false,
4373 }));
4374 }
4375 let control_write = crate::community::v2::control::ControlPlane::of(&v2).can_write();
4381 let has = |p: u64| roster.is_authorized(&me, Some(&owner_hex), p);
4382 let has_ctl = |p: u64| control_write && has(p);
4383 Ok(serde_json::json!({
4384 "manage_metadata": has_ctl(Permissions::MANAGE_METADATA), "manage_channels": has_ctl(Permissions::MANAGE_CHANNELS),
4385 "create_invite": has_ctl(Permissions::CREATE_INVITE), "kick": has(Permissions::KICK), "ban": has_ctl(Permissions::BAN),
4386 "manage_messages": has(Permissions::MANAGE_MESSAGES), "manage_roles": has_ctl(Permissions::MANAGE_ROLES),
4387 "manage_admin_role": me == owner_hex && control_write,
4389 "pin_messages": has_ctl(Permissions::PIN_MESSAGES),
4390 "control_write": control_write,
4391 "moderate_members": has(Permissions::MODERATE_MEMBERS),
4393 "view_audit_log": has(Permissions::VIEW_AUDIT_LOG),
4394 "manage_nicknames": has(Permissions::MANAGE_NICKNAMES),
4396 "change_nickname": roster.may_name(&me, Some(&owner_hex), &me),
4397 }))
4398 }
4399
4400 pub async fn check_community_relays(&self, community_id: &str, relays: &[String]) -> Result<Vec<crate::community::v2::service::RelayCheck>> {
4403 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4404 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
4405 crate::community::v2::service::check_relays(&transport, &v2, relays).await.map_err(VectorError::Other)
4406 }
4407
4408 pub async fn move_community_relays(&self, community_id: &str, relays: &[String]) -> Result<crate::community::v2::service::RelayMove> {
4411 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4412 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
4413 crate::community::v2::service::move_relays(&transport, &v2, relays).await.map_err(VectorError::Other)
4414 }
4415
4416 pub async fn community_audit_log(&self, community_id: &str) -> Result<crate::community::v2::service::AuditLog> {
4419 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4420 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
4421 crate::community::v2::service::audit_log(&transport, &v2).await.map_err(VectorError::Other)
4422 }
4423
4424 pub async fn pin_community_message(&self, community_id: &str, channel_id: &str, message_id: &str) -> Result<()> {
4427 use crate::community::{transport::LiveTransport, ChannelId};
4428 let v2 = Self::load_held(community_id)?
4429 .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
4430 let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4431 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4432 crate::community::v2::service::pin_message(&transport, &v2, &ch, message_id)
4433 .await
4434 .map_err(VectorError::Other)
4435 }
4436
4437 pub async fn unpin_community_message(&self, community_id: &str, channel_id: &str, message_id: &str) -> Result<()> {
4439 use crate::community::{transport::LiveTransport, ChannelId};
4440 let v2 = Self::load_held(community_id)?
4441 .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
4442 let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4443 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4444 crate::community::v2::service::unpin_message(&transport, &v2, &ch, message_id)
4445 .await
4446 .map_err(VectorError::Other)
4447 }
4448
4449 pub async fn fetch_pinned_attachment(
4457 &self,
4458 community_id: &str,
4459 channel_id: &str,
4460 rumor_id: &str,
4461 ) -> Result<serde_json::Value> {
4462 crate::db::scoped(async move {
4463 use crate::community::ChannelId;
4464 let v2 = Self::load_held(community_id)?
4465 .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
4466 let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4467 let pins = crate::community::v2::service::read_channel_pins(&v2, &ch).map_err(VectorError::Other)?;
4468 let pin = pins
4469 .pins
4470 .iter()
4471 .find(|p| p.rumor_id == rumor_id)
4472 .ok_or_else(|| VectorError::Other("that message is not pinned".into()))?;
4473 let dir = crate::db::get_download_dir();
4474 let tag = pin
4475 .tags
4476 .iter()
4477 .find(|t| t.first().map(String::as_str) == Some("imeta"))
4478 .map(|t| nostr_sdk::prelude::Tag::custom("imeta", t[1..].to_vec()))
4479 .ok_or_else(|| VectorError::Other("this pin carries no attachment".into()))?;
4480 let attachment = crate::community::attachments::attachment_from_imeta(&tag, &dir)
4481 .ok_or_else(|| VectorError::Other("this pin's attachment metadata is malformed".into()))?;
4482
4483 let respond = |path: &str| {
4484 serde_json::json!({
4485 "path": path,
4486 "name": attachment.name.to_string(),
4487 "extension": attachment.extension.to_string(),
4488 })
4489 };
4490
4491 let expected = attachment.original_hash.as_deref();
4495 let in_memory = crate::media::ram::cache().admits(attachment.size);
4498 let keep = !in_memory || crate::media::keep_media();
4499 if let Some(hash) = expected.and_then(crate::simd::hex::hex_to_bytes_32_checked).filter(|h| crate::media::resident(h)) {
4500 return Ok(respond(&crate::media::MediaRef::held(&hash)));
4501 }
4502 let path = std::path::PathBuf::from(&*attachment.path);
4503 if let Ok(bytes) = std::fs::read(&path) {
4504 match expected {
4505 Some(want) if crate::crypto::sha256_hex(&bytes) == want => return Ok(respond(&path.to_string_lossy())),
4506 None => return Ok(respond(&path.to_string_lossy())),
4507 _ => {} }
4509 }
4510
4511 let author_npub = nostr_sdk::prelude::PublicKey::from_hex(&pin.author)
4512 .ok()
4513 .and_then(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok());
4514 let bytes = self.download_attachment_from(&attachment, author_npub.as_deref()).await?;
4515 let hash = crate::crypto::sha256_hex(&bytes);
4516 if expected.is_some_and(|want| hash != want) {
4517 return Err(VectorError::Other("downloaded bytes do not match the pinned content hash".into()));
4518 }
4519 let held = crate::simd::hex::hex_to_bytes_32(&hash);
4520 let mime = crate::crypto::mime_from_extension(&attachment.extension.to_ascii_lowercase());
4521 if keep {
4523 #[cfg(not(target_arch = "wasm32"))]
4524 crate::media::store::keep_sealed(&bytes, held, mime, crate::db::media_store::Origin::Sealed)
4525 .map_err(|e| VectorError::Other(format!("could not keep the attachment: {e}")))?;
4526 #[cfg(target_arch = "wasm32")]
4527 crate::media::store::keep_sealed(&bytes, held, mime, crate::db::media_store::Origin::Sealed)
4528 .await
4529 .map_err(|e| VectorError::Other(format!("could not keep the attachment: {e}")))?;
4530 }
4531 if in_memory {
4532 match crate::media::ram::insert(held, bytes, mime) {
4533 Ok(_) => {}
4534 Err(_) if keep => {}
4535 Err(_) => return Err(VectorError::Other("too much media is open to show this one".into())),
4536 }
4537 }
4538 Ok(respond(&crate::media::MediaRef::held(&held)))
4539 })
4540 .await
4541 }
4542
4543 pub fn get_channel_pins(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
4547 use crate::community::ChannelId;
4548 let Some(v2) = Self::load_held(community_id)? else {
4549 return Ok(serde_json::json!({ "pins": [], "sealed": false, "version": 0 }));
4550 };
4551 let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4552 let pins = crate::community::v2::service::read_channel_pins(&v2, &ch).map_err(VectorError::Other)?;
4553 serde_json::to_value(&pins).map_err(|e| VectorError::Other(e.to_string()))
4554 }
4555
4556 pub fn community_role_graph(&self, community_id: &str) -> Result<serde_json::Value> {
4564 use nostr_sdk::prelude::{PublicKey, ToBech32};
4565 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4566 let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
4568 let roles: Vec<serde_json::Value> = roster
4569 .roles
4570 .iter()
4571 .map(|r| {
4572 let channel_id = match &r.scope {
4575 crate::community::roles::RoleScope::Channel(c) => Some(c.to_ascii_lowercase()),
4576 crate::community::roles::RoleScope::Server => None,
4577 };
4578 serde_json::json!({
4579 "role_id": r.role_id,
4580 "name": r.name,
4581 "position": r.position,
4582 "color": r.color,
4583 "channel_id": channel_id,
4584 "display": r.display,
4585 })
4586 })
4587 .collect();
4588 let grants: Vec<serde_json::Value> = roster
4589 .grants
4590 .iter()
4591 .filter(|g| !banned.contains(&g.member))
4592 .filter_map(|g| {
4593 let npub = PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok())?;
4594 Some(serde_json::json!({ "npub": npub, "role_ids": g.role_ids }))
4595 })
4596 .collect();
4597 let activated = roster.everyone.is_some();
4599 let mut readers = serde_json::Map::new();
4600 if activated {
4601 if let Some(v2) = Self::load_held(community_id)? {
4602 let owner_hex = v2.owner().ok().map(|o| o.to_hex());
4603 let mut candidates: std::collections::BTreeSet<PublicKey> =
4604 crate::community::v2::service::stored_memberlist(&v2).unwrap_or_default().into_iter().collect();
4605 candidates.extend(roster.grants.iter().filter_map(|g| PublicKey::from_hex(&g.member).ok()));
4606 for ch in v2.channels.iter().filter(|c| c.private) {
4607 let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
4608 let npubs: Vec<String> = candidates
4609 .iter()
4610 .filter(|pk| !banned.contains(&pk.to_hex()) && roster.is_entitled(owner_hex.as_deref(), &pk.to_hex(), &chan, &[], &[]))
4611 .filter_map(|pk| pk.to_bech32().ok())
4612 .collect();
4613 readers.insert(chan, npubs.into());
4614 }
4615 }
4616 }
4617 Ok(serde_json::json!({ "roles": roles, "grants": grants, "activated": activated, "readers": readers }))
4618 }
4619
4620 pub fn community_roles_view(&self, community_id: &str) -> Result<serde_json::Value> {
4625 use crate::community::roles::{Permissions, RoleScope};
4626 let v2 = Self::load_held(community_id)?
4627 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4628 let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
4629 let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
4630 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4631 let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
4632 let is_owner = me == owner_hex;
4633 let can_manage = is_owner
4634 || (!banned.contains(&me) && roster.is_authorized(&me, Some(&owner_hex), Permissions::MANAGE_ROLES));
4635 let rank = if is_owner { Some(0) } else { roster.highest_position(&me) };
4636 let grantable = if is_owner { u64::MAX } else { roster.effective_permissions(&me).0 };
4637 let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().collect();
4638 roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
4639 let activated = Self::roles_v2_active(community_id, &roster);
4640 let roles: Vec<serde_json::Value> = roles
4641 .into_iter()
4642 .map(|r| {
4643 let holders: Vec<String> = roster
4644 .grants
4645 .iter()
4646 .filter(|g| !banned.contains(&g.member) && g.role_ids.iter().any(|id| id == &r.role_id))
4647 .filter_map(|g| nostr_sdk::prelude::PublicKey::from_hex(&g.member).ok())
4648 .filter_map(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok())
4649 .collect();
4650 serde_json::json!({
4651 "role_id": r.role_id,
4652 "name": r.name,
4653 "position": r.position,
4654 "color": r.color,
4655 "permissions": r.permissions.0.to_string(),
4656 "channel_id": match &r.scope { RoleScope::Channel(c) => Some(c.to_ascii_lowercase()), RoleScope::Server => None },
4657 "holders": holders,
4658 "display": r.display,
4659 "mentionable": r.mentionable,
4660 "manageable": can_manage && (is_owner || {
4661 let support = roster.permissions_above(&me, r.position);
4662 support.contains(Permissions::MANAGE_ROLES) && r.permissions.0 & !support.0 == 0
4663 }),
4664 })
4665 })
4666 .collect();
4667 let channels: Vec<serde_json::Value> = v2
4668 .channels
4669 .iter()
4670 .map(|c| serde_json::json!({
4671 "channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
4672 "name": c.name,
4673 "private": c.private,
4674 }))
4675 .collect();
4676 Ok(serde_json::json!({
4677 "is_owner": is_owner,
4678 "can_manage": can_manage,
4679 "rank": rank,
4680 "grantable": grantable.to_string(),
4681 "activated": activated,
4683 "everyone": roster.everyone.map(|p| p.0.to_string()),
4684 "everyone_editable": activated && (is_owner || roster.permissions_above(&me, u32::MAX).contains(Permissions::MANAGE_ROLES)),
4685 "everyone_default": crate::community::v2::roles::EVERYONE_DEFAULT.to_string(),
4686 "roles": roles,
4687 "channels": channels,
4688 "max_roles": crate::community::v2::roles::MAX_ROLES_PER_COMMUNITY,
4689 "max_per_member": crate::community::v2::roles::MAX_ROLES_PER_MEMBER,
4690 }))
4691 }
4692
4693 fn parse_permissions(s: &str) -> Result<u64> {
4694 if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
4695 return Err(VectorError::Other(format!("permissions must be a decimal string, got {s:?}")));
4696 }
4697 s.parse::<u64>().map_err(|_| VectorError::Other("permissions out of range".into()))
4698 }
4699
4700 fn role_scope(channel_id: Option<&str>) -> Result<crate::community::roles::RoleScope> {
4701 use crate::community::roles::RoleScope;
4702 match channel_id {
4703 None => Ok(RoleScope::Server),
4704 Some(c) if c.len() == 64 && c.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(RoleScope::Channel(c.to_ascii_lowercase())),
4705 Some(_) => Err(VectorError::Other("channel_id must be 32-byte hex".into())),
4706 }
4707 }
4708
4709 pub async fn create_role(&self, community_id: &str, name: &str, color: u32, permissions: &str, channel_id: Option<&str>) -> Result<String> {
4711 let v2 = Self::load_held(community_id)?
4712 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4713 let perms = Self::parse_permissions(permissions)?;
4714 let scope = Self::role_scope(channel_id)?;
4715 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4716 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4717 let id = if Self::roles_v2_active(community_id, &roster) {
4718 if channel_id.is_some() {
4719 return Err(VectorError::Other("on the new roles, channel access is set on the channel".into()));
4720 }
4721 crate::community::v2::service::create_role_v2(&transport, &v2, name, color, perms).await
4722 } else {
4723 crate::community::v2::service::create_role(&transport, &v2, name, color, perms, scope).await
4724 }
4725 .map_err(VectorError::Other)?;
4726 Self::converge_v2_authority(&transport, community_id).await;
4727 Ok(id)
4728 }
4729
4730 pub async fn edit_role(&self, community_id: &str, role_id: &str, name: &str, color: u32, permissions: &str, channel_id: Option<&str>) -> Result<()> {
4732 self.edit_role_shown(community_id, role_id, name, color, permissions, channel_id, None, None).await
4733 }
4734
4735 #[allow(clippy::too_many_arguments)]
4738 pub async fn edit_role_shown(
4739 &self,
4740 community_id: &str,
4741 role_id: &str,
4742 name: &str,
4743 color: u32,
4744 permissions: &str,
4745 channel_id: Option<&str>,
4746 display: Option<bool>,
4747 mentionable: Option<bool>,
4748 ) -> Result<()> {
4749 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4750 if Self::roles_v2_active(community_id, &roster) {
4751 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4752 let perms = Self::parse_permissions(permissions)?;
4753 let current = roster.role(role_id).ok_or_else(|| VectorError::Other("no such role".into()))?;
4754 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4755 crate::community::v2::service::edit_role_v2(
4756 &transport,
4757 &v2,
4758 role_id,
4759 name,
4760 color,
4761 perms,
4762 display.unwrap_or(current.display),
4763 mentionable.unwrap_or(current.mentionable),
4764 )
4765 .await
4766 .map_err(VectorError::Other)?;
4767 Self::converge_v2_authority(&transport, community_id).await;
4768 return Ok(());
4769 }
4770 let v2 = Self::load_held(community_id)?
4771 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4772 let perms = Self::parse_permissions(permissions)?;
4773 let scope = Self::role_scope(channel_id)?;
4774 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4775 crate::community::v2::service::edit_role(&transport, &v2, role_id, name, color, perms, scope)
4776 .await
4777 .map_err(VectorError::Other)?;
4778 Self::converge_v2_authority(&transport, community_id).await;
4779 Ok(())
4780 }
4781
4782 pub async fn reorder_roles(&self, community_id: &str, ordered: &[String]) -> Result<usize> {
4784 let v2 = Self::load_held(community_id)?
4785 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4786 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4787 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4788 if Self::roles_v2_active(community_id, &roster) {
4789 let moved = crate::community::v2::service::reorder_roles_v2(&transport, &v2, ordered).await.map_err(VectorError::Other)?;
4790 if moved > 0 {
4791 Self::converge_v2_authority(&transport, community_id).await;
4792 }
4793 return Ok(moved);
4794 }
4795 let moved = crate::community::v2::service::reorder_roles(&transport, &v2, ordered)
4796 .await
4797 .map_err(VectorError::Other)?;
4798 if moved > 0 {
4799 Self::converge_v2_authority(&transport, community_id).await;
4800 }
4801 Ok(moved)
4802 }
4803
4804 fn roles_v2_active(community_id: &str, roster: &crate::community::roles::CommunityRoles) -> bool {
4806 if roster.everyone.is_some() {
4807 return true;
4808 }
4809 let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(community_id) else { return false };
4810 let everyone = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(&crate::community::CommunityId(cid)));
4811 crate::db::community::get_edition_head(community_id, &everyone).ok().flatten().is_some()
4812 }
4813
4814 fn held_v2(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
4815 Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("this needs a Concord v2 community".into()))
4816 }
4817
4818 fn short_transport() -> crate::community::transport::LiveTransport {
4819 crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12))
4820 }
4821
4822 fn view_named(view: &str) -> Result<crate::community::v2::community::ChannelView> {
4824 crate::community::v2::community::ChannelView::try_parse(view)
4825 .ok_or_else(|| VectorError::Other(format!("no channel view named {view:?}: chat, forum or voice")))
4826 }
4827
4828 fn id32(hex: &str, what: &str) -> Result<[u8; 32]> {
4829 crate::simd::hex::hex_to_bytes_32_checked(hex).ok_or_else(|| VectorError::Other(format!("{what} must be 32-byte hex")))
4830 }
4831
4832 pub fn channel_permissions_view(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
4835 use crate::community::roles::{OverwriteTarget, Permissions};
4836 let v2 = Self::held_v2(community_id)?;
4837 let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
4838 let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
4839 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4840 let is_owner = me == owner_hex;
4841 let chan = channel_id.to_ascii_lowercase();
4842 let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().collect();
4843 roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
4844 let overwrites: Vec<serde_json::Value> = roster
4845 .overwrites
4846 .iter()
4847 .filter(|o| o.scope == chan)
4848 .map(|o| {
4849 let (kind, id) = match &o.target {
4850 OverwriteTarget::Everyone => ("everyone", None),
4851 OverwriteTarget::Role(id) => ("role", Some(id.clone())),
4852 OverwriteTarget::Member(m) => ("member", Some(m.clone())),
4853 };
4854 let npub = (kind == "member").then(|| id.as_deref().and_then(|m| nostr_sdk::prelude::PublicKey::from_hex(m).ok()).and_then(|pk| ToBech32::to_bech32(&pk).ok())).flatten();
4855 serde_json::json!({ "kind": kind, "id": id, "npub": npub, "allow": o.allow.0.to_string(), "deny": o.deny.0.to_string() })
4856 })
4857 .collect();
4858 let category = crate::simd::hex::hex_to_bytes_32_checked(&chan)
4859 .and_then(|b| v2.channel(&crate::community::ChannelId(b)))
4860 .and_then(|c| c.category())
4861 .filter(|k| v2.categories.iter().any(|x| x.id == *k))
4862 .map(|k| crate::simd::hex::bytes_to_hex_32(&k));
4863 Ok(serde_json::json!({
4864 "activated": Self::roles_v2_active(community_id, &roster),
4865 "category": category,
4867 "synced": roster.syncs.get(&chan),
4868 "can_manage": is_owner || roster.is_authorized(&me, Some(&owner_hex), Permissions::MANAGE_ROLES),
4869 "grantable": if is_owner { u64::MAX.to_string() } else { roster.effective_permissions(&me).0.to_string() },
4870 "roles": roles.iter().map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name, "color": r.color, "position": r.position })).collect::<Vec<_>>(),
4871 "overwrites": overwrites,
4872 "members": crate::community::v2::service::stored_memberlist(&v2)
4874 .unwrap_or_default()
4875 .into_iter()
4876 .filter(|pk| pk.to_hex() != owner_hex)
4877 .map(|pk| serde_json::json!({ "id": pk.to_hex(), "npub": ToBech32::to_bech32(&pk).ok() }))
4878 .collect::<Vec<_>>(),
4879 }))
4880 }
4881
4882 pub async fn set_channel_overwrite(&self, community_id: &str, scope_id: &str, kind: &str, target_id: Option<&str>, allow: &str, deny: &str) -> Result<()> {
4885 use crate::community::roles::OverwriteTarget;
4886 let v2 = Self::held_v2(community_id)?;
4887 let target = match (kind, target_id) {
4888 ("everyone", _) => OverwriteTarget::Everyone,
4889 ("role", Some(id)) => OverwriteTarget::Role(crate::simd::hex::bytes_to_hex_32(&Self::id32(id, "role_id")?)),
4890 ("member", Some(m)) => OverwriteTarget::Member(
4891 nostr_sdk::prelude::PublicKey::parse(m).map_err(|_| VectorError::Other("invalid member key".into()))?.to_hex(),
4892 ),
4893 _ => return Err(VectorError::Other("an overwrite targets everyone, a role or a member".into())),
4894 };
4895 let (allow, deny) = (Self::parse_permissions(allow)?, Self::parse_permissions(deny)?);
4896 let transport = Self::short_transport();
4897 crate::community::v2::service::set_overwrite(&transport, &v2, Self::id32(scope_id, "scope_id")?, target, allow, deny)
4898 .await
4899 .map_err(VectorError::Other)?;
4900 Self::converge_v2_authority(&transport, community_id).await;
4901 Ok(())
4902 }
4903
4904 pub async fn set_channel_sync(&self, community_id: &str, channel_id: &str, category_id: Option<&str>) -> Result<()> {
4906 let v2 = Self::held_v2(community_id)?;
4907 let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
4908 let category = category_id.map(|c| Self::id32(c, "category_id")).transpose()?;
4909 let transport = Self::short_transport();
4910 crate::community::v2::service::set_channel_sync(&transport, &v2, &channel, category).await.map_err(VectorError::Other)?;
4911 Self::converge_v2_authority(&transport, community_id).await;
4912 Ok(())
4913 }
4914
4915 pub fn channel_send_denied(&self, community_id: &str, channel_id: &str, npubs: &[String]) -> Result<Vec<String>> {
4918 use crate::community::roles::Permissions;
4919 let v2 = Self::held_v2(community_id)?;
4920 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4921 if roster.everyone.is_none() {
4922 return Ok(Vec::new());
4923 }
4924 let owner = v2.owner().ok().map(|o| o.to_hex());
4925 let chan = channel_id.to_ascii_lowercase();
4926 let ch = Self::id32(channel_id, "channel_id").ok().and_then(|b| v2.channel(&crate::community::ChannelId(b)));
4927 let private = ch.is_some_and(|c| c.private);
4928 Ok(npubs
4929 .iter()
4930 .filter(|n| {
4931 nostr_sdk::prelude::PublicKey::parse(n.as_str())
4932 .is_ok_and(|pk| !roster.channel_permissions(owner.as_deref(), &pk.to_hex(), &chan, private).contains(Permissions::SEND_MESSAGES))
4933 })
4934 .cloned()
4935 .collect())
4936 }
4937
4938 pub fn community_mentions(&self, community_id: &str) -> Result<serde_json::Value> {
4942 use crate::community::roles::Permissions;
4943 use nostr_sdk::prelude::PublicKey;
4944 let v2 = Self::held_v2(community_id)?;
4945 let owner = v2.owner().map_err(VectorError::Other)?.to_hex();
4946 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4947 let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
4948 let me = crate::state::my_public_key().map(|pk| pk.to_hex()).unwrap_or_default();
4949 let members: std::collections::BTreeSet<&str> = std::iter::once(owner.as_str()).chain(roster.grants.iter().map(|g| g.member.as_str())).collect();
4950 let pingers: Vec<String> = members
4951 .into_iter()
4952 .filter(|m| !banned.iter().any(|b| b == m) && roster.is_authorized(m, Some(&owner), Permissions::MENTION_EVERYONE))
4953 .filter_map(|m| PublicKey::from_hex(m).ok()?.to_bech32().ok())
4954 .collect();
4955 let held: std::collections::HashSet<&str> = roster.roles_of(&me).map(|r| r.role_id.as_str()).collect();
4956 let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().filter(|r| crate::community::mentions::is_role_id(&r.role_id)).collect();
4957 roles.sort_by_key(|r| r.position);
4958 let roles: Vec<serde_json::Value> = roles
4959 .into_iter()
4960 .map(|r| serde_json::json!({ "id": r.role_id, "name": r.name, "color": r.color, "mentionable": r.mentionable, "held": held.contains(r.role_id.as_str()) }))
4961 .collect();
4962 Ok(serde_json::json!({
4963 "anyone": roster.everyone.is_some_and(|e| e.contains(Permissions::MENTION_EVERYONE)),
4964 "pingers": pingers,
4965 "roles": roles,
4966 }))
4967 }
4968
4969 pub fn role_mentions_ping_me(&self, community_id: &str, author_npub: &str, content: &str, role_ids: &[String]) -> bool {
4971 if role_ids.is_empty() {
4972 return false;
4973 }
4974 let (Some(me), Ok(author), Ok(Some(held))) = (
4975 crate::state::my_public_key(),
4976 nostr_sdk::prelude::PublicKey::parse(author_npub),
4977 Self::load_held(community_id),
4978 ) else {
4979 return false;
4980 };
4981 let (Ok(owner), Ok(roster)) = (held.owner(), crate::db::community::get_community_roles(community_id)) else { return false };
4982 let author = author.to_hex();
4983 if crate::db::community::get_community_banlist(community_id).unwrap_or_default().contains(&author) {
4984 return false;
4985 }
4986 crate::community::mentions::pings(&roster, Some(&owner.to_hex()), &author, &me.to_hex(), content, role_ids)
4987 }
4988
4989 pub fn post_silenced(&self, community_id: &str, channel_id: &str, author_npub: &str) -> bool {
4992 if self.channel_send_denied(community_id, channel_id, &[author_npub.to_string()]).is_ok_and(|d| !d.is_empty()) {
4993 return true;
4994 }
4995 let (Ok(v2), Ok(author)) = (Self::held_v2(community_id), nostr_sdk::prelude::PublicKey::parse(author_npub)) else { return false };
4996 crate::community::v2::service::community_timeouts(&v2).is_ok_and(|t| t.contains_key(&author))
4997 }
4998
4999 pub fn community_timeouts(&self, community_id: &str) -> Result<serde_json::Value> {
5001 let v2 = Self::held_v2(community_id)?;
5002 let running = crate::community::v2::service::community_timeouts(&v2).map_err(VectorError::Other)?;
5003 Ok(running
5004 .into_iter()
5005 .filter_map(|(pk, (from, until))| Some((pk.to_bech32().ok()?, serde_json::json!({ "from": from, "until": until }))))
5006 .collect::<serde_json::Map<_, _>>()
5007 .into())
5008 }
5009
5010 pub async fn timeout_member(&self, community_id: &str, npub: &str, seconds: u64) -> Result<()> {
5012 let v2 = Self::held_v2(community_id)?;
5013 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5014 crate::community::v2::service::timeout_member(&Self::short_transport(), &v2, &member, seconds).await.map_err(VectorError::Other)
5015 }
5016
5017 pub fn community_nicknames(&self, community_id: &str) -> Result<serde_json::Value> {
5019 let v2 = Self::held_v2(community_id)?;
5020 let named = crate::community::v2::service::community_nicknames(&v2).map_err(VectorError::Other)?;
5021 Ok(named
5022 .into_iter()
5023 .filter_map(|(pk, nick)| Some((pk.to_bech32().ok()?, serde_json::Value::String(nick))))
5024 .collect::<serde_json::Map<_, _>>()
5025 .into())
5026 }
5027
5028 pub fn member_nickname(&self, community_id: &str, npub: &str) -> Option<String> {
5030 let v2 = Self::held_v2(community_id).ok()?;
5031 let member = nostr_sdk::prelude::PublicKey::parse(npub).ok()?;
5032 crate::community::v2::service::community_nicknames(&v2).ok()?.remove(&member)
5033 }
5034
5035 pub async fn set_community_nickname(&self, community_id: &str, npub: &str, nickname: &str) -> Result<()> {
5037 let v2 = Self::held_v2(community_id)?;
5038 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5039 crate::community::v2::service::set_nickname(&Self::short_transport(), &v2, &member, nickname).await.map_err(VectorError::Other)
5040 }
5041
5042 pub async fn delete_role(&self, community_id: &str, role_id: &str) -> Result<()> {
5044 let v2 = Self::held_v2(community_id)?;
5045 let transport = Self::short_transport();
5046 crate::community::v2::service::delete_role_v2(&transport, &v2, role_id).await.map_err(VectorError::Other)?;
5047 Self::converge_v2_authority(&transport, community_id).await;
5048 Ok(())
5049 }
5050
5051 pub async fn set_everyone_permissions(&self, community_id: &str, permissions: &str) -> Result<()> {
5053 let v2 = Self::held_v2(community_id)?;
5054 let perms = Self::parse_permissions(permissions)?;
5055 let transport = Self::short_transport();
5056 crate::community::v2::service::set_everyone(&transport, &v2, perms).await.map_err(VectorError::Other)?;
5057 Self::converge_v2_authority(&transport, community_id).await;
5058 Ok(())
5059 }
5060
5061 pub async fn activate_roles_v2(&self, community_id: &str, everyone: &str) -> Result<usize> {
5063 let v2 = Self::held_v2(community_id)?;
5064 let perms = Self::parse_permissions(everyone)?;
5065 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
5066 let carried = crate::community::v2::service::activate_roles_v2(&transport, &v2, perms).await.map_err(VectorError::Other)?;
5067 Self::converge_v2_authority(&transport, community_id).await;
5068 Ok(carried)
5069 }
5070
5071 pub async fn create_category(&self, community_id: &str, name: &str) -> Result<String> {
5073 let v2 = Self::held_v2(community_id)?;
5074 let id = crate::community::v2::service::create_category(&Self::short_transport(), &v2, name).await.map_err(VectorError::Other)?;
5075 Ok(crate::simd::hex::bytes_to_hex_32(&id))
5076 }
5077
5078 pub async fn rename_category(&self, community_id: &str, category_id: &str, name: &str) -> Result<()> {
5079 let v2 = Self::held_v2(community_id)?;
5080 crate::community::v2::service::rename_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?, name).await.map_err(VectorError::Other)
5081 }
5082
5083 pub async fn delete_category(&self, community_id: &str, category_id: &str) -> Result<()> {
5085 let v2 = Self::held_v2(community_id)?;
5086 crate::community::v2::service::delete_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?).await.map_err(VectorError::Other)
5087 }
5088
5089 pub async fn move_category(&self, community_id: &str, category_id: &str, index: usize) -> Result<()> {
5091 let v2 = Self::held_v2(community_id)?;
5092 crate::community::v2::service::move_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?, index).await.map_err(VectorError::Other)
5093 }
5094
5095 pub async fn move_channel(&self, community_id: &str, channel_id: &str, category_id: Option<&str>, index: usize) -> Result<()> {
5097 let v2 = Self::held_v2(community_id)?;
5098 let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
5099 let category = category_id.map(|c| Self::id32(c, "category_id")).transpose()?;
5100 crate::community::v2::service::move_channel(&Self::short_transport(), &v2, &channel, category, index).await.map_err(VectorError::Other)
5101 }
5102
5103 pub async fn edit_channel_details(&self, community_id: &str, channel_id: &str, name: &str, topic: Option<&str>, view: &str) -> Result<()> {
5105 let view = Self::view_named(view)?;
5106 let v2 = Self::held_v2(community_id)?;
5107 let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
5108 crate::community::v2::service::edit_channel_details(&Self::short_transport(), &v2, &channel, name, topic, view).await.map_err(VectorError::Other)
5109 }
5110
5111 pub async fn set_channel_private(&self, community_id: &str, channel_id: &str, private: bool) -> Result<()> {
5113 let v2 = Self::held_v2(community_id)?;
5114 let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
5115 let transport = Self::short_transport();
5116 if private {
5117 return crate::community::v2::service::privatize_channel(&transport, &v2, &channel).await.map_err(VectorError::Other);
5118 }
5119 let mut meta = v2.channel(&channel).ok_or_else(|| VectorError::Other("unknown channel".into()))?.metadata();
5120 if !meta.private {
5121 return Ok(());
5122 }
5123 meta.private = false;
5125 meta.extra.remove("creator");
5126 meta.extra.remove("public_until");
5127 crate::community::v2::service::edit_channel_metadata(&transport, &v2, &channel, &meta).await.map_err(VectorError::Other)
5128 }
5129
5130 pub async fn set_member_roles(&self, community_id: &str, npub: &str, role_ids: Vec<String>) -> Result<()> {
5132 let v2 = Self::load_held(community_id)?
5133 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
5134 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5135 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5136 crate::community::v2::service::set_member_roles(&transport, &v2, &member, role_ids)
5137 .await
5138 .map_err(VectorError::Other)?;
5139 Self::converge_v2_authority(&transport, community_id).await;
5140 Ok(())
5141 }
5142
5143 pub async fn modify_member_roles(&self, community_id: &str, npub: &str, add: &[String], remove: &[String]) -> Result<()> {
5146 let v2 = Self::load_held(community_id)?
5147 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
5148 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5149 let (add, remove): (Vec<String>, Vec<String>) =
5150 (add.iter().map(|r| r.to_ascii_lowercase()).collect(), remove.iter().map(|r| r.to_ascii_lowercase()).collect());
5151 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5152 crate::community::v2::service::change_member_roles(&transport, &v2, &member, move |current| {
5153 let mut next: Vec<String> = current.iter().map(|r| r.to_ascii_lowercase()).filter(|r| !remove.contains(r)).collect();
5154 next.extend(add.into_iter().filter(|r| !remove.contains(r)));
5155 next
5156 })
5157 .await
5158 .map_err(VectorError::Other)?;
5159 Self::converge_v2_authority(&transport, community_id).await;
5160 Ok(())
5161 }
5162
5163 pub fn member_has_permission(&self, community_id: &str, npub: &str, permission: u64) -> Result<bool> {
5179 use nostr_sdk::prelude::PublicKey;
5180 let who = PublicKey::parse(npub).map_err(|_| VectorError::Other(format!("invalid npub: {npub}")))?.to_hex();
5181 let owner_hex = Self::load_held(community_id)?
5182 .ok_or_else(|| VectorError::Other("community not found".into()))?
5183 .owner()
5184 .map_err(VectorError::Other)?
5185 .to_hex();
5186 if who != owner_hex && crate::db::community::get_community_banlist(community_id).unwrap_or_default().contains(&who) {
5187 return Ok(false);
5188 }
5189 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5190 Ok(roster.is_authorized(&who, Some(&owner_hex), permission))
5191 }
5192
5193 pub fn community_roles(&self, community_id: &str) -> Result<serde_json::Value> {
5196 use nostr_sdk::prelude::{PublicKey, ToBech32};
5197 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5198 let owner = v2.owner().map_err(VectorError::Other)?;
5199 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5200 let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
5202 let admins: Vec<String> = roster.grants.iter()
5203 .filter(|g| roster.is_admin(&g.member) && !banned.contains(&g.member))
5204 .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
5205 .collect();
5206 Ok(serde_json::json!({ "owner": owner.to_bech32().ok(), "admins": admins }))
5207 }
5208
5209 async fn converge_v2_authority(
5218 transport: &crate::community::transport::LiveTransport,
5219 community_id: &str,
5220 ) {
5221 crate::db::scoped(async move {
5222 if let Ok(Some(fresh)) = Self::load_held(community_id) {
5225 let _ = crate::community::v2::service::follow_control(transport, &fresh).await;
5226 if let Ok(added) = crate::community::v2::service::sync_guestbook(transport, &fresh).await {
5231 if !added.is_empty() {
5232 traits::emit_event_json(
5233 "community_refreshed",
5234 serde_json::json!({ "community_id": community_id }),
5235 );
5236 }
5237 }
5238 }
5239 })
5240 .await
5241 }
5242
5243 pub async fn grant_admin(&self, community_id: &str, npub: &str) -> Result<()> {
5245 use crate::community::transport::LiveTransport;
5246 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5247 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5248 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5249 crate::community::v2::service::grant_admin(&transport, &v2, &member)
5250 .await
5251 .map_err(VectorError::Other)?;
5252 Self::converge_v2_authority(&transport, community_id).await;
5253 Ok(())
5254 }
5255
5256 pub async fn revoke_admin(&self, community_id: &str, npub: &str) -> Result<()> {
5258 use crate::community::transport::LiveTransport;
5259 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5260 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5261 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5262 crate::community::v2::service::revoke_admin(&transport, &v2, &member)
5263 .await
5264 .map_err(VectorError::Other)?;
5265 Self::converge_v2_authority(&transport, community_id).await;
5266 Ok(())
5267 }
5268
5269 pub async fn kick_member(&self, community_id: &str, npub: &str) -> Result<()> {
5271 crate::db::scoped(async move {
5272 use crate::community::transport::LiveTransport;
5273 let pk = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5274 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5275 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5276 crate::community::v2::service::kick_member(&transport, &v2, &pk)
5277 .await
5278 .map_err(VectorError::Other)?;
5279 if let Ok(fresh) = crate::community::v2::service::sync_guestbook(&transport, &v2).await {
5284 if !fresh.is_empty() {
5285 emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
5286 }
5287 }
5288 Self::converge_v2_authority(&transport, community_id).await;
5289 Ok(())
5290 })
5291 .await
5292 }
5293
5294 pub async fn set_member_banned(&self, community_id: &str, npub: &str, banned: bool) -> Result<()> {
5300 self.set_members_banned(community_id, &[npub], banned).await
5301 }
5302
5303 pub async fn set_members_banned(&self, community_id: &str, npubs: &[&str], banned: bool) -> Result<()> {
5313 use crate::community::{transport::LiveTransport, CommunityId};
5314 if npubs.is_empty() {
5315 return Ok(());
5316 }
5317 let mut pks: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(npubs.len());
5319 for n in npubs {
5320 let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5321 if !pks.contains(&pk) {
5322 pks.push(pk);
5323 }
5324 }
5325 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5326 if community_id.len() != 64 {
5330 return Err(VectorError::Other("malformed community id".into()));
5331 }
5332 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5333 crate::community::v2::service::set_members_banned(&transport, &cid, &pks, banned)
5334 .await
5335 .map_err(VectorError::Other)?;
5336 Self::invalidate_raid_report(community_id);
5339 Self::announce_ban_change(community_id);
5340 Ok(())
5341 }
5342
5343 fn announce_ban_change(community_id: &str) {
5347 emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
5348 }
5349
5350 pub async fn rescue_stranded_members(&self, community_id: &str, npubs: &[&str]) -> Result<serde_json::Value> {
5361 use nostr_sdk::prelude::PublicKey;
5362 let community = Self::load_held(community_id)?
5363 .ok_or_else(|| VectorError::Other("rescuing requires a Concord v2 community".into()))?;
5364 let mut targets: Vec<PublicKey> = Vec::with_capacity(npubs.len());
5365 for n in npubs {
5366 let pk = PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5367 if !targets.contains(&pk) {
5368 targets.push(pk);
5369 }
5370 }
5371 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
5372 let report = crate::community::v2::service::rescue_stranded_members(&transport, &community, &targets)
5373 .await
5374 .map_err(VectorError::Other)?;
5375 serde_json::to_value(report).map_err(|e| VectorError::Other(e.to_string()))
5376 }
5377
5378 pub async fn repair_community_roster(&self, community_id: &str) -> Result<serde_json::Value> {
5389 use crate::community::CommunityId;
5390 if community_id.len() != 64 {
5391 return Err(VectorError::Other("malformed community id".into()));
5392 }
5393 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5394 if crate::db::community::load_community_v2(&cid).map_err(VectorError::Other)?.is_none() {
5395 return Err(VectorError::Other("not a held Concord v2 community".into()));
5396 }
5397 let before = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5398 let before_at = crate::db::community::get_community_roles_at(community_id).map_err(VectorError::Other)?;
5399 crate::db::community::set_community_roles(community_id, &before, 0).map_err(VectorError::Other)?;
5400 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
5402 let community = crate::db::community::load_community_v2(&cid)
5403 .map_err(VectorError::Other)?
5404 .ok_or_else(|| VectorError::Other("community vanished mid-repair".into()))?;
5405 let follow = crate::community::v2::service::follow_control(&transport, &community).await;
5406 let after = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5407 Ok(serde_json::json!({
5408 "provenance_before": before_at,
5409 "provenance_after": crate::db::community::get_community_roles_at(community_id).unwrap_or(0),
5410 "roles_before": before.roles.len(),
5411 "grants_before": before.grants.len(),
5412 "roles_after": after.roles.len(),
5413 "grants_after": after.grants.len(),
5414 "fold_error": follow.as_ref().err().cloned(),
5415 "repaired": after.grants.len() > before.grants.len(),
5416 }))
5417 }
5418
5419 pub async fn explain_epoch_state(&self, community_id: &str) -> Result<serde_json::Value> {
5429 use crate::community::{transport::LiveTransport, CommunityId};
5430 if community_id.len() != 64 {
5431 return Err(VectorError::Other("malformed community id".into()));
5432 }
5433 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5434 let community = crate::db::community::load_community_v2(&cid)
5435 .map_err(VectorError::Other)?
5436 .ok_or_else(|| VectorError::Other("not a held Concord v2 community".into()))?;
5437 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(15));
5438 crate::community::v2::service::explain_epoch_state(&transport, &community)
5439 .await
5440 .map_err(VectorError::Other)
5441 }
5442
5443 pub async fn contain_raid(
5456 &self,
5457 community_id: &str,
5458 npubs: &[&str],
5459 window_start_secs: u64,
5460 cut_also: &[&str],
5461 ) -> Result<crate::community::v2::service::ContainmentReport> {
5462 use crate::community::{transport::LiveTransport, CommunityId};
5463 if community_id.len() != 64 {
5464 return Err(VectorError::Other("malformed community id".into()));
5465 }
5466 let mut pks: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(npubs.len());
5467 for n in npubs {
5468 let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5469 if !pks.contains(&pk) {
5470 pks.push(pk);
5471 }
5472 }
5473 let mut extra: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(cut_also.len());
5474 for n in cut_also {
5475 let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5476 if !extra.contains(&pk) {
5477 extra.push(pk);
5478 }
5479 }
5480 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5481 if !crate::db::community::community_held(&cid).map_err(VectorError::Other)? {
5482 return Err(VectorError::Other("community not found".into()));
5483 }
5484 let session = crate::db::current_session();
5487 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
5488 let report = crate::community::v2::service::contain_raid(&transport, &cid, &pks, window_start_secs, &extra)
5489 .await
5490 .map_err(VectorError::Other)?;
5491 if !session.is_live() {
5492 return Err(VectorError::Other("account changed during raid containment".into()));
5493 }
5494 Self::invalidate_raid_report(community_id);
5495 Ok(report)
5496 }
5497
5498 pub async fn dissolve_community(&self, community_id: &str) -> Result<()> {
5502 use crate::community::{transport::LiveTransport, CommunityId};
5503 if community_id.len() != 64 {
5504 return Err(VectorError::Other("malformed community id".into()));
5505 }
5506 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5507 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5508 let community = crate::db::community::load_community_v2(&cid)
5510 .map_err(VectorError::Other)?
5511 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5512 crate::community::v2::service::dissolve_community(&transport, &community)
5513 .await
5514 .map_err(VectorError::Other)
5515 }
5516
5517 pub async fn edit_community_metadata(&self, community_id: &str, name: Option<&str>, description: Option<&str>) -> Result<()> {
5520 use crate::community::{transport::LiveTransport, CommunityId};
5521 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5522 if community_id.len() != 64 {
5526 return Err(VectorError::Other("malformed community id".into()));
5527 }
5528 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5529 let community = crate::db::community::load_community_v2(&cid)
5530 .map_err(VectorError::Other)?
5531 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5532 let mut meta = community.metadata();
5533 if let Some(n) = name {
5534 meta.name = n.to_string();
5535 }
5536 if let Some(d) = description {
5537 meta.description = if d.is_empty() { None } else { Some(d.to_string()) };
5538 }
5539 crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
5540 .await
5541 .map_err(VectorError::Other)
5542 }
5543
5544 pub async fn remove_community_image(&self, community_id: &str, is_banner: bool) -> Result<()> {
5547 use crate::community::{transport::LiveTransport, CommunityId};
5548 let session = crate::db::current_session();
5549 let cid = CommunityId(Self::id32(community_id, "community_id")?);
5550 let community = crate::db::community::load_community_v2(&cid)
5551 .map_err(VectorError::Other)?
5552 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5553 let mut meta = community.metadata();
5554 if is_banner {
5555 meta.banner = None;
5556 } else {
5557 meta.icon = None;
5558 }
5559 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5560 crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
5561 .await
5562 .map_err(VectorError::Other)?;
5563 if !session.is_live() {
5565 return Err(VectorError::Other("account changed while removing the image".into()));
5566 }
5567 if let Some(updated) = crate::community::v2::service::persist_community_image(&cid, None, is_banner).await {
5568 self.register_v2_chats(&updated, &session).await;
5569 }
5570 Ok(())
5571 }
5572
5573 pub async fn set_community_image(&self, community_id: &str, bytes: &[u8], is_banner: bool) -> Result<String> {
5577 let usage = if is_banner { crate::image_prep::ImageUse::Banner } else { crate::image_prep::ImageUse::Icon };
5578 let raw = bytes.to_vec();
5579 let prepared = crate::rt::spawn_blocking(move || crate::image_prep::prepare(&raw, usage))
5580 .await
5581 .map_err(|e| VectorError::Other(format!("image preparation stopped: {e}")))?
5582 .map_err(VectorError::Other)?;
5583 self.publish_community_image(community_id, prepared.bytes, prepared.extension, is_banner, None).await
5584 }
5585
5586 pub async fn publish_community_image(
5589 &self,
5590 community_id: &str,
5591 bytes: Vec<u8>,
5592 extension: &str,
5593 is_banner: bool,
5594 progress: Option<crate::blossom::ProgressCallback>,
5595 ) -> Result<String> {
5596 use crate::community::{transport::LiveTransport, CommunityId};
5597 let session = crate::db::current_session();
5598 let cid = CommunityId(Self::id32(community_id, "community_id")?);
5599 crate::db::community::load_community_v2(&cid)
5600 .map_err(VectorError::Db)?
5601 .ok_or_else(|| VectorError::NotFound("community".into()))?;
5602 if crate::svg::looks_like_svg(&bytes) {
5603 return Err(VectorError::Other(crate::community::SVG_REFUSED.to_string()));
5604 }
5605 let hash = crate::crypto::sha256_hex(&bytes);
5606 let params = crate::crypto::generate_encryption_params();
5608 let encrypted = crate::crypto::encrypt_data(&bytes, ¶ms).map_err(VectorError::Other)?;
5609 let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("signer: {e}")))?;
5610 let servers = state::get_blossom_servers();
5611 if servers.is_empty() {
5612 return Err(VectorError::Other("no Blossom servers configured".into()));
5613 }
5614 let progress = progress.unwrap_or_else(|| std::sync::Arc::new(|_, _| Ok(())));
5615 let url = crate::blossom::upload_blob_with_progress_and_failover(
5616 signer,
5617 servers,
5618 std::sync::Arc::new(encrypted),
5619 Some("application/octet-stream"),
5620 true,
5621 progress,
5622 None,
5623 None,
5624 None,
5625 )
5626 .await
5627 .map_err(VectorError::Other)?
5628 .url;
5629 let mut extra = serde_json::Map::new();
5630 extra.insert("ext".into(), serde_json::Value::String(extension.to_string()));
5631 let image = crate::community::v2::control::ImageRef { url: url.clone(), key: params.key.clone(), nonce: params.nonce.clone(), hash, extra };
5632 if !session.is_live() {
5634 return Err(VectorError::Other("account changed while setting the image".into()));
5635 }
5636 let community = crate::db::community::load_community_v2(&cid)
5639 .map_err(VectorError::Db)?
5640 .ok_or_else(|| VectorError::NotFound("community".into()))?;
5641 let mut meta = community.metadata();
5642 if is_banner {
5643 meta.banner = Some(image.clone());
5644 } else {
5645 meta.icon = Some(image.clone());
5646 }
5647 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5648 crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
5649 .await
5650 .map_err(VectorError::Other)?;
5651 if !session.is_live() {
5652 return Err(VectorError::Other("account changed while setting the image".into()));
5653 }
5654 if let Some(updated) = crate::community::v2::service::persist_community_image(&cid, Some(image), is_banner).await {
5655 self.register_v2_chats(&updated, &session).await;
5656 }
5657 Ok(url)
5658 }
5659
5660 pub async fn community_image(&self, community_id: &str, is_banner: bool) -> Result<Option<Vec<u8>>> {
5663 use crate::community::CommunityId;
5664 let cid = CommunityId(Self::id32(community_id, "community_id")?);
5665 let community = crate::db::community::load_community_v2(&cid)
5666 .map_err(VectorError::Other)?
5667 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5668 let Some(image) = (if is_banner { community.banner } else { community.icon }) else {
5669 return Ok(None);
5670 };
5671 let cap: usize = if is_banner { 16 } else { 10 } * 1024 * 1024;
5672 crate::net::validate_url_not_private(&image.url).map_err(|e| VectorError::Network(format!("community image URL refused: {e}")))?;
5674 let client = crate::net::build_http_client(std::time::Duration::from_secs(30)).map_err(VectorError::Network)?;
5675 let resp = crate::net::proxied_request(&client, reqwest::Method::GET, &image.url)
5676 .await
5677 .send()
5678 .await
5679 .map_err(|e| VectorError::Network(format!("download: {e}")))?;
5680 if !resp.status().is_success() {
5681 return Err(VectorError::Network(format!("download failed: HTTP {}", resp.status())));
5682 }
5683 let mut encrypted: Vec<u8> = Vec::with_capacity(resp.content_length().map_or(64 * 1024, |l| (l as usize).min(cap)));
5684 let mut body = resp.bytes_stream();
5685 while let Some(chunk) = futures_util::StreamExt::next(&mut body).await {
5686 let chunk = chunk.map_err(|e| VectorError::Network(format!("read body: {e}")))?;
5687 if encrypted.len() + chunk.len() > cap {
5688 return Err(VectorError::Other("community image too large".into()));
5689 }
5690 encrypted.extend_from_slice(&chunk);
5691 }
5692 let plain = crate::crypto::decrypt_data_owned(encrypted, &image.key, &image.nonce).map_err(VectorError::Crypto)?;
5693 if crate::crypto::sha256_hex(&plain) != image.hash {
5694 return Err(VectorError::Crypto("community image failed its integrity check".into()));
5695 }
5696 if crate::svg::looks_like_svg(&plain) {
5697 return Err(VectorError::Other(crate::community::SVG_REFUSED.to_string()));
5698 }
5699 Ok(Some(plain))
5700 }
5701
5702 pub async fn set_voice_relays(&self, community_id: &str, relays: &[String]) -> Result<Vec<String>> {
5705 use crate::community::{transport::LiveTransport, CommunityId};
5706 let cid = CommunityId(Self::id32(community_id, "community_id")?);
5707 let community = crate::db::community::load_community_v2(&cid)
5708 .map_err(VectorError::Other)?
5709 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5710 let mut clean: Vec<String> = Vec::new();
5711 for r in relays.iter().map(|r| r.trim().trim_end_matches('/').to_string()).filter(|r| !r.is_empty()) {
5712 let parsed = url::Url::parse(&r).map_err(|_| VectorError::Other(format!("{r} isn't a relay address")))?;
5713 if parsed.scheme() != "https" || parsed.host_str().is_none() {
5714 return Err(VectorError::Other(format!("{r}: a voice relay is an https:// address")));
5715 }
5716 let normal = format!("{}/", parsed.as_str().trim_end_matches('/'));
5717 if !clean.contains(&normal) {
5718 clean.push(normal);
5719 }
5720 }
5721 if clean.len() > crate::community::v2::community::MAX_VOICE_RELAYS {
5722 return Err(VectorError::Other(format!("at most {} voice relays", crate::community::v2::community::MAX_VOICE_RELAYS)));
5723 }
5724 let mut meta = community.metadata();
5725 if clean.is_empty() {
5726 meta.extra.remove("voice_relays");
5727 } else {
5728 meta.extra.insert("voice_relays".into(), serde_json::json!(clean));
5729 }
5730 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5731 crate::community::v2::service::edit_community_metadata(&transport, &community, &meta).await.map_err(VectorError::Other)?;
5732 Ok(clean)
5733 }
5734
5735 pub async fn leave_community(&self, community_id: &str) -> Result<()> {
5738 crate::db::scoped(async move {
5739 use crate::community::transport::LiveTransport;
5740 if community_id.len() != 64 {
5741 return Err(VectorError::Other("malformed community id".into()));
5742 }
5743 use crate::community::v2::service;
5744 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5745 let Some(v2) = Self::load_held(community_id)? else {
5746 let cid = Self::unheld_id(community_id)?;
5747 let at_ms = service::leave_unheld_locally(&cid).await.ok_or_else(|| VectorError::Other("community not found".into()))?;
5748 service::announce_unheld_leave(&transport, &cid, at_ms).await;
5749 return Ok(());
5750 };
5751 let channel_ids: Vec<String> =
5753 v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
5754 service::leave_community(&transport, &v2).await.map_err(VectorError::Other)?;
5755 service::forget_community_chats(&crate::simd::hex::bytes_to_hex_32(&v2.id().0), &channel_ids).await;
5756 Ok(())
5757 })
5758 .await
5759 }
5760
5761 pub async fn leave_community_now(&self, community_id: &str) -> Result<()> {
5765 crate::db::scoped(async move {
5766 use crate::community::v2::service;
5767 let Some(v2) = Self::load_held(community_id)? else {
5768 let cid = Self::unheld_id(community_id)?;
5769 let at_ms = service::leave_unheld_locally(&cid).await.ok_or_else(|| VectorError::Other("community not found".into()))?;
5770 crate::db::spawn_bound(async move {
5771 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5772 service::announce_unheld_leave(&transport, &cid, at_ms).await;
5773 });
5774 return Ok(());
5775 };
5776 let channel_ids: Vec<String> =
5777 v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
5778 let at_ms = service::leave_locally(&v2).map_err(VectorError::Other)?;
5779 service::forget_community_chats(&crate::simd::hex::bytes_to_hex_32(&v2.id().0), &channel_ids).await;
5780 crate::db::spawn_bound(async move {
5781 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5782 service::announce_leave(&transport, &v2, at_ms).await;
5783 if let Some(client) = state::nostr_client() {
5784 crate::community::v2::realtime::refresh_subscription(&client).await;
5785 }
5786 crate::community::transport::prune_unneeded_community_relays(&v2.relays).await;
5788 });
5789 Ok(())
5790 })
5791 .await
5792 }
5793
5794 pub async fn decline_community_invite(&self, community_id: &str) -> Result<()> {
5798 crate::db::scoped(async move {
5799 use crate::db::community as db;
5800 let bundle = db::get_pending_invite(community_id)
5802 .ok()
5803 .flatten()
5804 .and_then(|j| crate::community::v2::invite::CommunityInvite::from_bundle_json(&j).ok());
5805 let relays: Vec<String> = bundle.as_ref().map(|b| b.relays.clone()).unwrap_or_default();
5806 let wraps = db::pending_invite_wraps(community_id).unwrap_or_default();
5807 db::delete_pending_invite(community_id).map_err(VectorError::Other)?;
5808 if let Some(cid) = bundle.and_then(|_| crate::simd::hex::hex_to_bytes_32_checked(community_id)) {
5809 let removed_at = crate::clock::now_ms();
5810 crate::community::v2::service::tombstone_community_list_durable(crate::community::CommunityId(cid), relays.clone(), removed_at);
5811 }
5812 for wrap in wraps.iter().filter_map(|w| nostr_sdk::prelude::EventId::from_hex(w).ok()) {
5813 crate::deletion::delete_received_wrap(wrap);
5814 }
5815 if !relays.is_empty() {
5816 crate::community::transport::prune_unneeded_community_relays(&relays).await;
5817 }
5818 Ok(())
5819 })
5820 .await
5821 }
5822
5823 pub async fn sync_dms(
5840 &self,
5841 since_days: Option<u64>,
5842 handler: &dyn InboundEventHandler,
5843 ) -> Result<(u32, u32)> {
5844 crate::db::scoped(async move {
5845 use futures_util::StreamExt;
5846 use nostr_sdk::prelude::*;
5847
5848 let client = state::nostr_client()
5849 .ok_or(VectorError::Other("Not connected".into()))?;
5850 let my_pk = state::my_public_key()
5851 .ok_or(VectorError::Other("Not logged in".into()))?;
5852
5853 let (items, filter) = if let Some(days) = since_days {
5858 let since_ts = crate::clock::timestamp().as_secs().saturating_sub(days * 24 * 3600);
5859 let items = db::wrappers::load_negentropy_items_since(since_ts)
5860 .unwrap_or_default();
5861 let filter = Filter::new()
5862 .pubkey(my_pk)
5863 .kind(Kind::GiftWrap)
5864 .since(Timestamp::from_secs(since_ts));
5865 (items, filter)
5866 } else {
5867 let items = db::wrappers::load_negentropy_items().unwrap_or_default();
5868 let filter = Filter::new()
5869 .pubkey(my_pk)
5870 .kind(Kind::GiftWrap);
5871 (items, filter)
5872 };
5873
5874 log_info!("[SyncDMs] {} negentropy items, since_days={:?}", items.len(), since_days);
5875 let items = std::sync::Arc::new(items);
5876
5877 let sync_opts = nostr_sdk::prelude::SyncOptions::new()
5879 .direction(nostr_sdk::prelude::SyncDirection::Down)
5880 .initial_timeout(relay_request_timeout(std::time::Duration::from_secs(10)))
5881 .dry_run();
5882
5883 let relay_map = client.relays().await;
5887 let (all_relays, no_neg_relays): (Vec<_>, Vec<_>) =
5888 relay_map.iter()
5889 .map(|(url, relay)| (url.clone(), relay.clone()))
5890 .partition(|(url, _)| negentropy::neg_supported_cached(url.as_str()) != Some(false));
5891 drop(relay_map);
5892 let skipped_no_neg: Vec<String> = no_neg_relays.iter().map(|(u, _)| u.to_string()).collect();
5893 if !skipped_no_neg.is_empty() {
5894 log_info!("[SyncDMs] {} relay(s) on REQ path (no NIP-77)", skipped_no_neg.len());
5895 }
5896
5897 let neg_budget = relay_request_timeout(std::time::Duration::from_secs(10));
5901 let neg_outer = neg_budget + std::time::Duration::from_secs(5);
5902 let connect_allowance = relay_request_timeout(std::time::Duration::from_secs(3))
5903 .min(neg_outer);
5904 let mut relay_futs = futures_util::stream::FuturesUnordered::new();
5905 for (url, relay) in &all_relays {
5906 let url = url.clone();
5907 let relay = relay.clone();
5908 let f = filter.clone();
5909 let i = items.clone();
5910 let o = sync_opts.clone();
5911 relay_futs.push(async move {
5912 if !negentropy::wait_connected(&relay, connect_allowance).await {
5913 return (url, None, false);
5914 }
5915 let result = crate::rt::time::timeout(
5918 neg_outer,
5919 relay.sync(f).items(i.iter().copied()).opts(o),
5920 ).await;
5921 let connected = relay.status() == RelayStatus::Connected;
5922 (url, Some(result), connected)
5923 });
5924 }
5925
5926 let cap_session = crate::db::current_session();
5928 let mut all_missing: std::collections::HashSet<EventId> = std::collections::HashSet::new();
5929 while let Some((url, result, connected)) = relay_futs.next().await {
5930 let Some(result) = result else {
5931 log_warn!("[SyncDMs] {} skipped: not connected", url);
5932 continue;
5933 };
5934 match result {
5935 Ok(Ok(recon)) => {
5936 let count = recon.remote.len();
5937 all_missing.extend(recon.remote);
5938 log_info!("[SyncDMs] {} reconciled: {} missing", url, count);
5939 negentropy::record_neg_support(url.as_str(), true);
5940 }
5941 Ok(Err(e)) => {
5942 log_warn!("[SyncDMs] {} failed: {}", url, e);
5943 if cap_session.is_live()
5944 && negentropy::classify_neg_sync_error(&e.to_string(), connected && !negentropy::neg_ever_confirmed(url.as_str())) == Some(false)
5945 {
5946 log_info!("[SyncDMs] {} marked no-NIP-77 for 24h", url);
5947 negentropy::record_neg_support(url.as_str(), false);
5948 }
5949 }
5950 Err(_) => log_warn!("[SyncDMs] {} timed out ({:?})", url, neg_outer),
5951 }
5952 }
5953
5954 let mut total_events = 0u32;
5955 let mut new_messages = 0u32;
5956
5957 if !skipped_no_neg.is_empty() {
5962 let req_filter = filter.clone().limit(500);
5963 match client
5964 .stream_events(nostr_sdk::prelude::ReqTarget::manual(
5965 skipped_no_neg.iter().cloned().map(|u| (u, vec![req_filter.clone()])),
5966 ))
5967 .timeout(relay_request_timeout(std::time::Duration::from_secs(20)))
5968 .await
5969 {
5970 Ok(stream) => {
5971 let mut seen: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
5972 let stream = stream.ready_chunks(event_handler::UNWRAP_BATCH);
5973 tokio::pin!(stream);
5974 while let Some(chunk) = stream.next().await {
5975 let events: Vec<Event> = chunk
5979 .into_iter()
5980 .filter_map(|(_relay, res)| res.ok())
5981 .filter(|event| seen.insert(event.id.to_bytes()))
5982 .collect();
5983 total_events += events.len() as u32;
5984 for prepared in event_handler::prepare_events(&events, my_pk).await {
5985 if event_handler::commit_prepared_event(prepared, false, handler).await {
5986 new_messages += 1;
5987 }
5988 }
5989 }
5990 }
5991 Err(e) => log_warn!("[SyncDMs] REQ pass failed: {}", e),
5992 }
5993 }
5994
5995 if all_missing.is_empty() {
5996 log_info!("[SyncDMs] No missing events");
5997 return Ok((total_events, new_messages));
5998 }
5999
6000 log_info!("[SyncDMs] Fetching {} missing events", all_missing.len());
6002 let ids: Vec<EventId> = all_missing.into_iter().collect();
6003 let relay_strs: Vec<String> = client.relays().await.keys()
6004 .map(|u| u.to_string()).collect();
6005
6006 const BATCH_SIZE: usize = 500;
6007
6008 for batch in ids.chunks(BATCH_SIZE) {
6009 let f = Filter::new().ids(batch.to_vec()).kind(Kind::GiftWrap).pubkey(my_pk);
6012 match client
6013 .stream_events(nostr_sdk::prelude::ReqTarget::manual(
6014 relay_strs.iter().cloned().map(|u| (u, vec![f.clone()])),
6015 ))
6016 .timeout(std::time::Duration::from_secs(30))
6017 .await
6018 {
6019 Ok(stream) => {
6020 let prepared_stream = stream
6021 .filter_map(|(_relay, res)| async move { res.ok() })
6022 .ready_chunks(event_handler::UNWRAP_BATCH)
6023 .map(move |events| {
6024 db::spawn_bound(async move {
6025 event_handler::prepare_events(&events, my_pk).await
6026 })
6027 })
6028 .buffer_unordered(8);
6029 tokio::pin!(prepared_stream);
6030
6031 while let Some(result) = prepared_stream.next().await {
6032 let Ok(batch) = result else { continue };
6033 total_events += batch.len() as u32;
6034 for prepared in batch {
6035 if event_handler::commit_prepared_event(prepared, false, handler).await {
6036 new_messages += 1;
6037 }
6038 }
6039 }
6040 }
6041 Err(e) => log_warn!("[SyncDMs] Batch fetch error: {}", e),
6042 }
6043 }
6044
6045 log_info!("[SyncDMs] Complete: {} events processed, {} new messages", total_events, new_messages);
6046 Ok((total_events, new_messages))
6047 })
6048 .await
6049 }
6050
6051 pub async fn subscribe_dms(&self) -> Result<nostr_sdk::prelude::SubscriptionId> {
6060 use nostr_sdk::prelude::*;
6061 let client = state::nostr_client()
6062 .ok_or(VectorError::Other("Not connected".into()))?;
6063 let my_pk = state::my_public_key()
6064 .ok_or(VectorError::Other("Not logged in".into()))?;
6065
6066 let filter = Filter::new()
6067 .pubkey(my_pk)
6068 .kind(Kind::GiftWrap)
6069 .limit(0);
6070
6071 let output = client.subscribe(filter.clone()).await
6072 .map_err(|e| VectorError::Nostr(e.to_string()))?;
6073 live_subs::keep_output(&output, vec![filter]);
6074 Ok(output.value)
6075 }
6076
6077 pub async fn sync_communities(&self) -> Result<Vec<String>> {
6091 let mut all_warnings: Vec<String> = Vec::new();
6092 {
6096 use crate::community::{transport::LiveTransport, v2::service as v2};
6097 let bootstrap: Vec<String> = match crate::state::nostr_client() {
6098 Some(client) => client.relays().await.keys().map(|r| r.to_string()).collect(),
6099 None => Vec::new(),
6100 };
6101 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
6102 if let Ok(outcome) = v2::sync_community_list(&transport, &bootstrap).await {
6103 let joined = outcome.joined;
6106 for c in &joined {
6107 if community::v2::realtime::follow_worker_running() {
6108 community::v2::realtime::enqueue_follow(c.id());
6109 } else {
6110 let cid_hex = crate::simd::hex::bytes_to_hex_32(&c.id().0);
6111 all_warnings.extend(
6112 Self::v2_inline_follow(c.id()).await.into_iter().map(|w| format!("{}: {w}", &cid_hex[..8])),
6113 );
6114 }
6115 }
6116 if !joined.is_empty() {
6117 if let Some(client) = crate::state::nostr_client() {
6118 community::v2::realtime::refresh_subscription(&client).await;
6119 }
6120 }
6121 }
6122 }
6123
6124 let ids = db::community::list_community_ids().map_err(VectorError::from)?;
6125 for id in ids {
6126 if community::v2::realtime::follow_worker_running() {
6129 community::v2::realtime::enqueue_follow(&id);
6130 } else {
6131 let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
6132 all_warnings.extend(
6133 Self::v2_inline_follow(&id).await.into_iter().map(|w| format!("{}: {w}", &cid_hex[..8])),
6134 );
6135 }
6136 if let Ok(Some(c)) = db::community::load_community_v2(&id) {
6142 for ch in &c.channels {
6143 let hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
6144 let _ = Self::v2_backfill_channel(
6145 &id, &hex, 50, 2, None, None,
6146 crate::community::transport::Evidence::Fast, 12,
6147 ).await;
6148 }
6149 }
6150 }
6151 Ok(all_warnings)
6152 }
6153
6154
6155 pub async fn listen(&self, handler: Arc<dyn InboundEventHandler>) -> Result<()> {
6187 self.listen_with(handler, CatchUp::Inline).await
6188 }
6189
6190 pub async fn listen_with(&self, handler: Arc<dyn InboundEventHandler>, catch_up: CatchUp) -> Result<()> {
6192 use nostr_sdk::prelude::*;
6193
6194 let client = state::nostr_client()
6195 .ok_or(VectorError::Other("Not connected".into()))?;
6196 let my_pk = state::my_public_key()
6197 .ok_or(VectorError::Other("Not logged in".into()))?;
6198
6199 community::v2::streamauth::ensure_responder(&client);
6206
6207 let listening_since = crate::clock::now_ms();
6210 let inline = catch_up == CatchUp::Inline;
6211 if inline {
6212 news::begin(handler.clone(), listening_since);
6213 } else {
6214 news::end();
6215 }
6216 let live_from = news::cutoff().unwrap_or(listening_since);
6217
6218 if handler.wants_community_changes() {
6222 community::v2::changes::prime_all(&*handler);
6223 }
6224
6225 community::v2::realtime::spawn_follow_worker(handler.clone());
6228 early::start(handler.clone());
6229
6230 let notifications = client.notifications();
6237 let dm_sub_id = self.subscribe_dms().await?;
6238 live_subs::watch(&client);
6239 let (live_tx, mut live_rx) = tokio::sync::mpsc::channel::<(LiveRoute, Box<nostr_sdk::prelude::Event>)>(4096);
6240 let dm_sid = dm_sub_id.clone();
6241 db::spawn_bound(async move {
6242 let mut notifications = notifications;
6243 while let Some(notification) = notifications.next().await {
6244 if let nostr_sdk::prelude::ClientNotification::Message { message, .. } = ¬ification {
6248 if let nostr_sdk::prelude::RelayMessage::Ok { event_id, status, .. } = &**message {
6249 sending::note_relay_ok(event_id, *status);
6250 }
6251 }
6252 let nostr_sdk::prelude::ClientNotification::Event { event, subscription_id, .. } = notification else { continue };
6253 let route = if subscription_id == dm_sid {
6254 LiveRoute::Dm
6255 } else if community::v2::realtime::subscription_id().await.as_ref() == Some(&subscription_id)
6256 || community::v2::realtime::poolwide_subscription_id().await.as_ref() == Some(&subscription_id)
6257 {
6258 LiveRoute::CommunityV2
6259 } else {
6260 continue;
6261 };
6262 if live_tx.send((route, event)).await.is_err() {
6263 break;
6264 }
6265 }
6266 });
6267
6268 if inline {
6276 let _ = self.sync_communities().await;
6277 let _ = self.sync_dms(None, &event_handler::LiveOnly::from(&*handler, live_from)).await;
6278 }
6279
6280 community::v2::realtime::refresh_subscription(&client).await;
6283
6284 if inline {
6287 Self::owe_catch_up(false, false, [(EVERY_RELAY.to_string(), live_from)]);
6288 live_subs::set_catch_up(|what| {
6291 let now = crate::clock::now_ms();
6292 match what {
6293 live_subs::CatchUp::All { away_ms } => Self::owe_catch_up(true, true, [(EVERY_RELAY.to_string(), now.saturating_sub(away_ms))]),
6294 live_subs::CatchUp::Relay(url) => Self::owe_catch_up(false, false, [(url, now.saturating_sub(live_subs::MAX_BACKOFF.as_millis() as u64))]),
6295 }
6296 });
6297 #[cfg(not(target_arch = "wasm32"))]
6298 live_subs::start_wake_watch();
6299 }
6300
6301 handler.on_subscription_ready(db::community::list_community_ids().map(|v| v.len()).unwrap_or(0));
6307
6308 if let Some(monitor) = client.monitor().filter(|_| catch_up == CatchUp::Inline) {
6315 let mut rx = monitor.subscribe();
6316 let pool = client.clone();
6317 db::spawn_bound(async move {
6318 let mut down: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
6321 for (url, relay) in pool.relays().await {
6322 if relay.status() != RelayStatus::Connected {
6323 down.insert(url.to_string(), live_from);
6324 }
6325 }
6326 loop {
6327 match rx.recv().await {
6328 Ok(MonitorNotification::StatusChanged { relay_url, status }) => {
6329 let url = relay_url.to_string();
6330 match status {
6331 RelayStatus::Disconnected | RelayStatus::Terminated => {
6332 down.entry(url).or_insert_with(crate::clock::now_ms);
6333 }
6334 RelayStatus::Connected => {
6336 if let Some(since) = down.remove(&url) {
6337 VectorCore::owe_catch_up(true, true, [(url, since)]);
6338 }
6339 }
6340 _ => {}
6341 }
6342 }
6343 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
6345 VectorCore::owe_catch_up(true, true, [(EVERY_RELAY.to_string(), crate::clock::now_ms().saturating_sub(30 * 60_000))]);
6346 }
6347 Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
6348 }
6349 }
6350 });
6351 }
6352
6353 {
6357 let client_health = client.clone();
6358 db::spawn_bound(async move {
6359 crate::rt::time::sleep(std::time::Duration::from_secs(30)).await; let heard = std::sync::Mutex::new(std::collections::HashMap::<RelayUrl, usize>::new());
6363 loop {
6364 let budget = relay_request_timeout(std::time::Duration::from_secs(8));
6367 let client_health = &client_health;
6368 let heard = &heard;
6369 futures_util::future::join_all(client_health.relays().await.into_iter().map(|(url, relay)| async move {
6370 match relay.status() {
6371 RelayStatus::Connected => {
6372 let received = relay.stats().bytes_received();
6373 let before = heard.lock().unwrap().insert(url.clone(), received);
6374 if before.is_some_and(|b| received > b) {
6375 return;
6376 }
6377 let probe = crate::rt::time::timeout(
6379 budget + std::time::Duration::from_secs(2),
6380 client_health
6381 .fetch_events(nostr_sdk::prelude::ReqTarget::single(
6382 url.to_string(),
6383 [Filter::new().id(EventId::from_byte_array([0; 32]))],
6384 ))
6385 .timeout(budget),
6386 )
6387 .await;
6388 heard.lock().unwrap().insert(url.clone(), relay.stats().bytes_received());
6389 if !matches!(probe, Ok(Ok(_))) {
6390 relay.disconnect();
6391 crate::rt::time::sleep(std::time::Duration::from_millis(500)).await;
6392 let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
6393 }
6394 }
6395 RelayStatus::Terminated | RelayStatus::Disconnected => {
6396 let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
6397 }
6398 _ => {}
6399 }
6400 })).await;
6401 crate::rt::time::sleep(std::time::Duration::from_secs(60)).await;
6402 }
6403 });
6404 }
6405
6406 let client_for_closure = client.clone();
6407
6408 while let Some((route, event)) = live_rx.recv().await {
6411 match route {
6412 LiveRoute::Dm => {
6414 let prepared = event_handler::prepare_event(*event, &client_for_closure, my_pk).await;
6415 event_handler::commit_prepared_event(prepared, true, &*handler).await;
6416 }
6417 LiveRoute::CommunityV2 => community::v2::realtime::dispatch_event(*event, handler.clone()).await,
6419 }
6420 }
6421
6422 news::end();
6423 Ok(())
6424 }
6425
6426 pub(crate) fn owe_catch_up(communities: bool, dms: bool, relays: impl IntoIterator<Item = (String, u64)>) {
6430 if news::listening_since().is_none() {
6431 return;
6432 }
6433 let session = db::current_session_id();
6434 let start = {
6435 let mut owed = CATCH_UPS.lock().unwrap_or_else(|e| e.into_inner());
6436 if owed.session != session {
6437 *owed = Owed { session, ..Owed::default() };
6438 }
6439 owed.communities |= communities;
6440 owed.dms |= dms;
6441 for (relay, since) in relays {
6442 let at = owed.relays.entry(relay).or_insert(since);
6443 *at = (*at).min(since);
6444 }
6445 !std::mem::replace(&mut owed.running, true)
6446 };
6447 if start {
6448 db::spawn_bound(Self::run_catch_ups(session));
6449 }
6450 }
6451
6452 async fn run_catch_ups(session: u64) {
6453 loop {
6454 crate::rt::time::sleep(std::time::Duration::from_secs(1)).await;
6456 let listener = news::listener().zip(news::cutoff());
6457 let owed = {
6458 let mut owed = CATCH_UPS.lock().unwrap_or_else(|e| e.into_inner());
6459 let nothing = !owed.communities && !owed.dms && owed.relays.is_empty();
6460 if owed.session != session || nothing || listener.is_none() {
6461 owed.running = false;
6462 return;
6463 }
6464 std::mem::replace(&mut *owed, Owed { session, running: true, ..Owed::default() })
6465 };
6466 let Some((handler, from)) = listener else { return };
6467 if owed.communities {
6468 let _ = VectorCore.sync_communities().await;
6469 }
6470 if owed.dms {
6471 let _ = VectorCore.sync_dms(None, &event_handler::LiveOnly::from(&*handler, from)).await;
6472 }
6473 if let Some(client) = state::nostr_client() {
6474 if owed.communities {
6475 community::v2::realtime::refresh_subscription(&client).await;
6476 }
6477 for (relay, since) in owed.relays {
6478 let since = since.saturating_sub(news::ALLOWANCE_MS).max(from);
6479 let only = (relay != EVERY_RELAY).then_some(relay.as_str());
6480 community::v2::realtime::replay(&client, nostr_sdk::prelude::Timestamp::from_secs(since / 1000), only, handler.clone()).await;
6481 }
6482 }
6483 }
6484 }
6485
6486 pub async fn logout(&self) {
6488 news::end();
6489 if let Some(client) = state::nostr_client() {
6490 let _ = client.disconnect().await;
6491 }
6492 db::close_database();
6493 }
6494
6495 pub async fn swap_session(&self) {
6503 state::clear_message_tombstones();
6505 news::end();
6506
6507 #[cfg(feature = "xdc")]
6510 crate::xdc::session::leave_all(std::time::Duration::from_secs(4)).await;
6511 #[cfg(feature = "calls")]
6513 crate::calls::voice::leave().await;
6514
6515 if let Some(client) = state::take_nostr_client() {
6518 let _ = client.shutdown().await;
6519 }
6520 db::close_database();
6521
6522 state::ENCRYPTION_KEY.clear(&[&state::MY_SECRET_KEY]);
6524 state::MY_SECRET_KEY.clear(&[&state::ENCRYPTION_KEY]);
6525 {
6526 use zeroize::Zeroize;
6527 if let Ok(mut g) = state::MNEMONIC_SEED.lock() {
6528 if let Some(s) = g.as_mut() { s.zeroize(); }
6529 *g = None;
6530 }
6531 if let Ok(mut g) = state::PENDING_NSEC.lock() {
6532 if let Some(s) = g.as_mut() { s.zeroize(); }
6533 *g = None;
6534 }
6535 }
6536
6537 crate::community::v2::realtime::clear().await;
6545 crate::community::transport::clear_plane_pool();
6548 }
6549}
6550
6551#[cfg(test)]
6552mod catch_up_tests {
6553 use super::*;
6554
6555 #[tokio::test]
6556 async fn what_a_listener_is_owed_merges_and_runs_once() {
6557 let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
6558 *CATCH_UPS.lock().unwrap() = Owed::default();
6559 VectorCore::owe_catch_up(true, false, [("wss://a".to_string(), 100)]);
6560 assert!(!CATCH_UPS.lock().unwrap().running, "nobody listening: nothing owed");
6561
6562 let _listening = news::listen_for_test(Arc::new(event_handler::NoOpEventHandler), crate::clock::now_ms());
6563 VectorCore::owe_catch_up(false, false, [("wss://a".to_string(), 100)]);
6564 VectorCore::owe_catch_up(false, true, [("wss://a".to_string(), 50), ("wss://b".to_string(), 70)]);
6565 let owed = CATCH_UPS.lock().unwrap();
6566 assert!(owed.running && owed.dms && !owed.communities);
6567 assert_eq!((owed.relays.get("wss://a"), owed.relays.get("wss://b")), (Some(&50), Some(&70)), "each relay from its earliest gap");
6568 }
6569}
6570
6571fn page_before(
6576 held: &[compact::CompactMessage],
6577 interner: &compact::NpubInterner,
6578 before: Option<(u64, &str)>,
6579 limit: usize,
6580) -> Vec<Message> {
6581 let (lo, mut msgs) = match before {
6582 None => (held.len(), Vec::new()),
6583 Some((at, id)) => {
6584 let lo = held.partition_point(|m| m.at < at);
6585 let hi = held.partition_point(|m| m.at <= at);
6586 let tie = held[lo..hi].iter().map(|m| m.to_message(interner)).filter(|m| m.id.as_str() < id).collect();
6587 (lo, tie)
6588 }
6589 };
6590 let mut start = lo.saturating_sub(limit.saturating_sub(msgs.len()));
6591 while start > 0 && start < lo && held[start - 1].at == held[start].at {
6592 start -= 1;
6593 }
6594 msgs.extend(held[start..lo].iter().map(|m| m.to_message(interner)));
6595 msgs.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
6596 if msgs.len() > limit {
6597 msgs.drain(..msgs.len() - limit);
6598 }
6599 msgs
6600}
6601
6602#[cfg(test)]
6603mod page_before_tests {
6604 use super::*;
6605
6606 #[test]
6607 fn it_matches_converting_the_whole_chat() {
6608 let mut interner = compact::NpubInterner::new();
6609 let mut held = compact::CompactMessageVec::new();
6610 let mut seed: u64 = 7;
6611 for n in 0..400u64 {
6612 seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17;
6613 let msg = Message { id: format!("{:064x}", seed), at: (n / 9) * 1000 + (seed % 3), ..Default::default() };
6615 held.insert(compact::CompactMessage::from_message(&msg, &mut interner));
6616 }
6617 let mut all: Vec<Message> = held.iter().map(|m| m.to_message(&interner)).collect();
6618 all.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
6619 let reference = |before: Option<(u64, &str)>, limit: usize| {
6620 let mut v: Vec<String> = all.iter()
6621 .filter(|m| before.is_none_or(|(at, id)| (m.at, m.id.as_str()) < (at, id)))
6622 .map(|m| m.id.clone())
6623 .collect();
6624 if v.len() > limit { v.drain(..v.len() - limit); }
6625 v
6626 };
6627 let ids = |v: Vec<Message>| v.into_iter().map(|m| m.id).collect::<Vec<_>>();
6628 for limit in [1, 3, 10, 50, 1000] {
6629 assert_eq!(ids(page_before(held.messages(), &interner, None, limit)), reference(None, limit));
6630 for c in all.iter().step_by(13) {
6631 for cursor in [(c.at, c.id.as_str()), (c.at, "0"), (c.at, "g"), (c.at + 1, "0")] {
6632 assert_eq!(ids(page_before(held.messages(), &interner, Some(cursor), limit)), reference(Some(cursor), limit), "cursor {cursor:?} limit {limit}");
6633 }
6634 }
6635 }
6636 }
6637}
6638
6639#[cfg(all(test, feature = "tor", not(target_arch = "wasm32")))]
6640mod transport_policy_tests {
6641 use std::time::Duration;
6642
6643 use crate::transport::{egress, Egress, Kind, Lane};
6644
6645 fn live() -> u64 {
6646 crate::db::live_session_id()
6647 }
6648
6649 #[test]
6652 fn tor_transport_policy() {
6653 let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
6654 let short = Duration::from_secs(5);
6655 let long = Duration::from_secs(300);
6656
6657 crate::transport::set_preference(Some(Kind::Clearnet));
6660 crate::tor::set_tor_enabled_pref(false);
6661 assert_eq!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Direct);
6662 assert_eq!(super::relay_connect_timeout(short), short);
6663 assert_eq!(super::relay_request_timeout(short), short);
6664
6665 crate::tor::set_tor_enabled_pref(true);
6668 assert!(matches!(
6669 crate::tor::transport_state(),
6670 crate::tor::TorTransportState::RequiredButInactive
6671 ));
6672 assert!(
6675 matches!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Refuse(_)),
6676 "Tor enabled but inactive must never connect direct"
6677 );
6678 assert_eq!(super::relay_connect_timeout(short), Duration::from_secs(60));
6679 assert_eq!(super::relay_request_timeout(short), Duration::from_secs(30));
6680
6681 crate::tor::set_tor_enabled_pref(false);
6684 crate::tor::arm_prelogin_carry(true);
6685 assert!(crate::tor::effective_tor_pref(false), "an armed carry raises an off preference");
6686 crate::tor::set_tor_enabled_pref(crate::tor::effective_tor_pref(false));
6687 assert!(
6688 matches!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Refuse(_)),
6689 "an armed carry must refuse until Tor is up, never connect direct"
6690 );
6691 crate::tor::arm_prelogin_carry(false);
6692 assert!(!crate::tor::effective_tor_pref(false), "a disarmed carry leaves the preference alone");
6693 assert!(crate::tor::effective_tor_pref(true));
6694
6695 let opts = super::transport_relay_options();
6697 assert!(format!("{opts:?}").contains("proxy: Some"), "remote-signer relays must carry the transport");
6698
6699 for tor in [true, false] {
6702 crate::tor::set_tor_enabled_pref(tor);
6703 assert_eq!(super::relay_connect_timeout(long), long, "connect, tor={tor}");
6704 assert_eq!(super::relay_request_timeout(long), long, "request, tor={tor}");
6705 }
6706 crate::transport::set_preference(Some(Kind::Clearnet));
6707 }
6708}
6709
6710#[cfg(test)]
6711mod facade_tests {
6712 use super::*;
6713
6714 #[tokio::test]
6717 async fn download_attachment_rejects_private_url() {
6718 let att = crate::types::Attachment {
6719 url: "http://169.254.169.254/latest/meta-data/".to_string(),
6720 ..Default::default()
6721 };
6722 match VectorCore.download_attachment(&att).await {
6723 Err(VectorError::Other(msg)) => {
6724 assert!(msg.contains("Private/internal"), "expected SSRF rejection, got: {msg}")
6725 }
6726 other => panic!("expected SSRF rejection, got {other:?}"),
6727 }
6728 }
6729
6730 #[tokio::test]
6731 async fn download_attachment_rejects_empty_url() {
6732 let att = crate::types::Attachment::default();
6733 assert!(VectorCore.download_attachment(&att).await.is_err());
6734 }
6735
6736 #[tokio::test]
6739 async fn list_communities_and_channel_routing_are_protocol_aware() {
6740 use crate::community::transport::memory::MemoryRelay;
6741 use nostr_sdk::prelude::Keys;
6742
6743 let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
6744 crate::db::close_database();
6745 crate::db::clear_id_caches();
6746 let tmp = tempfile::tempdir().unwrap();
6747 let acct = {
6749 const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
6750 let mut s = String::from("npub1");
6751 for i in 0..58 {
6752 s.push(B[(i * 7 + 3) % 32] as char);
6753 }
6754 s
6755 };
6756 std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
6757 crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
6758 crate::db::set_current_account(acct.clone()).unwrap();
6759 crate::db::init_database(&acct).unwrap();
6760 let _ = crate::state::take_nostr_client();
6761 let me = Keys::generate();
6762 crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
6763 crate::state::set_my_public_key(me.public_key());
6764
6765 let relay = MemoryRelay::new();
6767 let community = crate::community::v2::service::create_community(&relay, "V2 Guild", vec!["wss://r".into()], None)
6768 .await
6769 .unwrap();
6770 let channel_hex = crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0);
6771
6772 let listed = VectorCore.list_communities().await;
6774 let v2 = listed.iter().find(|c| c["version"] == 2).expect("the v2 community is listed");
6775 assert_eq!(v2["name"], "V2 Guild");
6776 assert_eq!(v2["is_owner"], true);
6777 assert_eq!(v2["channels"][0]["channel_id"], channel_hex);
6778
6779 assert_eq!(
6781 VectorCore.v2_community_for_channel(&channel_hex).unwrap(),
6782 Some(community.identity.community_id),
6783 "a v2 channel is routed to v2"
6784 );
6785 assert_eq!(VectorCore.v2_community_for_channel(&"00".repeat(32)).unwrap(), None);
6787 }
6788
6789 #[test]
6794 fn v2_invite_url_base_derivation_round_trips() {
6795 use crate::community::v2::derive::TOKEN_LEN;
6796 use crate::community::v2::invite::{build_invite_url, parse_invite_link};
6797 use nostr_sdk::prelude::Keys;
6798 let base = crate::community::v2::invite::INVITE_URL_BASE.trim_end_matches("/invite");
6799 assert!(!base.ends_with("/invite"), "the bare domain must not carry /invite");
6800 let signer = Keys::generate();
6801 let token = [0x07u8; TOKEN_LEN];
6802 let url = build_invite_url(base, &signer.public_key(), &token, &[]).unwrap();
6803 assert!(url.contains("/invite/"), "a v2 URL carries the naddr path");
6804 assert!(!url.contains("/invite/invite/"), "no doubled /invite from the base");
6805 let parsed = parse_invite_link(&url).unwrap();
6806 assert_eq!(parsed.link_signer, signer.public_key());
6807 assert_eq!(parsed.token, token);
6808 }
6809}
6810
6811#[cfg(test)]
6812mod history_paging_tests {
6813 use super::*;
6814
6815 fn msg(at: u64, id_byte: u8, content: &str) -> Message {
6816 Message {
6817 id: format!("{:02x}", id_byte).repeat(32),
6818 content: content.to_string(),
6819 at,
6820 ..Default::default()
6821 }
6822 }
6823
6824 #[tokio::test]
6828 async fn history_pages_through_a_same_ms_wall_and_a_deleted_cursor() {
6829 let chat_id = "test-history-paging-wall";
6830 {
6831 let mut st = state::STATE.lock().await;
6832 st.ensure_community_chat(chat_id);
6833 for m in [msg(500, 0x01, "old"), msg(900, 0xaa, "wall-a"), msg(900, 0xbb, "wall-b"), msg(900, 0xcc, "wall-c")] {
6835 st.add_message_to_chat(chat_id, &m);
6836 }
6837 }
6838 let core = VectorCore;
6839
6840 let newest = core.get_messages_before(chat_id, None, 2).await;
6842 assert_eq!(newest.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(), ["wall-b", "wall-c"]);
6843
6844 let cursor = (newest[0].at, newest[0].id.as_str().to_string());
6846 let page = core.get_messages_before(chat_id, Some((cursor.0, &cursor.1)), 10).await;
6847 assert_eq!(page.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(), ["old", "wall-a"]);
6848
6849 {
6852 let mut st = state::STATE.lock().await;
6853 let chat = st.get_chat_mut(chat_id).unwrap();
6854 chat.messages.remove_by_hex_id(&cursor.1);
6855 }
6856 let page = core.get_messages_before(chat_id, Some((cursor.0, &cursor.1)), 10).await;
6857 assert_eq!(
6858 page.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(),
6859 ["old", "wall-a"],
6860 "a deleted cursor pages identically"
6861 );
6862
6863 assert!(core.get_messages_before("test-history-paging-nochat", None, 5).await.is_empty());
6865 }
6866}
6867
6868#[cfg(test)]
6869mod moderation_cache_audit {
6870 #[test]
6876 fn every_moderation_action_drops_the_memoised_verdict() {
6877 let src = include_str!("lib.rs");
6878 for name in [
6879 "pub async fn refound_community",
6880 "pub async fn kick_community_members",
6881 "pub async fn set_members_banned",
6882 "pub async fn contain_raid",
6883 ] {
6884 let start = src.find(name).unwrap_or_else(|| panic!("{name} not found — rename?"));
6885 let rest = &src[start + name.len()..];
6887 let end = rest.find("\n pub ").unwrap_or(rest.len());
6888 assert!(
6889 rest[..end].contains("invalidate_raid_report"),
6890 "{name} mutates membership but never drops the memoised console verdict"
6891 );
6892 }
6893 }
6894
6895 #[test]
6900 fn an_adopted_change_drops_the_verdict_too() {
6901 let src = include_str!("db/community.rs");
6902 for name in ["pub fn set_community_banlist", "pub fn set_community_roles", "pub fn set_guestbook"] {
6903 let start = src.find(name).unwrap_or_else(|| panic!("{name} not found — rename?"));
6904 let rest = &src[start + name.len()..];
6905 let end = rest.find("\npub fn ").unwrap_or(rest.len());
6906 assert!(
6907 rest[..end].contains("forget_console_verdict"),
6908 "{name} changes who the console reports on but leaves the memo standing"
6909 );
6910 }
6911 }
6912}