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, Presence, 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
747fn drop_community_image(url: Option<String>, kept: Option<&str>) {
750 let Some(url) = url.filter(|u| Some(u.as_str()) != kept) else { return };
751 if let Ok(signer) = crate::signer::active_signer() {
752 crate::blossom::delete_blobs_best_effort(signer, vec![url]);
753 }
754}
755
756const BACKFILL_CONTINUATIONS: usize = 3;
758
759const UNPROVEN_EPOCHS: u64 = 2;
761
762#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
769pub struct BackfillCount {
770 pub fetched: usize,
771 pub new_messages: usize,
772 pub next_before: Option<u64>,
775 pub unreachable: bool,
777}
778
779impl VectorCore {
780 pub fn init(config: CoreConfig) -> Result<Self> {
782 db::set_app_data_dir(config.data_dir);
784
785 if let Some(emitter) = config.event_emitter {
787 traits::set_event_emitter(emitter);
788 }
789
790 #[cfg(not(target_arch = "wasm32"))]
792 let _ = rustls::crypto::ring::default_provider().install_default();
793
794 net::raise_fd_limit();
795
796 Ok(VectorCore)
797 }
798
799 pub fn accounts(&self) -> Result<Vec<String>> {
801 db::get_accounts().map_err(VectorError::from)
802 }
803
804 pub async fn login(&self, key: &str, password: Option<&str>) -> Result<LoginResult> {
806 use nostr_sdk::prelude::*;
807
808 let keys = if key.starts_with("nsec1") {
810 let secret = SecretKey::from_bech32(key)
811 .map_err(|e| VectorError::Nostr(format!("Invalid nsec: {}", e)))?;
812 Keys::new(secret)
813 } else {
814 Keys::from_mnemonic(key, None)
816 .map_err(|e| VectorError::Nostr(format!("Key derivation failed: {}", e)))?
817 };
818
819 let public_key = keys.public_key();
820 let npub = public_key.to_bech32()
821 .map_err(|e| VectorError::Nostr(format!("Failed to encode npub: {}", e)))?;
822
823 let secret_bytes = keys.secret_key().to_secret_bytes();
825 state::MY_SECRET_KEY.set(secret_bytes, &[&state::ENCRYPTION_KEY]);
826 state::set_my_public_key(public_key);
827
828 db::set_current_account(npub.clone())?;
830 db::init_database(&npub)?;
831
832 {
834 let nsec = keys.secret_key().to_bech32()
835 .map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))?;
836 *state::PENDING_NSEC.lock().unwrap() = Some(nsec.clone());
837
838 let existing_encrypted = db::get_pkey().ok().flatten().is_some_and(|v| !v.starts_with("nsec1"));
845 if !(state::resolve_encryption_enabled_from_db() && existing_encrypted) {
846 db::set_pkey(&nsec)?;
847 }
848 }
849
850 let has_encryption = state::resolve_encryption_enabled_from_db();
853
854 if has_encryption {
855 if let Some(pwd) = password {
856 let kdf = crate::crypto::Kdf::of_account().map_err(VectorError::Crypto)?;
861 let key = zeroize::Zeroizing::new(crate::crypto::derive_key(pwd, &kdf).await);
862 crate::crypto::install_unlocked_key(&key, &kdf).map_err(VectorError::Crypto)?;
863 }
864 }
865 state::init_encryption_enabled();
868
869 let client = crate::nostr_client_builder()
872 .monitor(Monitor::new(1024))
874 .build();
875
876 for relay in state::TRUSTED_RELAYS {
878 client.add_managed_relay(*relay).await.ok();
879 }
880
881 client.connect().await;
883
884 let _ = { state::set_nostr_client(client); Ok::<(), ()>(()) };
885
886 Ok(LoginResult { npub, has_encryption })
887 }
888
889 pub fn generate_nsec(&self) -> Result<String> {
892 use nostr_sdk::prelude::*;
893 Keys::generate().secret_key().to_bech32()
894 .map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))
895 }
896
897 pub async fn send_dm(&self, to_npub: &str, content: &str) -> Result<sending::SendResult> {
902 let config = SendConfig { self_send: false, ..SendConfig::headless() };
903 sending::send_dm(to_npub, content, None, &config, Arc::new(NoOpSendCallback)).await
904 .map_err(VectorError::Other)
905 }
906
907 pub async fn send_dm_reply(&self, to_npub: &str, replied_to: &str, content: &str) -> Result<sending::SendResult> {
909 let config = SendConfig { self_send: false, ..SendConfig::headless() };
910 sending::send_dm(to_npub, content, Some(replied_to), &config, Arc::new(NoOpSendCallback)).await
911 .map_err(VectorError::Other)
912 }
913
914 pub async fn download_attachment(&self, attachment: &Attachment) -> Result<Vec<u8>> {
921 self.download_attachment_from(attachment, None).await
922 }
923
924 pub async fn download_attachment_from(
929 &self,
930 attachment: &Attachment,
931 author_npub: Option<&str>,
932 ) -> Result<Vec<u8>> {
933 self.download_attachment_within(attachment, author_npub, 256 * 1024 * 1024)
934 .await
935 .map_err(|e| VectorError::Other(e.to_string()))
936 }
937
938 pub async fn download_attachment_within(
942 &self,
943 attachment: &Attachment,
944 author_npub: Option<&str>,
945 max_bytes: usize,
946 ) -> std::result::Result<Vec<u8>, DownloadError> {
947 self.download_attachment_reporting(attachment, author_npub, max_bytes, |_| true).await
948 }
949
950 pub async fn download_attachment_reporting<F: FnMut(DownloadStep) -> bool>(
954 &self,
955 attachment: &Attachment,
956 author_npub: Option<&str>,
957 max_bytes: usize,
958 mut step: F,
959 ) -> std::result::Result<Vec<u8>, DownloadError> {
960 use futures_util::StreamExt;
961 let max_download = max_bytes;
962 if attachment.url.is_empty() {
963 return Err(DownloadError::Unusable("attachment has no URL".into()));
964 }
965 let client = crate::net::build_http_client_with_options(
967 None,
968 Some(crate::net::transfer_stall()),
969 true,
970 )
971 .map_err(DownloadError::Unreachable)?;
972 let mut last_err = String::from("download failed");
973 let mut network_waits = 0u8;
976 let mut all_answered = true;
978 let mut candidates: Vec<String> = vec![attachment.url.clone()];
979 candidates.extend(attachment.fallback_urls.iter().cloned());
980 let mut hash_swap_tried = false;
981 let mut i = 0;
982 'sources: while i < candidates.len() {
983 let url = candidates[i].clone();
984 i += 1;
985 let extend_with_swap = |candidates: &mut Vec<String>, servers: &[String]| {
988 let extra = crate::blossom::hash_swap_candidates(&attachment.url, servers);
989 for c in extra {
990 if !candidates.contains(&c) {
991 candidates.push(c);
992 }
993 }
994 };
995 macro_rules! next_source {
996 () => {{
997 log_net_fail!("[Download] source failed ({}): {}", url, last_err);
998 if i == candidates.len() && !hash_swap_tried {
999 hash_swap_tried = true;
1000 let servers = crate::blossom_servers::author_swap_servers(author_npub, false).await;
1001 extend_with_swap(&mut candidates, &servers);
1002 }
1003 continue 'sources;
1004 }};
1005 }
1006 if let Err(e) = crate::net::validate_url_not_private(&url) {
1010 last_err = e.to_string();
1011 next_source!();
1012 }
1013 macro_rules! network_changed {
1014 ($e:expr) => {{
1015 if $e.is_transient() && network_waits < 8 {
1016 network_waits += 1;
1017 match crate::net::wait_after(&$e).await {
1018 Ok(()) => {
1019 i -= 1;
1020 continue 'sources;
1021 }
1022 Err(text) => return Err(DownloadError::Unreachable(text)),
1024 }
1025 }
1026 }};
1027 }
1028 let resp = match crate::net::proxied_request(&client, reqwest::Method::GET, &url).await.send().await {
1029 Ok(r) => r,
1030 Err(e) => {
1031 network_changed!(e);
1032 last_err = format!("download: {e}");
1033 all_answered = false;
1034 next_source!();
1035 }
1036 };
1037 if !resp.status().is_success() {
1038 last_err = format!("download failed: HTTP {}", resp.status());
1039 all_answered = false;
1040 next_source!();
1041 }
1042 let mut encrypted: Vec<u8> = Vec::with_capacity(
1045 resp.content_length().map(|l| usize::try_from(l).unwrap_or(usize::MAX).min(max_download).min(4 * 1024 * 1024)).unwrap_or(64 * 1024),
1047 );
1048 let total = resp.content_length();
1049 if !step(DownloadStep::Received { bytes: 0, total }) {
1050 return Err(DownloadError::Cancelled);
1051 }
1052 let mut stream = resp.bytes_stream();
1053 loop {
1054 if total.is_some_and(|t| encrypted.len() as u64 >= t) {
1056 break;
1057 }
1058 #[cfg(target_arch = "wasm32")]
1060 let next = match crate::rt::time::timeout(crate::transport::budget(crate::transport::Op::HttpRead, crate::net::transfer_stall()), stream.next()).await {
1061 Ok(next) => next,
1062 Err(_) => {
1063 last_err = "read body: stalled".to_string();
1064 all_answered = false;
1065 next_source!();
1066 }
1067 };
1068 #[cfg(not(target_arch = "wasm32"))]
1069 let next = stream.next().await;
1070 let Some(chunk) = next else { break };
1071 let chunk = match chunk {
1072 Ok(c) => c,
1073 Err(e) => {
1074 network_changed!(e);
1075 last_err = format!("read body: {e}");
1076 all_answered = false;
1077 next_source!();
1078 }
1079 };
1080 if encrypted.len() + chunk.len() > max_download {
1081 return Err(DownloadError::TooLarge(max_download));
1082 }
1083 encrypted.extend_from_slice(&chunk);
1084 if !step(DownloadStep::Received { bytes: encrypted.len() as u64, total }) {
1085 return Err(DownloadError::Cancelled);
1086 }
1087 }
1088 if !step(DownloadStep::Opening) {
1089 return Err(DownloadError::Cancelled);
1090 }
1091 if attachment.key.is_empty() || attachment.nonce.is_empty() {
1094 let hash = crate::crypto::sha256_hex(&encrypted);
1095 if crate::blossom::plaintext_matches(&url, attachment.original_hash.as_deref(), &hash) {
1096 return Ok(encrypted);
1097 }
1098 last_err = "plaintext blob fails its hash claim".to_string();
1099 next_source!();
1100 }
1101 match crate::crypto::decrypt_data_owned(encrypted, &attachment.key, &attachment.nonce) {
1102 Ok(plain) => {
1103 if i > 1 {
1104 log_net_info!("[Download] fallback source {}/{} served {}", i, candidates.len(), url);
1105 }
1106 return Ok(plain);
1107 }
1108 Err(e) => {
1109 last_err = format!("decrypt: {e}");
1112 next_source!();
1113 }
1114 }
1115 }
1116 log_net_fail!("[Download] all {} source(s) failed for {}: {}", candidates.len(), attachment.url, last_err);
1117 Err(if all_answered { DownloadError::Unusable(last_err) } else { DownloadError::Unreachable(last_err) })
1118 }
1119
1120 pub async fn probe_attachment_size(&self, message_id: &str, attachment_id: &str) -> Option<u64> {
1124 crate::db::scoped(async move {
1125 let (chat_id, message) = self.get_message(message_id).await?;
1126 let att = message.attachments.iter().find(|a| a.id == attachment_id)?;
1127 if att.size > 0 {
1128 return Some(att.size);
1129 }
1130 if !(att.url.starts_with("https://") || att.url.starts_with("http://")) {
1131 return None;
1132 }
1133 if !message.mine && crate::requests::shielded() && state::STATE.lock().await.dm_unanswered(&chat_id) {
1134 return None;
1135 }
1136 let probe = crate::net::get_remote_file_size(&att.url);
1137 let size = crate::rt::time::timeout(crate::net::tor_http_timeout(std::time::Duration::from_secs(5)), probe).await.ok().flatten()?;
1138 if let Err(e) = db::attachments::set_attachment_size(message_id, attachment_id, size) {
1139 crate::log_warn!("[Attachments] could not record a probed size: {e}");
1140 }
1141 state::STATE.lock().await.update_attachment(&chat_id, message_id, attachment_id, |a| a.size = size);
1142 Some(size)
1143 })
1144 .await
1145 }
1146
1147 pub async fn send_file(&self, to_npub: &str, file_path: &str) -> Result<sending::SendResult> {
1149 let path = std::path::Path::new(file_path);
1150 let bytes = std::fs::read(path)
1151 .map_err(VectorError::Io)?;
1152 let filename = path.file_name()
1153 .and_then(|n| n.to_str())
1154 .unwrap_or("file");
1155 let extension = path.extension()
1156 .and_then(|e| e.to_str())
1157 .unwrap_or("bin");
1158
1159 sending::send_file_dm(
1160 to_npub,
1161 std::sync::Arc::new(bytes),
1162 filename,
1163 extension,
1164 None,
1165 None,
1166 &SendConfig::default(),
1167 Arc::new(NoOpSendCallback),
1168 ).await.map_err(VectorError::Other)
1169 }
1170
1171 pub async fn send_file_bytes(&self, to_npub: &str, bytes: Vec<u8>, filename: &str, opts: &PostOptions) -> Result<sending::SendResult> {
1175 if opts.expires_in_secs.is_some() {
1176 return Err(VectorError::Other("DMs have no per-message expiry".into()));
1177 }
1178 let (bytes, filename) = ready_to_send(bytes, filename, opts.compress).await?;
1179 let extension = std::path::Path::new(&filename).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
1180 let config = SendConfig { self_send: false, ..SendConfig::headless() };
1181 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))
1182 .await
1183 .map_err(VectorError::Other)?;
1184 if let Some(caption) = opts.caption.as_deref().filter(|c| !c.trim().is_empty()) {
1186 let file_id = sent.event_id.clone().unwrap_or_else(|| sent.pending_id.clone());
1187 self.send_dm_reply(to_npub, &file_id, caption).await?;
1188 }
1189 Ok(sent)
1190 }
1191
1192 pub async fn remove_reaction(&self, reaction_id: &str) -> Result<()> {
1194 crate::db::scoped(async move {
1195 use nostr_sdk::prelude::{EventId, PublicKey, ToBech32};
1196 let session = crate::db::current_session();
1197 let (chat_id, message_id, author_npub, is_community) =
1198 Self::locate_reaction(reaction_id).await.ok_or_else(|| VectorError::NotFound(format!("reaction {reaction_id}")))?;
1199 let me = state::my_public_key().ok_or_else(|| VectorError::NotInitialized("not logged in".into()))?;
1200 if me.to_bech32().ok().as_deref() != Some(author_npub.as_str()) {
1201 return Err(VectorError::Other("only its own author can withdraw a reaction".into()));
1202 }
1203 let updated = state::STATE.lock().await.remove_reaction_from_message(&message_id, reaction_id);
1206 let _ = crate::db::events::delete_event(reaction_id).await;
1207 if let Some((_, mut message)) = updated {
1208 traits::emit_message_update(&chat_id, &message_id, &mut message).await;
1209 }
1210 if !session.is_live() {
1212 return Err(VectorError::Other("account changed while withdrawing the reaction".into()));
1213 }
1214 if is_community {
1215 use crate::community::transport::LiveTransport;
1216 let id = self.v2_community_for_channel(&chat_id)?.ok_or_else(|| VectorError::NotFound("community channel".into()))?;
1217 let community = crate::db::community::load_community_v2(&id)
1218 .map_err(VectorError::Db)?
1219 .ok_or_else(|| VectorError::NotFound("community".into()))?;
1220 let ch = crate::community::ChannelId(Self::id32(&chat_id, "channel_id")?);
1221 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1222 crate::community::v2::service::delete_own(&transport, &community, &ch, reaction_id, crate::community::v2::kind::REACTION)
1223 .await
1224 .map_err(VectorError::Other)?;
1225 } else {
1226 let rid = EventId::from_hex(reaction_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1227 let recipient = PublicKey::parse(&chat_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1228 crate::deletion::delete_own_reaction(&rid, recipient).await.map_err(VectorError::Other)?;
1229 }
1230 Ok(())
1231 })
1232 .await
1233 }
1234
1235 async fn locate_reaction(reaction_id: &str) -> Option<(String, String, String, bool)> {
1238 if let Some(found) = state::STATE.lock().await.find_reaction(reaction_id) {
1239 return Some(found);
1240 }
1241 let parent = crate::db::events::reaction_target(reaction_id).ok().flatten()?;
1242 let (chat_id, message) = crate::db::events::get_message_by_id(&parent).await.ok().flatten()?;
1243 let author = message.reactions.iter().find(|r| r.id == reaction_id)?.author_id.clone();
1244 let community = crate::db::community::community_id_for_channel(&chat_id).ok().flatten().is_some();
1245 Some((chat_id, parent, author, community))
1246 }
1247
1248 pub async fn remove_my_reaction(&self, message_id: &str, emoji: &str) -> Result<bool> {
1250 match Self::own_reaction_id(message_id, emoji).await {
1251 Some(id) => self.remove_reaction(&id).await.map(|_| true),
1252 None => Ok(false),
1253 }
1254 }
1255
1256 async fn own_reaction_id(message_id: &str, emoji: &str) -> Option<String> {
1261 use nostr_sdk::prelude::ToBech32;
1262 let me = state::my_public_key()?.to_bech32().ok()?;
1263 let resident = state::STATE.lock().await.find_message(message_id).map(|(_, m)| m);
1264 let message = match resident {
1265 Some(m) => m,
1266 None => crate::db::events::get_message_by_id(message_id).await.ok().flatten()?.1,
1267 };
1268 message.reactions.iter().find(|r| r.author_id == me && r.emoji == emoji).map(|r| r.id.clone())
1269 }
1270
1271 pub async fn send_reaction(
1276 &self,
1277 to_npub: &str,
1278 reference_id: &str,
1279 emoji: &str,
1280 emoji_url: Option<&str>,
1281 ) -> Result<String> {
1282 use nostr_sdk::prelude::*;
1283
1284 let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
1285 let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
1286
1287 if let Some(existing) = Self::own_reaction_id(reference_id, emoji).await {
1289 return Ok(existing);
1290 }
1291
1292 badges::check_new_reaction_allowance(reference_id, emoji)
1294 .await
1295 .map_err(VectorError::Other)?;
1296
1297 let reference_event = EventId::from_hex(reference_id)
1298 .map_err(|e| VectorError::Nostr(e.to_string()))?;
1299 let receiver_pubkey = PublicKey::from_bech32(to_npub)
1300 .map_err(|e| VectorError::Nostr(e.to_string()))?;
1301
1302 let custom_emoji_tag = emoji_url.and_then(|url| {
1304 if !emoji.starts_with(':') || !emoji.ends_with(':') || emoji.len() < 3 || url.is_empty() {
1305 return None;
1306 }
1307 let shortcode = &emoji[1..emoji.len() - 1];
1308 if shortcode.is_empty() { return None; }
1309 Some(Tag::custom("emoji", [shortcode.to_string(), url.to_string()]))
1310 });
1311
1312 let reaction_target = nostr_sdk::prelude::nip25::ReactionTarget {
1313 event_id: reference_event,
1314 public_key: receiver_pubkey,
1315 coordinate: None,
1316 kind: Some(Kind::PrivateDirectMessage),
1317 relay_hint: None,
1318 };
1319 let mut builder =
1320 nostr_sdk::prelude::nip25::ReactionBuilder::new(reaction_target, emoji)
1321 .into_event_builder();
1322 if let Some(tag) = custom_emoji_tag {
1323 builder = builder.tag(tag);
1324 }
1325 let rumor = builder.finalize_unsigned_with_id(my_public_key);
1326 let inner_rumor_id = rumor.id;
1327 let rumor_id = inner_rumor_id.ok_or(VectorError::Other("Failed to get rumor ID".into()))?.to_hex();
1328
1329 let outcome = inbox_relays::send_gift_wrap_retained(&client, &receiver_pubkey, rumor.clone(), [])
1333 .await.map_err(VectorError::Other)?;
1334 if !outcome.output.success.is_empty() {
1335 if let Some(rid) = inner_rumor_id {
1336 if let Err(e) = db::nip17_keys::store_wrap_key(
1337 &outcome.wrap_event_id, &rid, &receiver_pubkey,
1338 db::nip17_keys::WrapRole::Recipient,
1339 &outcome.wrap_secret, &outcome.targeted_relays,
1340 ) {
1341 crate::log_warn!("[Reaction] failed to persist wrap key: {}", e);
1342 }
1343 }
1344 }
1345
1346 let self_wrap_client = client.clone();
1349 db::spawn_bound(async move {
1350 if let Ok(self_outcome) = inbox_relays::send_gift_wrap_retained(
1351 &self_wrap_client, &my_public_key, rumor, [],
1352 ).await {
1353 if !self_outcome.output.success.is_empty() {
1354 if let Some(rid) = inner_rumor_id {
1355 let _ = db::nip17_keys::store_wrap_key(
1356 &self_outcome.wrap_event_id, &rid, &my_public_key,
1357 db::nip17_keys::WrapRole::SelfSend,
1358 &self_outcome.wrap_secret, &self_outcome.targeted_relays,
1359 );
1360 }
1361 }
1362 }
1363 });
1364
1365 let reaction = Reaction {
1367 id: rumor_id.clone(),
1368 reference_id: reference_id.to_string(),
1369 author_id: my_public_key.to_bech32().unwrap_or_else(|_| my_public_key.to_hex()),
1370 emoji: emoji.to_string(),
1371 emoji_url: emoji_url.map(|s| s.to_string()),
1372 };
1373 let msg_for_save = {
1374 let mut st = state::STATE.lock().await;
1375 match st.add_reaction_to_message(reference_id, reaction) {
1376 Some((cid, true)) => st.find_message(reference_id).map(|(_, m)| (cid, m)),
1377 _ => None,
1378 }
1379 };
1380 if let Some((cid, mut msg)) = msg_for_save {
1381 let _ = db::events::save_message(&cid, &msg).await;
1382 traits::emit_message_update(&cid, reference_id, &mut msg).await;
1383 }
1384
1385 Ok(rumor_id)
1386 }
1387
1388 pub async fn send_typing(&self, to_npub: &str) -> Result<()> {
1391 use nostr_sdk::prelude::*;
1392
1393 let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
1394 let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
1395 let pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
1396 if pubkey == my_public_key {
1398 return Ok(());
1399 }
1400
1401 let expiry = Timestamp::from_secs(crate::clock::timestamp().as_secs() + 30);
1402 let rumor = EventBuilder::new(Kind::ApplicationSpecificData, "typing")
1403 .tag(Tag::public_key(pubkey))
1404 .tag(Tag::custom("d", vec!["vector"]))
1405 .tag(Tag::expiration(expiry))
1406 .finalize_unsigned_with_id(my_public_key);
1407
1408 signer::active_signer().map_err(VectorError::Other)?;
1411 let wrap = signer::gift_wrap(&pubkey, rumor, [Tag::expiration(expiry)])
1413 .await
1414 .map_err(VectorError::Nostr)?;
1415 transport_aware(client.send_event(&wrap))
1416 .to(state::active_trusted_relays().await)
1417 .await
1418 .map_err(|e| VectorError::Nostr(e.to_string()))?;
1419 Ok(())
1420 }
1421
1422 pub async fn edit_dm(&self, to_npub: &str, message_id: &str, new_content: &str) -> Result<String> {
1426 crate::db::scoped(async move {
1427 use nostr_sdk::prelude::*;
1428
1429 let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
1430 let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
1431 let my_npub = my_public_key.to_bech32().map_err(|e| VectorError::Nostr(e.to_string()))?;
1432 let receiver_pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
1433 let reference_event = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1434
1435 let (plain, text_spans) = crate::text_spans::extract_own(new_content);
1436 let new_content = plain.as_str();
1437 let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
1439 let expiry_tags: Vec<Tag> = crate::self_destruct::edit_expiry(message_id)
1441 .await
1442 .map_err(VectorError::Other)?
1443 .map(|exp| Tag::expiration(Timestamp::from_secs(exp)))
1444 .into_iter()
1445 .collect();
1446
1447 let mut builder = EventBuilder::new(
1448 Kind::from_u16(stored_event::event_kind::MESSAGE_EDIT),
1449 new_content,
1450 ).tag(Tag::event(reference_event));
1451 for et in &emoji_tags {
1452 builder = builder.tag(Tag::custom(
1453 "emoji",
1454 [et.shortcode.clone(), et.url.clone()],
1455 ));
1456 }
1457 builder = builder.tags(crate::text_spans::to_nostr_tags(&text_spans));
1458 let rumor = builder.tags(expiry_tags.clone()).finalize_unsigned_with_id(my_public_key);
1459 let edit_id = rumor.id.ok_or(VectorError::Other("Failed to get edit rumor ID".into()))?.to_hex();
1460 let edit_ts_ms = rumor.created_at.as_secs() * 1000;
1461
1462 let msg_for_emit = {
1464 let mut st = state::STATE.lock().await;
1465 st.update_message_in_chat_with(to_npub, message_id, |msg, i| {
1466 msg.apply_edit(new_content.to_string(), edit_ts_ms, emoji_tags.clone(), text_spans.clone(), i);
1467 msg.set_preview_metadata(None);
1468 })
1469 };
1470 if let Some(mut msg) = msg_for_emit {
1471 traits::emit_message_update(to_npub, message_id, &mut msg).await;
1472 if let Ok(db_chat_id) = db::id_cache::get_chat_id_by_identifier(to_npub) {
1473 let _ = db::events::save_edit_event(
1474 &edit_id, message_id, new_content, &emoji_tags, &text_spans, db_chat_id, None, &my_npub,
1475 ).await;
1476 }
1477 }
1478
1479 inbox_relays::send_gift_wrap(&client, &receiver_pubkey, rumor.clone(), expiry_tags.clone())
1480 .await.map_err(VectorError::Other)?;
1481
1482 let self_wrap_client = client.clone();
1483 let self_wrap_session = crate::db::current_session();
1484 db::spawn_bound(async move {
1485 if !self_wrap_session.is_live() { return; }
1486 if let Ok(wrap) = signer::gift_wrap(&my_public_key, rumor, expiry_tags).await {
1487 let _ = crate::transport_aware(self_wrap_client.send_event(&wrap)).await;
1488 }
1489 });
1490
1491 Ok(edit_id)
1492 })
1493 .await
1494 }
1495
1496 pub async fn delete_dm(&self, message_id: &str) -> Result<deletion::DeleteOutcome> {
1499 use nostr_sdk::prelude::*;
1500 let rumor_id = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
1501 let (chat_id, msg) = self.get_message(message_id).await.ok_or_else(|| VectorError::Other("message not found".into()))?;
1502 if !chat_id.starts_with("npub1") {
1503 return Err(VectorError::Other("not a DM".into()));
1504 }
1505 let outcome = if msg.mine { deletion::delete_own_dm(&rumor_id).await } else { deletion::delete_received_dm(&rumor_id).await }
1506 .map_err(VectorError::Other)?;
1507 state::STATE.lock().await.remove_message(message_id);
1508 let _ = crate::db::events::delete_event(message_id).await;
1509 traits::emit_event_json("message_removed", serde_json::json!({ "id": message_id, "chat_id": chat_id, "reason": "deleted" }));
1510 Ok(outcome)
1511 }
1512
1513 pub async fn get_chats(&self) -> Vec<SerializableChat> {
1515 let state = state::STATE.lock().await;
1516 state.chats.iter()
1517 .map(|c| c.to_serializable_with_last_n(1, &state.interner))
1518 .collect()
1519 }
1520
1521 pub async fn get_messages(&self, chat_id: &str, limit: usize, offset: usize) -> Vec<Message> {
1523 let state = state::STATE.lock().await;
1524 let Some(chat) = state.get_chat(chat_id) else { return Vec::new() };
1525 let msgs = chat.messages.messages();
1526 let start = offset.min(msgs.len());
1527 let end = offset.saturating_add(limit).min(msgs.len());
1528 msgs[start..end].iter().map(|m| m.to_message(&state.interner)).collect()
1529 }
1530
1531 pub async fn get_message(&self, message_id: &str) -> Option<(String, Message)> {
1540 {
1541 let state = state::STATE.lock().await;
1542 if let Some((chat, msg)) = state.find_message(message_id) {
1543 return Some((chat.id.clone(), msg));
1544 }
1545 }
1546 db::events::get_message_by_id(message_id).await.ok().flatten()
1547 }
1548
1549 pub async fn get_messages_with_attachment(&self, content_hash: &str) -> Vec<(String, Message)> {
1558 let Ok(ids) = db::attachments::events_with_attachment_hash(content_hash) else { return Vec::new() };
1559 let mut out = Vec::with_capacity(ids.len());
1560 for id in ids {
1561 if let Some(found) = self.get_message(&id).await {
1562 out.push(found);
1563 }
1564 }
1565 out
1566 }
1567
1568 pub async fn get_messages_before(
1578 &self,
1579 chat_id: &str,
1580 before: Option<(u64, &str)>,
1581 limit: usize,
1582 ) -> Vec<Message> {
1583 let state = state::STATE.lock().await;
1584 let Some(chat) = state.get_chat(chat_id) else {
1585 return Vec::new();
1586 };
1587 page_before(chat.messages.messages(), &state.interner, before, limit)
1588 }
1589
1590 pub async fn get_profile(&self, npub: &str) -> Option<SlimProfile> {
1592 let state = state::STATE.lock().await;
1593 state.get_profile(npub)
1594 .map(|p| SlimProfile::from_profile(p, &state.interner))
1595 }
1596
1597 pub async fn load_profile(&self, npub: &str) -> bool {
1599 profile::sync::load_profile(npub.to_string(), &NoOpProfileSyncHandler).await
1600 }
1601
1602 pub async fn update_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
1604 profile::sync::update_profile(
1605 name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
1606 &NoOpProfileSyncHandler,
1607 ).await
1608 }
1609
1610 pub async fn update_bot_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
1613 profile::sync::update_bot_profile(
1614 name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
1615 &NoOpProfileSyncHandler,
1616 ).await
1617 }
1618
1619 pub async fn set_stream_consent(&self, on: bool) -> Result<bool> {
1622 db::scoped_result(profile::sync::set_stream_consent(on, &NoOpProfileSyncHandler))
1623 .await
1624 .map_err(VectorError::Other)
1625 }
1626
1627 pub async fn update_status(&self, status: &str) -> bool {
1629 profile::sync::update_status(status.to_string()).await
1630 }
1631
1632 pub async fn upload_public_image(&self, file_path: &str) -> Result<String> {
1638 let path = std::path::Path::new(file_path);
1639 let bytes = std::fs::read(path).map_err(VectorError::Io)?;
1640 if bytes.is_empty() {
1641 return Err(VectorError::Other("Empty image file".into()));
1642 }
1643 let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
1644 let mime = crate::crypto::mime_from_extension(&extension);
1645 let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
1646 let signer = crate::signer::active_signer()
1647 .map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
1648 let servers = crate::blossom_servers::compute_enabled_servers();
1649 if servers.is_empty() {
1650 return Err(VectorError::Other("No Blossom servers configured".into()));
1651 }
1652 crate::blossom::upload_blob_with_failover(
1655 signer,
1656 servers,
1657 std::sync::Arc::new(bytes),
1658 Some(mime),
1659 Some(crate::net::tor_http_timeout(std::time::Duration::from_secs(20))),
1660 )
1661 .await
1662 .map_err(VectorError::Other)
1663 }
1664
1665 pub async fn block_user(&self, npub: &str) -> bool {
1667 profile::sync::block_user(npub.to_string(), &NoOpProfileSyncHandler).await
1668 }
1669
1670 pub async fn unblock_user(&self, npub: &str) -> bool {
1672 profile::sync::unblock_user(npub.to_string(), &NoOpProfileSyncHandler).await
1673 }
1674
1675 pub async fn set_nickname(&self, npub: &str, nickname: &str) -> bool {
1677 profile::sync::set_nickname(npub.to_string(), nickname.to_string(), &NoOpProfileSyncHandler).await
1678 }
1679
1680 pub async fn get_blocked_users(&self) -> Vec<SlimProfile> {
1682 profile::sync::get_blocked_users().await
1683 }
1684
1685 pub fn queue_profile_sync(&self, npub: &str, priority: SyncPriority) {
1687 profile::sync::queue_profile_sync(npub.to_string(), priority, false);
1688 }
1689
1690 pub fn my_npub(&self) -> Option<String> {
1692 state::my_public_key()
1693 .and_then(|pk| ToBech32::to_bech32(&pk).ok())
1694 }
1695
1696 pub async fn list_communities(&self) -> Vec<serde_json::Value> {
1703 let ids = crate::db::community::list_community_ids().unwrap_or_default();
1704 let me = state::my_public_key();
1705 let mut out = Vec::new();
1706 for id in ids {
1707 let Ok(Some(c)) = crate::db::community::load_community_v2(&id) else { continue };
1708 let is_owner = me.is_some_and(|m| c.owner().is_ok_and(|o| o == m));
1709 out.push(serde_json::json!({
1710 "community_id": crate::simd::hex::bytes_to_hex_32(&c.identity.community_id.0),
1711 "version": 2,
1712 "name": c.name,
1713 "description": c.description,
1714 "is_owner": is_owner,
1715 "dissolved": c.dissolved,
1720 "channels": c.layout().1.into_iter()
1726 .map(|(ch, cat)| serde_json::json!({
1727 "channel_id": crate::simd::hex::bytes_to_hex_32(&ch.id.0),
1728 "name": ch.name,
1729 "private": ch.private,
1730 "readable": !(ch.private && ch.key.is_none()),
1731 "epoch": ch.epoch.0,
1732 "category_id": cat.map(|k| crate::simd::hex::bytes_to_hex_32(&k.id)),
1733 "topic": ch.topic(),
1734 "view": ch.view().as_str(),
1735 }))
1736 .collect::<Vec<_>>(),
1737 "categories": Self::categories_json(&c),
1738 }));
1739 }
1740 out
1741 }
1742
1743 pub async fn create_community_v2(&self, name: &str) -> Result<serde_json::Value> {
1747 self.create_community_with(name, &NewCommunity::default()).await
1748 }
1749
1750 pub async fn create_community_with(&self, name: &str, opts: &NewCommunity) -> Result<serde_json::Value> {
1753 use crate::community::{v2::service as v2, transport::LiveTransport};
1754 let relays: Vec<String> = if opts.relays.is_empty() {
1755 crate::state::active_trusted_relays().await.iter().map(|s| s.to_string()).collect()
1756 } else {
1757 crate::community::v2::service::clean_relays(&[], &opts.relays).map_err(VectorError::Other)?
1758 };
1759 if relays.is_empty() {
1760 return Err(VectorError::Other("no relays available to host the Community".into()));
1761 }
1762 let session = crate::db::current_session();
1763 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
1764 let mut community = v2::create_community_on_roles_v2(&transport, name, relays, opts.description.clone())
1765 .await
1766 .map_err(VectorError::Other)?;
1767 if !session.is_live() {
1768 return Err(VectorError::Other("account changed while creating the community".into()));
1769 }
1770 self.register_v2_chats(&community, &session).await;
1771 if let Some(first) = opts.first_channel.as_deref().map(str::trim).filter(|n| !n.is_empty() && *n != "general") {
1774 if let Some(ch) = community.channels.first().cloned() {
1775 let mut meta = ch.metadata();
1777 meta.name = first.to_string();
1778 match v2::edit_channel_metadata(&transport, &community, &ch.id, &meta).await {
1779 Ok(()) => {
1780 if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
1781 community = fresh;
1782 if session.is_live() {
1783 self.register_v2_chats(&community, &session).await;
1784 }
1785 }
1786 }
1787 Err(e) => crate::log_warn!("[v2:create] the first channel keeps the name general: {e}"),
1788 }
1789 }
1790 }
1791 if let Some(client) = state::nostr_client() {
1793 crate::community::v2::realtime::refresh_subscription(&client).await;
1794 }
1795 Ok(Self::v2_summary(&community))
1796 }
1797
1798 fn v2_community_for_channel(&self, channel_id: &str) -> Result<Option<crate::community::CommunityId>> {
1802 let Some(cid_hex) = crate::db::community::community_id_for_channel(channel_id).map_err(VectorError::Other)? else {
1803 return Ok(None);
1804 };
1805 let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
1806 Ok(crate::db::community::community_held(&cid).map_err(VectorError::Other)?.then_some(cid))
1807 }
1808
1809 fn v2_summary(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
1811 let me = state::my_public_key();
1812 let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
1813 serde_json::json!({
1814 "community_id": crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0),
1815 "version": 2,
1816 "name": community.name,
1817 "description": community.description,
1818 "is_owner": is_owner,
1819 "primary_channel": community.primary_channel().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)),
1824 "channels": community.layout().1.into_iter()
1825 .map(|(c, cat)| serde_json::json!({
1826 "channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
1827 "name": c.name,
1828 "private": c.private,
1829 "category_id": cat.map(|k| crate::simd::hex::bytes_to_hex_32(&k.id)),
1830 "topic": c.topic(),
1831 "view": c.view().as_str(),
1832 }))
1833 .collect::<Vec<_>>(),
1834 "categories": Self::categories_json(community),
1835 "system_channel": community.system_lines_target().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)),
1836 "landing_channel": community.landing_channel().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)),
1837 })
1838 }
1839
1840 pub fn my_channel_permissions(community: &crate::community::v2::community::CommunityV2) -> std::collections::HashMap<[u8; 32], u64> {
1843 let Some(me) = state::my_public_key() else { return Default::default() };
1844 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1845 let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
1846 if roster.everyone.is_none() {
1847 return Default::default();
1848 }
1849 let owner = community.owner().ok().map(|o| o.to_hex());
1850 community
1851 .channels
1852 .iter()
1853 .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))
1854 .collect()
1855 }
1856
1857 pub fn categories_json(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
1859 community
1860 .layout()
1861 .0
1862 .into_iter()
1863 .map(|k| serde_json::json!({ "category_id": crate::simd::hex::bytes_to_hex_32(&k.id), "name": k.name }))
1864 .collect()
1865 }
1866
1867 pub async fn register_v2_chats(&self, community: &crate::community::v2::community::CommunityV2, __session: &std::sync::Arc<crate::db::Session>) {
1873 register_v2_chats_inner(community).await
1874 }
1875}
1876
1877pub(crate) async fn register_v2_chats_inner(community: &crate::community::v2::community::CommunityV2) {
1880 crate::community::v2::changes::prime(community);
1883 crate::db::scoped(async move {
1884 match crate::db::community::settle_presence_lines(community) {
1887 Ok(true) => crate::emit_event("community_presence_lines", &serde_json::json!({ "community_id": crate::simd::hex::bytes_to_hex_32(&community.id().0) })),
1888 Ok(false) => {}
1889 Err(e) => crate::log_warn!("[presence] settling join lines on register: {e}"),
1890 }
1891 let owner_npub = community.owner().ok().and_then(|p| ToBech32::to_bech32(&p).ok());
1892 let me = state::my_public_key();
1893 let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
1894 let id_hex = crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0);
1895 let Some(primary) = community.primary_channel() else { return };
1898 let primary_hex = crate::simd::hex::bytes_to_hex_32(&primary.id.0);
1899 let slims = {
1904 let mut st = state::STATE.lock().await;
1905 let mut slims = Vec::new();
1906 for ch in &community.channels {
1907 let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
1908 st.upsert_community_chat(
1909 &ch_hex,
1910 &community.name,
1911 community.description.as_deref().unwrap_or(""),
1912 &id_hex,
1913 is_owner,
1914 community.icon.is_some(),
1915 owner_npub.as_deref(),
1916 Some(community.created_at_ms),
1917 community.dissolved,
1918 &ch.name,
1919 &primary_hex,
1920 );
1921 if let Some(chat) = st.chats.iter().find(|c| c.id == ch_hex) {
1922 slims.push(crate::db::chats::SlimChatDB::from_chat(chat, &st.interner));
1923 }
1924 }
1925 slims
1926 };
1927 for slim in &slims {
1929 let _ = crate::db::chats::save_slim_chat(slim);
1930 }
1931 })
1932 .await
1933}
1934
1935const RAID_REPORT_TTL_SECS: u64 = 90;
1939
1940struct RaidReportCache;
1942
1943struct PolicyReportCache;
1944struct PolicyReportGate;
1945
1946type ReportCache<T> = std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, (u64, std::sync::Arc<T>)>>>;
1947
1948fn policy_report_cache() -> ReportCache<serde_json::Value> {
1952 crate::db::current_session().scoped::<PolicyReportCache, _>()
1953}
1954
1955fn policy_report_gate() -> std::sync::Arc<std::sync::Mutex<()>> {
1956 crate::db::current_session().scoped::<PolicyReportGate, _>()
1957}
1958
1959fn raid_report_cache() -> ReportCache<crate::community::raid::RaidReport> {
1960 crate::db::current_session().scoped::<RaidReportCache, _>()
1961}
1962
1963fn report_get<T>(cache: &ReportCache<T>, cid_hex: &str, now_secs: u64) -> Option<std::sync::Arc<T>> {
1966 let mut map = cache.lock().unwrap_or_else(|e| e.into_inner());
1967 map.retain(|_, (at, _)| now_secs.saturating_sub(*at) < RAID_REPORT_TTL_SECS);
1968 map.get(cid_hex).map(|(_, report)| report.clone())
1969}
1970
1971fn report_put<T>(cache: &ReportCache<T>, cid_hex: &str, now_secs: u64, report: std::sync::Arc<T>) {
1972 let mut map = cache.lock().unwrap_or_else(|e| e.into_inner());
1973 map.retain(|_, (at, _)| now_secs.saturating_sub(*at) < RAID_REPORT_TTL_SECS);
1974 map.insert(cid_hex.to_string(), (now_secs, report));
1975}
1976
1977fn report_once<T>(
1980 cache: &ReportCache<T>,
1981 gate: &std::sync::Mutex<()>,
1982 cid_hex: &str,
1983 now_secs: u64,
1984 compute: impl FnOnce() -> Result<std::sync::Arc<T>>,
1985) -> Result<std::sync::Arc<T>> {
1986 if let Some(hit) = report_get(cache, cid_hex, now_secs) {
1987 return Ok(hit);
1988 }
1989 let _turn = gate.lock().unwrap_or_else(|e| e.into_inner());
1990 if let Some(hit) = report_get(cache, cid_hex, now_secs) {
1991 return Ok(hit);
1992 }
1993 let report = compute()?;
1994 report_put(cache, cid_hex, now_secs, report.clone());
1995 Ok(report)
1996}
1997
1998#[cfg(test)]
1999mod report_cache_tests {
2000 use super::*;
2001
2002 #[test]
2003 fn an_expired_report_goes_on_the_next_touch() {
2004 let cache: ReportCache<u32> = Default::default();
2005 report_put(&cache, "a", 1_000, std::sync::Arc::new(1));
2006 report_put(&cache, "b", 1_050, std::sync::Arc::new(2));
2007 assert_eq!(report_get(&cache, "a", 1_000 + RAID_REPORT_TTL_SECS - 1).as_deref(), Some(&1));
2008 assert_eq!(report_get(&cache, "a", 1_000 + RAID_REPORT_TTL_SECS), None, "a report is fresh for the TTL, no longer");
2009 assert_eq!(cache.lock().unwrap().len(), 1, "the lookup dropped it");
2010 report_put(&cache, "c", 1_050 + RAID_REPORT_TTL_SECS, std::sync::Arc::new(3));
2011 let map = cache.lock().unwrap();
2012 assert!(!map.contains_key("b") && map.contains_key("c"), "and so does an insert");
2013 }
2014
2015 #[test]
2016 fn callers_that_miss_together_share_one_evaluation() {
2017 let cache: ReportCache<u32> = Default::default();
2018 let gate = std::sync::Mutex::new(());
2019 let runs = std::sync::atomic::AtomicU32::new(0);
2020 std::thread::scope(|s| {
2021 for _ in 0..4 {
2022 s.spawn(|| {
2023 let got = report_once(&cache, &gate, "a", 1_000, || {
2024 runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2025 std::thread::sleep(std::time::Duration::from_millis(50));
2026 Ok(std::sync::Arc::new(7))
2027 });
2028 assert_eq!(got.unwrap().as_ref(), &7);
2029 });
2030 }
2031 });
2032 assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1);
2033 let again = report_once(&cache, &gate, "a", 1_000 + RAID_REPORT_TTL_SECS, || Ok(std::sync::Arc::new(8)));
2034 assert_eq!(again.unwrap().as_ref(), &8, "an expired report is evaluated afresh");
2035 }
2036}
2037
2038impl VectorCore {
2039 pub async fn join_community(&self, invite_url: &str) -> Result<serde_json::Value> {
2043 use crate::community::transport::LiveTransport;
2044 crate::community::v2::invite::parse_invite_link(invite_url)
2045 .map_err(|_| VectorError::Other("not a Vector invite link".into()))?;
2046 let session = crate::db::current_session();
2047 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2048 let community = crate::community::v2::service::accept_public_link(&transport, invite_url)
2049 .await
2050 .map_err(VectorError::Other)?;
2051 self.register_v2_chats(&community, &session).await;
2052 if let Some(client) = state::nostr_client() {
2053 crate::community::v2::realtime::refresh_subscription(&client).await;
2054 }
2055 if crate::community::v2::realtime::follow_worker_running() {
2060 crate::community::v2::realtime::enqueue_follow(community.id());
2061 } else {
2062 let seed_community = community.clone();
2063 db::spawn_bound(async move {
2064 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2065 if matches!(
2066 crate::community::v2::service::sync_guestbook(&transport, &seed_community).await,
2067 Ok(fresh) if !fresh.is_empty()
2068 ) {
2069 let cid_hex = crate::simd::hex::bytes_to_hex_32(&seed_community.id().0);
2070 emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
2071 }
2072 });
2073 }
2074 Ok(Self::v2_summary(&community))
2075 }
2076
2077 pub fn list_pending_invites(&self) -> Result<Vec<serde_json::Value>> {
2080 let rows = crate::db::community::list_pending_invites().map_err(VectorError::Other)?;
2081 Ok(rows
2082 .iter()
2083 .filter_map(|p| {
2084 let v2 = crate::community::v2::invite::CommunityInvite::from_bundle_json(&p.bundle_json).ok()?;
2085 Some(serde_json::json!({
2086 "community_id": p.community_id,
2087 "name": v2.name,
2088 "inviter_npub": p.inviter_npub,
2089 "version": 2,
2090 }))
2091 })
2092 .collect())
2093 }
2094
2095 pub async fn accept_pending_invite(&self, community_id: &str) -> Result<serde_json::Value> {
2099 crate::db::scoped(async move {
2100 use crate::community::transport::LiveTransport;
2101 let bundle_json = crate::db::community::get_pending_invite(community_id)
2102 .map_err(VectorError::Other)?
2103 .ok_or_else(|| VectorError::Other(format!("no pending invite for {community_id}")))?;
2104 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2105 let session = crate::db::current_session();
2106 let inviter = crate::db::community::list_pending_invites()
2108 .ok()
2109 .and_then(|rows| rows.into_iter().find(|p| p.community_id == community_id).map(|p| p.inviter_npub));
2110 let community = match crate::community::v2::service::accept_parked_invite(&transport, &bundle_json, inviter.as_deref()).await {
2122 Ok(c) => c,
2123 Err(e) if e == crate::community::v2::service::ERR_DISSOLVED => {
2124 let relays = crate::community::v2::invite::CommunityInvite::from_bundle_json(&bundle_json)
2125 .map(|i| i.relays)
2126 .unwrap_or_default();
2127 crate::community::v2::service::retire_dead_invite(&transport, community_id, &relays).await;
2128 return Err(VectorError::Other("this community has been dissolved — the invite was removed".into()));
2129 }
2130 Err(e) => return Err(VectorError::Other(e)),
2131 };
2132 self.register_v2_chats(&community, &session).await;
2133 if let Some(client) = state::nostr_client() {
2134 crate::community::v2::realtime::refresh_subscription(&client).await;
2135 }
2136 crate::community::v2::realtime::enqueue_follow(community.id());
2137 let _ = crate::db::community::delete_pending_invite(community_id);
2138 Ok(Self::v2_summary(&community))
2139 })
2140 .await
2141 }
2142
2143
2144 fn v2_community(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
2148 use crate::community::CommunityId;
2149 if community_id.len() != 64 {
2150 return Err(VectorError::Other("malformed community id".into()));
2151 }
2152 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2153 crate::db::community::load_community_v2(&cid)
2154 .map_err(VectorError::Other)?
2155 .ok_or_else(|| VectorError::Other("community not found".into()))
2156 }
2157
2158 fn channel_id_of(channel_id: &str) -> Result<crate::community::ChannelId> {
2159 crate::simd::hex::hex_to_bytes_32_checked(channel_id)
2160 .map(crate::community::ChannelId)
2161 .ok_or_else(|| VectorError::Other("malformed channel id".into()))
2162 }
2163
2164 pub async fn create_channel(&self, community_id: &str, name: &str, private: bool) -> Result<String> {
2169 use crate::community::{v2::service, transport::LiveTransport};
2170 let community = Self::v2_community(community_id)?;
2171 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2172 let id = if private {
2173 service::create_private_channel(&transport, &community, name).await
2174 } else {
2175 service::create_public_channel(&transport, &community, name).await
2176 }
2177 .map_err(VectorError::Other)?;
2178 if let Some(client) = state::nostr_client() {
2181 crate::community::v2::realtime::refresh_subscription(&client).await;
2182 }
2183 Ok(crate::simd::hex::bytes_to_hex_32(&id.0))
2184 }
2185
2186 pub async fn create_channel_with(&self, community_id: &str, name: &str, opts: &NewChannel) -> Result<String> {
2188 use crate::community::{v2::service, transport::LiveTransport};
2189 let name = name.trim();
2190 if name.is_empty() {
2191 return Err(VectorError::Other("a channel needs a name".into()));
2192 }
2193 let view = opts.view.as_deref().map(Self::view_named).transpose()?;
2194 let session = crate::db::current_session();
2195 let community = Self::v2_community(community_id)?;
2196 let category = opts.category_id.as_deref().map(|c| Self::id32(c, "category_id")).transpose()?;
2197 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2199 let id = service::create_channel_in(&transport, &community, name, opts.private, category).await.map_err(VectorError::Other)?;
2200 let channel_id = crate::simd::hex::bytes_to_hex_32(&id.0);
2201 if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
2203 if session.is_live() {
2204 self.register_v2_chats(&fresh, &session).await;
2205 }
2206 }
2207 if view.is_some() || opts.topic.is_some() {
2210 let view = view.unwrap_or(crate::community::v2::community::ChannelView::Chat).as_str();
2211 if let Err(e) = self.edit_channel_details(community_id, &channel_id, name, opts.topic.as_deref(), view).await {
2212 crate::log_warn!("[v2:create] channel {} stands without its view or topic: {e}", &channel_id[..12]);
2213 }
2214 }
2215 if let Some(client) = state::nostr_client() {
2216 crate::community::v2::realtime::refresh_subscription(&client).await;
2217 }
2218 Ok(channel_id)
2219 }
2220
2221 pub async fn duplicate_channel(&self, community_id: &str, channel_id: &str, name: &str) -> Result<String> {
2225 use crate::community::{v2::service, transport::LiveTransport};
2226 let session = crate::db::current_session();
2227 let community = Self::v2_community(community_id)?;
2228 let source = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
2229 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2230 let id = service::duplicate_channel(&transport, &community, &source, name).await.map_err(VectorError::Other)?;
2231 if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
2232 if session.is_live() {
2233 self.register_v2_chats(&fresh, &session).await;
2234 }
2235 }
2236 if let Some(client) = state::nostr_client() {
2237 crate::community::v2::realtime::refresh_subscription(&client).await;
2238 }
2239 Ok(crate::simd::hex::bytes_to_hex_32(&id.0))
2240 }
2241
2242 pub async fn preview_public_link(&self, url: &str) -> Result<LinkPreview> {
2245 use crate::community::{transport::LiveTransport, CommunityId};
2246 crate::community::v2::invite::parse_invite_link(url).map_err(|_| VectorError::Other("not a Vector invite link".into()))?;
2247 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2248 let bundle = crate::community::v2::service::fetch_public_bundle_for_preview(&transport, url).await.map_err(VectorError::Other)?;
2249 let community_id = bundle.community_id.clone();
2251 if let Ok(id) = Self::id32(&community_id, "community_id") {
2252 if let Ok(Some(local)) = crate::db::community::load_community_v2(&CommunityId(id)) {
2253 return Ok(LinkPreview {
2254 community_id,
2255 name: local.name.clone(),
2256 description: local.description.clone(),
2257 icon: local.icon.as_ref().map(|i| i.to_community_image()),
2258 joined: true,
2259 verified: true,
2260 });
2261 }
2262 }
2263 let (folded, verified) = crate::community::v2::service::preview_bundle_checked(&transport, &bundle).await.map_err(VectorError::Other)?;
2264 Ok(LinkPreview {
2265 community_id,
2266 name: folded.name.clone(),
2267 description: folded.description.clone(),
2268 icon: folded.icon.as_ref().map(|i| i.to_community_image()),
2269 joined: false,
2270 verified,
2271 })
2272 }
2273
2274 pub async fn rename_channel(&self, community_id: &str, channel_id: &str, name: &str) -> Result<()> {
2277 use crate::community::{v2::service, transport::LiveTransport};
2278 let community = Self::v2_community(community_id)?;
2279 let id = Self::channel_id_of(channel_id)?;
2280 let mut meta = community
2281 .channel(&id)
2282 .ok_or_else(|| VectorError::Other("unknown channel".into()))?
2283 .metadata();
2284 meta.name = name.to_string();
2285 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2286 service::edit_channel_metadata(&transport, &community, &id, &meta)
2287 .await
2288 .map_err(VectorError::Other)
2289 }
2290
2291 pub async fn delete_channel(&self, community_id: &str, channel_id: &str) -> Result<()> {
2294 use crate::community::{v2::service, transport::LiveTransport};
2295 let community = Self::v2_community(community_id)?;
2296 let id = Self::channel_id_of(channel_id)?;
2297 let name = community.channel(&id).map(|c| c.name.clone()).unwrap_or_default();
2298 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2299 service::delete_channel(&transport, &community, &id, &name)
2300 .await
2301 .map_err(VectorError::Other)
2302 }
2303
2304 pub async fn grant_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
2307 use crate::community::{v2::service, transport::LiveTransport};
2308 let community = Self::v2_community(community_id)?;
2309 let id = Self::channel_id_of(channel_id)?;
2310 let member = nostr_sdk::prelude::PublicKey::parse(npub)
2311 .map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
2312 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2313 service::grant_channel_access(&transport, &community, &id, &member)
2314 .await
2315 .map_err(VectorError::Other)
2316 }
2317
2318 pub async fn revoke_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
2322 use crate::community::{v2::service, transport::LiveTransport};
2323 let community = Self::v2_community(community_id)?;
2324 let id = Self::channel_id_of(channel_id)?;
2325 let member = nostr_sdk::prelude::PublicKey::parse(npub)
2326 .map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
2327 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2328 service::revoke_channel_access(&transport, &community, &id, &member)
2329 .await
2330 .map_err(VectorError::Other)
2331 }
2332
2333 pub fn member_can_read_channel(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<bool> {
2356 use nostr_sdk::prelude::PublicKey;
2357 let community = Self::v2_community(community_id)?;
2358 let id = Self::channel_id_of(channel_id)?;
2359 let ch = community.channel(&id).ok_or_else(|| VectorError::Other("unknown channel".into()))?;
2360 let who = PublicKey::parse(npub).map_err(|_| VectorError::Other(format!("invalid npub: {npub}")))?.to_hex();
2361 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
2362 if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&who) {
2363 return Ok(false);
2364 }
2365 if !ch.private {
2366 return Ok(true);
2367 }
2368 if community.owner().map(|o| o.to_hex()) == Ok(who.clone()) {
2369 return Ok(true);
2370 }
2371 let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
2372 let access_ids = roster.channel_role_ids(&crate::simd::hex::bytes_to_hex_32(&id.0));
2373 Ok(roster
2374 .grants
2375 .iter()
2376 .filter(|g| g.member == who)
2377 .any(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid))))
2378 }
2379
2380 pub fn channel_access(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
2381 use nostr_sdk::prelude::{PublicKey, ToBech32};
2382 let community = Self::v2_community(community_id)?;
2383 let id = Self::channel_id_of(channel_id)?;
2384 let ch = community
2385 .channel(&id)
2386 .ok_or_else(|| VectorError::Other("unknown channel".into()))?;
2387 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
2390 let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
2391 let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
2392 let chan_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
2393 let owner_hex = community.owner().ok().map(|o| o.to_hex());
2394 let (roles, members): (Vec<serde_json::Value>, Vec<String>) = if roster.everyone.is_some() {
2395 use crate::community::roles::{OverwriteTarget, Permissions};
2397 let scope = roster.syncs.get(&chan_hex).cloned().unwrap_or_else(|| chan_hex.clone());
2398 let roles = roster
2399 .overwrites
2400 .iter()
2401 .filter(|o| o.scope == scope && o.allow.contains(Permissions::VIEW_CHANNEL))
2402 .filter_map(|o| match &o.target {
2403 OverwriteTarget::Role(id) => roster.role(id).map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name })),
2404 _ => None,
2405 })
2406 .collect();
2407 let mut named: Vec<String> = roster.grants.iter().map(|g| g.member.clone()).collect();
2408 named.extend(roster.overwrites.iter().filter_map(|o| match &o.target {
2409 OverwriteTarget::Member(m) => Some(m.clone()),
2410 _ => None,
2411 }));
2412 named.sort();
2413 named.dedup();
2414 let members = named
2415 .into_iter()
2416 .filter(|m| !banned.contains(m) && Some(m) != owner_hex.as_ref() && roster.is_entitled(owner_hex.as_deref(), m, &chan_hex, &[], &[]))
2417 .filter_map(|m| PublicKey::from_hex(&m).ok().and_then(|pk| pk.to_bech32().ok()))
2418 .collect();
2419 (roles, members)
2420 } else {
2421 let access_ids = roster.channel_role_ids(&chan_hex);
2422 let roles = roster
2423 .channel_roles(&chan_hex)
2424 .into_iter()
2425 .map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name }))
2426 .collect();
2427 let members = roster
2428 .grants
2429 .iter()
2430 .filter(|g| !banned.contains(&g.member))
2431 .filter(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid)))
2432 .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
2433 .collect();
2434 (roles, members)
2435 };
2436 Ok(serde_json::json!({
2437 "channel_id": chan_hex,
2438 "private": ch.private,
2439 "readable": !(ch.private && ch.key.is_none()),
2440 "owner": community.owner().ok().and_then(|o| o.to_bech32().ok()),
2441 "roles": roles,
2442 "members": members,
2443 }))
2444 }
2445
2446 pub async fn create_public_invite(
2450 &self,
2451 community_id: &str,
2452 expires_at_ms: Option<u64>,
2453 label: Option<String>,
2454 ) -> Result<String> {
2455 use crate::community::CommunityId;
2456 if community_id.len() != 64 {
2457 return Err(VectorError::Other("malformed community id".into()));
2458 }
2459 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2460 let community = crate::db::community::load_community_v2(&cid)
2461 .map_err(VectorError::Other)?
2462 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2463 let base = crate::community::v2::invite::INVITE_URL_BASE.trim_end_matches("/invite");
2465 let label = Some(crate::community::v2::invite::resolve_invite_label(community_id, label).map_err(VectorError::Other)?);
2466 let minted = crate::community::v2::service::mint_public_link_sync_later(&community, base, expires_at_ms, label)
2467 .await
2468 .map_err(VectorError::Other)?;
2469 Ok(minted.url)
2470 }
2471
2472 pub async fn invite_to_community(&self, community_id: &str, invitee_npub: &str) -> Result<serde_json::Value> {
2475 crate::db::scoped(async move {
2476 use crate::community::CommunityId;
2477
2478 let my_pk = crate::state::my_public_key()
2479 .ok_or_else(|| VectorError::Other("Public key not set".into()))?;
2480
2481 if community_id.len() != 64 {
2482 return Err(VectorError::Other("malformed community id".into()));
2483 }
2484 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2485 let recipient = nostr_sdk::prelude::PublicKey::parse(invitee_npub)
2489 .map_err(|e| VectorError::Other(format!("bad invitee npub: {e}")))?;
2490 let client = crate::state::nostr_client().ok_or_else(|| VectorError::Other("Not connected".into()))?;
2491 let bundle = {
2499 let lock = crate::community::v2::realtime::follow_lock(&cid);
2500 let _rotation = lock.lock().await;
2501 let community = crate::db::community::load_community_v2(&cid)
2502 .map_err(VectorError::Other)?
2503 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2504 crate::community::v2::service::bundle_of(
2505 &community,
2506 crate::community::v2::service::BundleAudience::Member(recipient),
2507 Some(my_pk),
2508 None,
2509 None,
2510 )
2511 };
2512 let bundle_json = serde_json::to_string(&bundle).map_err(|e| VectorError::Other(e.to_string()))?;
2513 let expires_at = crate::clock::timestamp().as_secs()
2515 + crate::community::v2::invite::DIRECT_INVITE_EXPIRY_SECS;
2516 let expiry_tag = nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(expires_at));
2517 let rumor = nostr_sdk::prelude::EventBuilder::new(
2518 nostr_sdk::prelude::Kind::Custom(crate::community::v2::kind::DIRECT_INVITE),
2519 bundle_json,
2520 )
2521 .tag(expiry_tag.clone())
2522 .finalize_unsigned_with_id(my_pk);
2523 let k_tag = nostr_sdk::prelude::Tag::custom(
2524 "k",
2525 [crate::community::v2::kind::DIRECT_INVITE.to_string()],
2526 );
2527 crate::inbox_relays::send_gift_wrap(&client, &recipient, rumor, [k_tag, expiry_tag])
2528 .await
2529 .map_err(VectorError::Other)?;
2530 Ok(serde_json::json!({ "invited": invitee_npub, "version": 2 }))
2531 })
2532 .await
2533 }
2534
2535 pub fn list_public_invites(&self, community_id: &str) -> Result<Vec<crate::db::community::PublicInviteRecord>> {
2540 crate::db::community::list_public_invites(community_id).map_err(VectorError::Other)
2541 }
2542
2543 pub async fn sync_public_invites(&self, community_id: &str) -> Result<bool> {
2546 let held = Self::held_v2(community_id)?;
2547 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2548 crate::community::v2::service::adopt_invite_list(&transport, &held).await.map_err(VectorError::Other)
2549 }
2550
2551 pub async fn revoke_public_invite(&self, community_id: &str, token: &str) -> Result<()> {
2556 use crate::community::{transport::LiveTransport, CommunityId};
2557 if community_id.len() != 64 {
2558 return Err(VectorError::Other("malformed community id".into()));
2559 }
2560 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
2561 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
2562 let community = crate::db::community::load_community_v2(&cid)
2565 .map_err(VectorError::Other)?
2566 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2567 crate::community::v2::service::revoke_public_link(&transport, &community, token)
2568 .await
2569 .map_err(VectorError::Other)
2570 }
2571
2572 pub async fn send_community_message(
2574 &self,
2575 channel_id: &str,
2576 content: &str,
2577 replied_to: Option<&str>,
2578 ) -> Result<String> {
2579 self.send_community_message_expiring(channel_id, content, replied_to, None).await
2580 }
2581
2582 pub async fn send_community_message_expiring(
2591 &self,
2592 channel_id: &str,
2593 content: &str,
2594 replied_to: Option<&str>,
2595 expires_in_secs: Option<u64>,
2596 ) -> Result<String> {
2597 let opts = PostOptions { reply_to: replied_to.map(str::to_string), expires_in_secs, ..Default::default() };
2598 self.post_community_message(channel_id, content, &opts).await
2599 }
2600
2601 pub async fn post_community_message(&self, channel_id: &str, content: &str, opts: &PostOptions) -> Result<String> {
2604 self.post_community(channel_id, content, Vec::new(), opts, std::time::Duration::from_secs(12)).await
2605 }
2606
2607 async fn post_community(
2610 &self,
2611 channel_id: &str,
2612 content: &str,
2613 mut extra_tags: Vec<nostr_sdk::prelude::Tag>,
2614 opts: &PostOptions,
2615 timeout: std::time::Duration,
2616 ) -> Result<String> {
2617 use crate::community::transport::LiveTransport;
2618 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2619 let community = crate::db::community::load_community_v2(&id)
2620 .map_err(VectorError::Other)?
2621 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2622 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2623 let transport = LiveTransport::with_timeout(timeout);
2624 let reply = match opts.reply_to.as_deref().filter(|r| !r.is_empty()) {
2627 Some(parent_id) => {
2628 let author_hex = {
2629 let st = state::STATE.lock().await;
2630 st.find_message(parent_id)
2631 .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
2632 .map(|pk| pk.to_hex())
2633 .unwrap_or_default()
2634 };
2635 Some((parent_id.to_string(), author_hex))
2636 }
2637 None => None,
2638 };
2639 let reply_ref = reply.as_ref().map(|(id, author)| (id.as_str(), author.as_str()));
2640 let (named, role_mentions) = crate::community::mentions::resolve_in(&crate::simd::hex::bytes_to_hex_32(&id.0), content);
2641 let (plain, text_spans) = crate::text_spans::extract_own(&named);
2644 let content = plain.as_str();
2645 let emoji_owned = crate::emoji_packs::resolve_outbound_emoji_tags(content);
2646 let emoji_pairs: Vec<(&str, &str)> = emoji_owned.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
2647 extra_tags.extend(crate::text_spans::to_nostr_tags(&text_spans).chain(crate::community::mentions::to_tags(&role_mentions)));
2648 if let Some(bot) = opts.bot.as_deref().filter(|b| !b.is_empty()) {
2649 let pk = nostr_sdk::prelude::PublicKey::parse(bot).map_err(|_| VectorError::Other(format!("{bot} isn't an npub or hex pubkey")))?;
2650 extra_tags.push(crate::bot_interface::bot_tag(&pk));
2651 }
2652 if let Some(secs) = opts.expires_in_secs.filter(|s| *s > 0) {
2653 let at = crate::clock::now_secs().saturating_add(secs);
2654 extra_tags.push(nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(at)));
2655 }
2656 crate::community::v2::service::send_chat_message(&transport, &community, &ch, content, reply_ref, &emoji_pairs, extra_tags)
2657 .await
2658 .map_err(VectorError::Other)
2659 }
2660
2661 pub async fn send_community_file(&self, channel_id: &str, file_path: &str) -> Result<String> {
2665 self.post_community_file(channel_id, file_path, &PostOptions::default().compress(false)).await
2666 }
2667
2668 pub async fn post_community_file(&self, channel_id: &str, file_path: &str, opts: &PostOptions) -> Result<String> {
2670 let path = std::path::Path::new(file_path);
2671 let bytes = std::fs::read(path).map_err(VectorError::Io)?;
2672 let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("file").to_string();
2673 self.post_community_bytes(channel_id, bytes, &filename, opts).await
2674 }
2675
2676 pub async fn post_community_bytes(&self, channel_id: &str, bytes: Vec<u8>, filename: &str, opts: &PostOptions) -> Result<String> {
2679 crate::db::scoped(async move {
2680 use crate::community::attachments;
2681 if bytes.is_empty() {
2682 return Err(VectorError::Other("Empty file".into()));
2683 }
2684 let (bytes, filename) = ready_to_send(bytes, filename, opts.compress).await?;
2685 let filename = filename.as_str();
2686 let extension = std::path::Path::new(filename).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
2687
2688 let id = self
2691 .v2_community_for_channel(channel_id)?
2692 .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2693 let community = crate::db::community::load_community_v2(&id)
2694 .map_err(VectorError::Other)?
2695 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2696 if community.dissolved {
2697 return Err(VectorError::Other("this community has been dissolved".into()));
2698 }
2699 let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
2700
2701 let file_hash = crate::crypto::sha256_hex(&bytes);
2702 let mime = crate::crypto::mime_from_extension(&extension);
2703 let img_meta = crate::crypto::generate_image_metadata(&bytes);
2704
2705 let params = crate::crypto::generate_encryption_params();
2707 let encrypted = crate::crypto::encrypt_data(&bytes, ¶ms)?;
2708 let encrypted_size = encrypted.len() as u64;
2709
2710 let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
2711 let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
2712 let servers = crate::blossom_servers::compute_enabled_servers();
2713 if servers.is_empty() {
2714 return Err(VectorError::Other("No Blossom servers configured".into()));
2715 }
2716 let noop_progress: crate::blossom::ProgressCallback = std::sync::Arc::new(|_, _| Ok(()));
2717 let accepted = crate::blossom::upload_blob_with_progress_and_failover(
2718 signer.clone(),
2719 servers,
2720 std::sync::Arc::new(encrypted),
2721 Some(mime),
2722 true,
2723 noop_progress,
2724 Some(3),
2725 Some(std::time::Duration::from_secs(2)),
2726 None,
2727 ).await.map_err(VectorError::Other)?;
2728 let url = accepted.url;
2730
2731 let attachment = crate::types::Attachment {
2732 id: file_hash.clone(),
2733 key: params.key.clone(),
2734 nonce: params.nonce.clone(),
2735 extension: extension.clone(),
2736 name: filename.to_string(),
2737 url,
2738 path: String::new(),
2740 size: encrypted_size,
2741 img_meta,
2742 downloading: false,
2743 downloaded: false,
2744 verified: true,
2745 webxdc_topic: extension
2747 .eq_ignore_ascii_case("xdc")
2748 .then(|| crate::webxdc::mint_topic_id(&file_hash, &author_pk.to_hex())),
2749 ..Default::default()
2750 };
2751 let imeta = vec![attachments::attachment_to_imeta(&attachment)];
2753 let caption = opts.caption.clone().unwrap_or_default();
2754 self.post_community(channel_id, &caption, imeta, opts, std::time::Duration::from_secs(30)).await
2755 })
2756 .await
2757 }
2758
2759 pub async fn send_community_typing(&self, channel_id: &str) -> Result<()> {
2761 use crate::community::transport::LiveTransport;
2762 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2763 let community = crate::db::community::load_community_v2(&id)
2764 .map_err(VectorError::Other)?
2765 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2766 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2767 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(8));
2768 crate::community::v2::service::send_typing(&transport, &community, &ch)
2769 .await
2770 .map_err(VectorError::Other)
2771 }
2772
2773 pub async fn send_community_reaction(
2776 &self,
2777 channel_id: &str,
2778 message_id: &str,
2779 emoji: &str,
2780 emoji_url: Option<&str>,
2781 ) -> Result<()> {
2782 crate::db::scoped(async move {
2783 if Self::own_reaction_id(message_id, emoji).await.is_some() {
2785 return Ok(());
2786 }
2787 let emoji_tags: Vec<crate::types::EmojiTag> = match emoji_url {
2788 Some(url) if emoji.starts_with(':') && emoji.ends_with(':') && emoji.len() >= 3 && !url.is_empty() => {
2789 vec![crate::types::EmojiTag { shortcode: emoji[1..emoji.len() - 1].to_string(), url: url.to_string() }]
2790 }
2791 _ => Vec::new(),
2792 };
2793 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2794 let community = crate::db::community::load_community_v2(&id)
2795 .map_err(VectorError::Other)?
2796 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2797 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2798 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2799 let held = {
2804 let st = state::STATE.lock().await;
2805 st.find_message(message_id)
2806 .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
2807 };
2808 let held = held.or_else(|| {
2809 crate::db::events::event_author(message_id)
2810 .ok()
2811 .flatten()
2812 .and_then(|n| nostr_sdk::prelude::PublicKey::parse(&n).ok())
2813 });
2814 let target_author = match held {
2815 Some(pk) => pk,
2816 None => crate::community::v2::service::fetch_channel(&transport, &community, &ch, 500)
2817 .await
2818 .map_err(VectorError::Other)?
2819 .iter()
2820 .find(|f| f.event.opened().rumor_id.to_hex() == message_id)
2821 .map(|f| f.event.opened().author)
2822 .ok_or_else(|| VectorError::Other("reacted-to message not found".into()))?,
2823 };
2824 let pair = emoji_tags.first().map(|t| (t.shortcode.as_str(), t.url.as_str()));
2826 crate::community::v2::service::send_reaction(
2831 &transport, &community, &ch, message_id, &target_author.to_hex(), crate::community::v2::kind::MESSAGE, emoji, pair,
2832 )
2833 .await
2834 .map(|_| ())
2835 .map_err(VectorError::Other)
2836 })
2837 .await
2838 }
2839
2840 pub async fn edit_community_message(&self, channel_id: &str, message_id: &str, new_content: &str) -> Result<()> {
2842 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2843 let (named, _) = crate::community::mentions::resolve_in(&crate::simd::hex::bytes_to_hex_32(&id.0), new_content);
2845 let (plain, text_spans) = crate::text_spans::extract_own(&named);
2846 let new_content = plain.as_str();
2847 let span_tags: Vec<nostr_sdk::prelude::Tag> = crate::text_spans::to_nostr_tags(&text_spans).collect();
2848 let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
2849 let community = crate::db::community::load_community_v2(&id)
2850 .map_err(VectorError::Other)?
2851 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2852 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2853 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2854 let emoji_pairs: Vec<(&str, &str)> = emoji_tags.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
2855 crate::community::v2::service::send_edit_tagged(&transport, &community, &ch, message_id, new_content, &emoji_pairs, span_tags)
2856 .await
2857 .map(|_| ())
2858 .map_err(VectorError::Other)
2859 }
2860
2861 pub async fn delete_community_message(&self, message_id: &str) -> Result<()> {
2865 let channel_id = self.message_chat(message_id).await?;
2866 self.delete_community_message_in(&channel_id, message_id).await
2867 }
2868
2869 pub async fn message_chat(&self, message_id: &str) -> Result<String> {
2872 if let Some((_, chat)) = state::STATE.lock().await.find_chat_for_message(message_id) {
2873 return Ok(chat);
2874 }
2875 crate::db::events::locate_message(message_id)
2876 .map_err(VectorError::Other)?
2877 .chat
2878 .ok_or_else(|| VectorError::Other("message not found (already deleted?)".into()))
2879 }
2880
2881 pub async fn delete_community_message_in(&self, channel_id: &str, message_id: &str) -> Result<()> {
2885 use crate::community::transport::LiveTransport;
2886 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2887
2888 let attachment_urls: Vec<String> = self
2891 .get_message(message_id)
2892 .await
2893 .map(|(_, msg)| msg.attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect())
2894 .unwrap_or_default();
2895 let attachment_urls =
2897 crate::db::attachments::urls_unreferenced_elsewhere(&attachment_urls, message_id).unwrap_or_default();
2898
2899 let id = self
2900 .v2_community_for_channel(channel_id)?
2901 .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2902 let community = crate::db::community::load_community_v2(&id)
2903 .map_err(VectorError::Other)?
2904 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2905 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2906 crate::community::v2::service::delete_own(&transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE)
2907 .await
2908 .map_err(VectorError::Other)?;
2909 if !attachment_urls.is_empty() {
2911 if let Some(_client) = state::nostr_client() {
2912 if let Ok(signer) = crate::signer::active_signer() {
2913 crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
2914 }
2915 }
2916 }
2917 let removed_chat = {
2918 let mut st = state::STATE.lock().await;
2919 st.remove_message(message_id).map(|(cid, _)| cid)
2920 };
2921 let _ = crate::db::events::delete_event(message_id).await;
2922 traits::emit_event_json("message_removed", serde_json::json!({
2923 "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "deleted",
2924 }));
2925 Ok(())
2926 }
2927
2928 pub async fn hide_community_message(&self, channel_id: &str, message_id: &str) -> Result<()> {
2933 use crate::community::transport::LiveTransport;
2934 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2935
2936 let author_npub = {
2939 let st = state::STATE.lock().await;
2940 st.find_message(message_id).and_then(|(_, m)| m.npub)
2941 };
2942 let author_npub = match author_npub {
2943 Some(n) => n,
2944 None => crate::db::events::event_author(message_id)
2945 .ok()
2946 .flatten()
2947 .ok_or_else(|| VectorError::Other("can't resolve the target message's author".into()))?,
2948 };
2949 let author = nostr_sdk::prelude::PublicKey::parse(&author_npub)
2950 .map_err(|_| VectorError::Other("target message has an unreadable author".into()))?;
2951
2952 let id = self
2953 .v2_community_for_channel(channel_id)?
2954 .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2955 let community = crate::db::community::load_community_v2(&id)
2956 .map_err(VectorError::Other)?
2957 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
2958 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
2959 crate::community::v2::service::moderation_delete(
2960 &transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE, &author,
2961 )
2962 .await
2963 .map_err(VectorError::Other)?;
2964
2965 let removed_chat = {
2966 let mut st = state::STATE.lock().await;
2967 st.remove_message(message_id).map(|(cid, _)| cid)
2968 };
2969 let _ = crate::db::events::delete_event(message_id).await;
2970 traits::emit_event_json("message_removed", serde_json::json!({
2971 "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "hidden",
2972 }));
2973 Ok(())
2974 }
2975
2976 pub async fn sync_community_channel(&self, channel_id: &str, limit: usize) -> Result<(usize, Vec<String>)> {
2981 self.sync_community_channel_before(channel_id, limit, None).await
2982 }
2983
2984 pub async fn sync_community_channel_page(
2987 &self,
2988 channel_id: &str,
2989 limit: usize,
2990 before_secs: Option<u64>,
2991 since_secs: Option<u64>,
2992 ) -> Result<(BackfillCount, Vec<String>)> {
2993 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
2994 let warnings = if community::v2::realtime::follow_worker_running() {
2995 community::v2::realtime::enqueue_follow(&id);
2996 Vec::new()
2997 } else {
2998 Self::v2_inline_follow(&id).await
2999 };
3000 let count = Self::v2_backfill_channel_counted(
3001 &id, channel_id, limit, 8, since_secs, before_secs,
3002 crate::community::transport::Evidence::Fast, 12,
3003 ).await;
3004 Ok((count, warnings))
3005 }
3006
3007 pub async fn fill_community_gap(&self, channel_id: &str, before_ms: u64) -> Result<usize> {
3011 let Some(gap) = history_gaps::gap_at(channel_id, before_ms / 1000) else {
3012 return Ok(0);
3013 };
3014 let before = gap.hi + 1;
3016 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
3017 let count = Self::v2_backfill_channel_counted(
3018 &id, channel_id, 50, 2, None, Some(before),
3019 crate::community::transport::Evidence::Fast, 12,
3020 ).await;
3021 if count.next_before.is_some_and(|n| n >= before) {
3024 history_gaps::abandon(channel_id, before);
3025 }
3026 Ok(count.new_messages)
3027 }
3028
3029 pub async fn sync_community_channel_before(
3038 &self,
3039 channel_id: &str,
3040 limit: usize,
3041 before_secs: Option<u64>,
3042 ) -> Result<(usize, Vec<String>)> {
3043 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
3048 let warnings = if community::v2::realtime::follow_worker_running() {
3049 community::v2::realtime::enqueue_follow(&id);
3050 Vec::new()
3051 } else {
3052 Self::v2_inline_follow(&id).await
3053 };
3054 let new = Self::v2_backfill_channel(
3059 &id, channel_id, limit, 8, None, before_secs,
3060 crate::community::transport::Evidence::Fast, 12,
3061 ).await;
3062 Ok((new, warnings))
3063 }
3064
3065 pub async fn sync_channel_events(
3080 &self,
3081 channel_id: &str,
3082 max_events: usize,
3083 until_s: Option<u64>,
3084 since_s: Option<u64>,
3085 ) -> Result<usize> {
3086 let max = max_events.clamp(1, 500);
3087 let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
3088 let community = crate::db::community::load_community_v2(&id)
3089 .map_err(VectorError::Other)?
3090 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
3091 if community.dissolved {
3092 return Err(VectorError::Other("this community has been dissolved".into()));
3093 }
3094 let ch_id = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
3095 let ch = community
3096 .channel(&ch_id)
3097 .ok_or_else(|| VectorError::Other("no such channel in this community".into()))?;
3098 if ch.private && ch.key.is_none() {
3101 return Err(VectorError::Other(
3102 "this private channel has no key yet (awaiting rekey delivery)".into(),
3103 ));
3104 }
3105 let new = Self::v2_backfill_channel(
3106 &id, channel_id, max, 1, since_s, until_s,
3107 crate::community::transport::Evidence::Fast, 12,
3108 )
3109 .await;
3110 Ok(new)
3111 }
3112
3113 pub async fn get_chat_commands(&self, chat_id: &str) -> crate::bot_interface::ChatCommandsSnapshot {
3125 use crate::bot_interface::{self, ChatCommandsSnapshot};
3126 use nostr_sdk::prelude::ToBech32;
3127
3128 let mut bots: Vec<nostr_sdk::prelude::PublicKey> = Vec::new();
3129 let mut relays: Vec<String> = Vec::new();
3130 let community_hex = crate::db::community::community_id_for_channel(chat_id).ok().flatten();
3131 if let Some(cid_hex) = community_hex {
3132 let Ok(Some(community)) = Self::load_held(&cid_hex) else {
3133 return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
3134 };
3135 let members = community::v2::service::stored_memberlist(&community).unwrap_or_default();
3136 relays = community.relays.clone();
3137 let state = crate::state::STATE.lock().await;
3138 for pk in members {
3139 let Ok(npub) = pk.to_bech32();
3140 if state.get_profile(&npub).map(|p| p.flags.is_bot()).unwrap_or(false) {
3141 bots.push(pk);
3142 }
3143 }
3144 } else if chat_id.starts_with("npub1") {
3145 if let Ok(pk) = nostr_sdk::prelude::PublicKey::parse(chat_id) {
3146 let is_bot = {
3147 let state = crate::state::STATE.lock().await;
3148 state.get_profile(chat_id).map(|p| p.flags.is_bot()).unwrap_or(false)
3149 };
3150 if is_bot {
3151 bots.push(pk);
3152 if let Some(client) = crate::state::nostr_client() {
3155 relays = client.relays().await.keys().map(|u| u.to_string()).collect();
3156 }
3157 }
3158 }
3159 }
3160
3161 if bots.is_empty() {
3162 return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
3163 }
3164 relays.extend(bot_interface::DISCOVERY_RELAYS.iter().map(|s| s.to_string()));
3167 relays.sort();
3168 relays.dedup();
3169 bots.sort_by_key(|p| p.to_hex());
3172 let bot_hexes: Vec<String> = bots.iter().map(|p| p.to_hex()).collect();
3173 let commands = bot_interface::assemble_from_store(&bot_hexes);
3174 let fresh = bot_interface::commands_fresh(chat_id, &bot_hexes);
3175 if !fresh {
3176 bot_interface::spawn_commands_refresh(chat_id.to_string(), bots.clone(), relays);
3177 }
3178 ChatCommandsSnapshot { bots: bots.len(), commands, fresh }
3179 }
3180
3181 pub async fn get_community_members(&self, community_id: &str) -> Vec<serde_json::Value> {
3187 use nostr_sdk::prelude::ToBech32;
3188 let Ok(Some(community)) = Self::load_held(community_id) else { return Vec::new() };
3194 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3195 let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
3196 if cursor == 0 {
3197 if crate::community::v2::realtime::follow_worker_running() {
3198 crate::community::v2::realtime::enqueue_follow(community.id());
3199 } else {
3200 let c2 = community.clone();
3201 db::spawn_bound(async move {
3202 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
3203 if matches!(crate::community::v2::service::sync_guestbook(&transport, &c2).await, Ok(fresh) if !fresh.is_empty()) {
3204 emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
3205 }
3206 });
3207 }
3208 }
3209 let parts = crate::community::v2::service::stored_member_parts(&community, &events).unwrap_or_default();
3210 let counted = parts.counted.into_iter().filter_map(|pk| pk.to_bech32().ok()).map(|npub| serde_json::json!({ "npub": npub }));
3211 let unlisted = parts
3212 .unlisted
3213 .into_iter()
3214 .filter_map(|(pk, why)| pk.to_bech32().ok().map(|npub| serde_json::json!({ "npub": npub, "unlisted": why })));
3215 counted.chain(unlisted).collect()
3216 }
3217
3218 pub fn get_community_banned(&self, community_id: &str) -> Vec<String> {
3228 use nostr_sdk::prelude::{PublicKey, ToBech32};
3229 let cid_hex = match Self::load_held(community_id) {
3232 Ok(Some(c)) => crate::simd::hex::bytes_to_hex_32(&c.id().0),
3233 _ => community_id.to_string(),
3234 };
3235 crate::db::community::get_community_banlist(&cid_hex)
3236 .unwrap_or_default()
3237 .iter()
3238 .filter_map(|hex| PublicKey::parse(hex).ok())
3239 .filter_map(|pk| pk.to_bech32().ok())
3240 .collect()
3241 }
3242
3243 pub fn community_moderation_intel(&self, community_id: &str) -> Result<serde_json::Value> {
3250 let community = Self::load_held(community_id)?
3251 .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
3252 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3253 let report = Self::policy_console_report(&cid_hex, &community)?;
3254 let invites = crate::db::community::list_public_invites(&cid_hex).unwrap_or_default();
3255 let banlist = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
3256 let caps = self.community_capabilities(community_id).unwrap_or_else(|_| serde_json::json!({}));
3257 let owner_b32 = community.owner().map_err(VectorError::Other)?.to_bech32().unwrap_or_default();
3258 let unlisted: Vec<String> = crate::db::community::get_guestbook_shared(&cid_hex)
3260 .ok()
3261 .and_then(|(events, _)| crate::community::v2::service::stored_member_parts(&community, &events).ok())
3262 .map(|p| p.unlisted.into_keys().filter_map(|pk| pk.to_bech32().ok()).collect())
3263 .unwrap_or_default();
3264
3265 Ok(serde_json::json!({
3266 "community_id": cid_hex,
3267 "name": community.name,
3268 "owner_npub": owner_b32,
3269 "epoch": community.root_epoch.0,
3270 "report": &*report,
3271 "unlisted": unlisted,
3272 "invites": invites.iter().map(|i| serde_json::json!({
3273 "token": i.token,
3274 "label": i.label,
3275 "created_at": i.created_at,
3276 "expires_at": i.expires_at,
3277 "join_count": i.join_count,
3278 })).collect::<Vec<_>>(),
3279 "banlist_count": banlist.len(),
3280 "banlist_max": crate::community::v2::roles::MAX_BANLIST,
3281 "capabilities": caps,
3282 "channels": community.channels.iter().map(|c| serde_json::json!({
3285 "id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
3286 "name": c.name,
3287 })).collect::<Vec<_>>(),
3288 }))
3289 }
3290
3291 pub fn screen_community_message(
3300 &self,
3301 channel_id: &str,
3302 author_npub: &str,
3303 text: &str,
3304 ) -> Result<serde_json::Value> {
3305 use nostr_sdk::prelude::PublicKey;
3306 let Some(id) = self.v2_community_for_channel(channel_id)? else {
3307 return Ok(serde_json::json!({ "findings": [] }));
3308 };
3309 let community = crate::db::community::load_community_v2(&id)
3310 .map_err(VectorError::Other)?
3311 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
3312 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3313 let owner = community.owner().map_err(VectorError::Other)?;
3314 let author = PublicKey::parse(author_npub).map_err(|_| VectorError::Other("unreadable author".into()))?;
3315
3316 use crate::community::roles::Permissions;
3319 const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3320 | Permissions::MANAGE_CHANNELS
3321 | Permissions::MANAGE_METADATA
3322 | Permissions::KICK
3323 | Permissions::BAN
3324 | Permissions::MANAGE_MESSAGES;
3325 let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3326 let hex = author.to_hex();
3327 let roles: Vec<String> =
3328 roster.grants.iter().find(|g| g.member == hex).map(|g| g.role_ids.clone()).unwrap_or_default();
3329 let is_staff = roles
3330 .iter()
3331 .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0));
3332
3333 let now_ms = crate::clock::now_ms();
3334 let findings = crate::community::policy::harness::screen_message(
3335 &cid_hex, &owner, &author, &roles, is_staff, channel_id, text, now_ms,
3336 );
3337 Ok(serde_json::json!({ "findings": findings }))
3338 }
3339
3340 pub fn check_community_raid(&self, community_id: &str) -> Result<serde_json::Value> {
3344 let Some(community) = Self::load_held(community_id)? else {
3345 return Ok(serde_json::json!({ "detected": false }));
3346 };
3347 let caps = self.community_capabilities(community_id)?;
3351 if caps["ban"].as_bool() != Some(true) {
3352 return Ok(serde_json::json!({ "detected": false }));
3353 }
3354 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3355 let report = Self::policy_console_report(&cid_hex, &community)?;
3356 let biggest = report["cohorts"].get(0);
3357 Ok(serde_json::json!({
3358 "detected": report["raid_detected"].as_bool().unwrap_or(false),
3359 "suspects": report["suspects"].as_u64().unwrap_or(0),
3360 "cohort": biggest.and_then(|c| c["size"].as_u64()).unwrap_or(0),
3361 "sample": biggest
3362 .and_then(|c| c["sample"].as_str())
3363 .map(|s| s.chars().take(60).collect::<String>())
3364 .unwrap_or_default(),
3365 }))
3366 }
3367
3368 fn raid_report(cid_hex: &str) -> Result<std::sync::Arc<crate::community::raid::RaidReport>> {
3372 use crate::community::raid;
3373 use crate::community::v2::guestbook::GuestbookEntry;
3374 use nostr_sdk::prelude::PublicKey;
3375 use std::collections::{HashMap, HashSet};
3376
3377 let now_secs = crate::clock::now_secs();
3378 if let Some(report) = report_get(&raid_report_cache(), cid_hex, now_secs) {
3379 return Ok(report);
3380 }
3381 let community = crate::db::community::load_community_v2(&crate::community::CommunityId(
3382 crate::simd::hex::hex_to_bytes_32(cid_hex),
3383 ))
3384 .map_err(VectorError::Other)?
3385 .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
3386 let owner_b32 = community.owner().map_err(VectorError::Other)?.to_bech32().unwrap_or_default();
3387 let me_b32 = state::my_public_key().and_then(|p| p.to_bech32().ok()).unwrap_or_default();
3388
3389 let roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
3391 let staff: HashSet<String> = roster
3392 .grants
3393 .iter()
3394 .filter(|g| !g.role_ids.is_empty())
3395 .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
3396 .collect();
3397
3398 let members: Vec<String> = crate::community::v2::service::stored_memberlist(&community)
3400 .unwrap_or_default()
3401 .into_iter()
3402 .filter_map(|pk| pk.to_bech32().ok())
3403 .collect();
3404
3405 let (events, _cursor) = crate::db::community::get_guestbook(cid_hex).unwrap_or_default();
3407 let mut joined_at: HashMap<String, u64> = HashMap::new();
3408 let mut invite_label: HashMap<String, String> = HashMap::new();
3409 for e in &events {
3410 let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
3411 let Ok(b32) = member.to_bech32();
3412 let slot = joined_at.entry(b32.clone()).or_insert(*at_ms);
3414 *slot = (*slot).min(*at_ms);
3415 if let Some((_creator, label)) = invited_by {
3416 invite_label.entry(b32).or_insert_with(|| label.clone());
3417 }
3418 }
3419
3420 let footprints: HashMap<String, crate::db::community::AuthorFootprint> =
3421 crate::db::community::community_author_footprints(cid_hex)
3422 .unwrap_or_default()
3423 .into_iter()
3424 .map(|f| (f.npub.clone(), f))
3425 .collect();
3426
3427 const TEXT_WINDOW: usize = 4_000;
3430 let mut texts: HashMap<String, (Vec<String>, Vec<u64>)> = HashMap::new();
3431 for (npub, at, text) in crate::db::community::community_recent_texts(cid_hex, TEXT_WINDOW).unwrap_or_default() {
3432 let slot = texts.entry(npub).or_default();
3433 slot.0.push(text);
3434 slot.1.push(at);
3435 }
3436
3437 let signals: Vec<raid::MemberSignals> = members
3438 .iter()
3439 .map(|npub| {
3440 let f = footprints.get(npub);
3441 raid::MemberSignals {
3442 npub: npub.clone(),
3443 joined_at_ms: joined_at.get(npub).copied().unwrap_or(0),
3444 invite_label: invite_label.get(npub).cloned(),
3445 messages: f.map(|f| f.messages).unwrap_or(0),
3446 first_secs: f.map(|f| f.first_secs).unwrap_or(0),
3447 last_secs: f.map(|f| f.last_secs).unwrap_or(0),
3448 texts: texts.get(npub).map(|t| t.0.clone()).unwrap_or_default(),
3449 text_secs: texts.get(npub).map(|t| t.1.clone()).unwrap_or_default(),
3450 is_owner: *npub == owner_b32,
3451 is_admin: staff.contains(npub),
3452 is_me: *npub == me_b32,
3453 }
3454 })
3455 .collect();
3456
3457 let params = raid::RaidParams {
3458 known_shortcodes: crate::emoji_packs::known_shortcodes(),
3459 ..Default::default()
3460 };
3461 let report = std::sync::Arc::new(raid::assess(&signals, now_secs, ¶ms));
3462 report_put(&raid_report_cache(), cid_hex, now_secs, report.clone());
3463 Ok(report)
3464 }
3465
3466 pub fn policy_presets(&self) -> Result<serde_json::Value> {
3468 let presets: Vec<serde_json::Value> = crate::community::policy::presets::all()
3469 .into_iter()
3470 .map(|p| {
3471 serde_json::json!({
3472 "id": p.id,
3473 "name": p.name,
3474 "description": p.description,
3475 "example": p.example,
3476 "caveat": p.caveat,
3477 "dials": p.dials,
3478 "rules": crate::community::policy::presets::describe(&p.policy),
3482 "bytes": serde_json::to_string(&p.policy).unwrap_or_default(),
3483 })
3484 })
3485 .collect();
3486 let rule_kinds: Vec<serde_json::Value> = crate::community::policy::presets::rule_kinds()
3490 .into_iter()
3491 .map(|k| {
3492 serde_json::json!({
3493 "id": k.id,
3494 "label": k.label,
3495 "description": k.description,
3496 "input": k.input,
3497 "input_label": k.input_label,
3498 "input_hint": k.input_hint,
3499 "rule": k.rule,
3500 })
3501 })
3502 .collect();
3503 Ok(serde_json::json!({ "presets": presets, "rule_kinds": rule_kinds }))
3504 }
3505
3506 pub fn preview_community_policy(&self, community_id: &str, bytes: &str) -> Result<serde_json::Value> {
3510 use crate::community::v2::guestbook::GuestbookEntry;
3511 let community = Self::load_held(community_id)?
3512 .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3513 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3514 let owner = community.owner().map_err(VectorError::Other)?;
3515 let me = state::my_public_key();
3516
3517 use crate::community::roles::Permissions;
3518 const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3519 | Permissions::MANAGE_CHANNELS
3520 | Permissions::MANAGE_METADATA
3521 | Permissions::KICK
3522 | Permissions::BAN
3523 | Permissions::MANAGE_MESSAGES;
3524 let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3525 let staff: std::collections::HashSet<String> = roster
3526 .grants
3527 .iter()
3528 .filter(|g| {
3529 g.role_ids
3530 .iter()
3531 .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0))
3532 })
3533 .map(|g| g.member.clone())
3534 .collect();
3535 let roles_of: std::collections::HashMap<String, Vec<String>> =
3536 roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
3537
3538 let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
3539 let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
3540 let mut invite_label: std::collections::HashMap<String, String> = std::collections::HashMap::new();
3541 for e in events.iter() {
3542 let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
3543 let hex = member.to_hex();
3544 let slot = joined_at.entry(hex.clone()).or_insert(*at_ms);
3545 *slot = (*slot).min(*at_ms);
3546 if let Some((_c, label)) = invited_by {
3547 invite_label.entry(hex).or_insert_with(|| label.clone());
3548 }
3549 }
3550 let members: Vec<crate::community::policy::harness::MemberRow> =
3551 crate::community::v2::service::stored_memberlist(&community)
3552 .unwrap_or_default()
3553 .into_iter()
3554 .map(|pk| {
3555 let hex = pk.to_hex();
3556 (
3557 pk,
3558 joined_at.get(&hex).copied(),
3559 staff.contains(&hex),
3560 roles_of.get(&hex).cloned().unwrap_or_default(),
3561 invite_label.get(&hex).cloned(),
3562 )
3563 })
3564 .collect();
3565
3566 let now_ms = crate::clock::now_ms();
3567 let assembled =
3568 crate::community::policy::harness::assemble(&cid_hex, &owner, me.as_ref(), &members, now_ms)
3569 .map_err(VectorError::Other)?;
3570 let preview = crate::community::policy::harness::preview_policy(&assembled, bytes, now_ms);
3571 serde_json::to_value(preview).map_err(|e| VectorError::Other(e.to_string()))
3572 }
3573
3574 pub fn list_community_policies(&self, community_id: &str) -> Result<serde_json::Value> {
3577 let community = Self::load_held(community_id)?
3578 .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3579 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3580 let stored = crate::db::community::get_community_policies(&cid_hex).map_err(VectorError::Other)?;
3581 let rows: Vec<serde_json::Value> = stored
3582 .iter()
3583 .map(|p| {
3584 let verdict = serde_json::from_str::<crate::community::policy::document::Policy>(&p.bytes)
3588 .map_err(|e| e.to_string())
3589 .and_then(|doc| doc.validate().map_err(|r| format!("{r:?}")));
3590 serde_json::json!({
3591 "policy_id": p.policy_id,
3592 "hash": p.hash,
3593 "enabled": p.enabled,
3594 "updated_at": p.updated_at,
3595 "bytes": p.bytes,
3596 "valid": verdict.is_ok(),
3597 "error": verdict.err(),
3598 })
3599 })
3600 .collect();
3601 Ok(serde_json::json!({
3602 "community_id": cid_hex,
3603 "policies": rows,
3604 "using_builtin": !stored
3609 .iter()
3610 .any(|p| p.policy_id == crate::community::policy::harness::DEFAULTS_POLICY_ID),
3611 }))
3612 }
3613
3614 pub fn set_community_policy(&self, community_id: &str, policy_id: &str, bytes: &str, enabled: bool) -> Result<serde_json::Value> {
3617 let community = Self::load_held(community_id)?
3618 .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3619 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3620 if bytes.len() > crate::community::policy::types::caps::MAX_POLICY_BYTES {
3621 return Err(VectorError::Other("policy exceeds the maximum document size".into()));
3622 }
3623 let doc: crate::community::policy::document::Policy =
3624 serde_json::from_str(bytes).map_err(|e| VectorError::Other(format!("policy is not valid JSON: {e}")))?;
3625 doc.validate().map_err(|r| VectorError::Other(format!("policy rejected: {r:?}")))?;
3626
3627 let hash = crate::community::policy::harness::hash_policy_bytes(bytes.as_bytes());
3628 let hash_hex = crate::simd::hex::bytes_to_hex_32(&hash.0);
3629 let now_secs = crate::clock::now_secs();
3630 crate::db::community::set_community_policy(&cid_hex, policy_id, bytes, &hash_hex, enabled, now_secs)
3631 .map_err(VectorError::Other)?;
3632 Self::invalidate_raid_report(&cid_hex);
3635 Ok(serde_json::json!({ "policy_id": policy_id, "hash": hash_hex, "enabled": enabled }))
3636 }
3637
3638 pub fn delete_community_policy(&self, community_id: &str, policy_id: &str) -> Result<()> {
3639 let community = Self::load_held(community_id)?
3640 .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
3641 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3642 crate::db::community::delete_community_policy(&cid_hex, policy_id).map_err(VectorError::Other)?;
3643 Self::invalidate_raid_report(&cid_hex);
3644 Ok(())
3645 }
3646
3647 pub fn builtin_policy_json(&self) -> Result<String> {
3650 serde_json::to_string_pretty(&crate::community::policy::harness::default_policy())
3651 .map_err(|e| VectorError::Other(e.to_string()))
3652 }
3653
3654 fn policy_console_report(cid_hex: &str, community: &crate::community::v2::community::CommunityV2) -> Result<std::sync::Arc<serde_json::Value>> {
3662 let now_secs = crate::clock::now_secs();
3663 report_once(&policy_report_cache(), &policy_report_gate(), cid_hex, now_secs, || {
3664 Self::evaluate_policy_console(cid_hex, community, now_secs)
3665 })
3666 }
3667
3668 fn evaluate_policy_console(
3669 cid_hex: &str,
3670 community: &crate::community::v2::community::CommunityV2,
3671 now_secs: u64,
3672 ) -> Result<std::sync::Arc<serde_json::Value>> {
3673 use crate::community::v2::guestbook::GuestbookEntry;
3674 let owner = community.owner().map_err(VectorError::Other)?;
3675 let me = state::my_public_key();
3676
3677 use crate::community::roles::Permissions;
3681 const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3682 | Permissions::MANAGE_CHANNELS
3683 | Permissions::MANAGE_METADATA
3684 | Permissions::KICK
3685 | Permissions::BAN
3686 | Permissions::MANAGE_MESSAGES;
3687 let roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
3688 let staff: std::collections::HashSet<String> = roster
3689 .grants
3690 .iter()
3691 .filter(|g| {
3692 g.role_ids
3693 .iter()
3694 .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0))
3695 })
3696 .map(|g| g.member.clone())
3697 .collect();
3698 let roles_of: std::collections::HashMap<String, Vec<String>> =
3699 roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
3700
3701 let (events, _cursor) = crate::db::community::get_guestbook(cid_hex).unwrap_or_default();
3702 let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
3703 let mut invite_label: std::collections::HashMap<String, String> = std::collections::HashMap::new();
3704 for e in &events {
3705 let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
3706 let hex = member.to_hex();
3707 let slot = joined_at.entry(hex.clone()).or_insert(*at_ms);
3709 *slot = (*slot).min(*at_ms);
3710 if let Some((_creator, label)) = invited_by {
3711 invite_label.entry(hex).or_insert_with(|| label.clone());
3712 }
3713 }
3714
3715 let members: Vec<crate::community::policy::harness::MemberRow> =
3716 crate::community::v2::service::stored_memberlist(community)
3717 .unwrap_or_default()
3718 .into_iter()
3719 .map(|pk| {
3720 let hex = pk.to_hex();
3721 (
3722 pk,
3723 joined_at.get(&hex).copied(),
3724 staff.contains(&hex),
3725 roles_of.get(&hex).cloned().unwrap_or_default(),
3726 invite_label.get(&hex).cloned(),
3727 )
3728 })
3729 .collect();
3730
3731 let now_ms = now_secs.saturating_mul(1000);
3732 let assembled =
3733 crate::community::policy::harness::assemble(cid_hex, &owner, me.as_ref(), &members, now_ms)
3734 .map_err(VectorError::Other)?;
3735 Ok(std::sync::Arc::new(
3736 crate::community::policy::harness::evaluate_for_console(cid_hex, &assembled, now_ms)
3737 .map_err(VectorError::Other)?,
3738 ))
3739 }
3740
3741 pub fn policy_side_by_side(&self, community_id: &str) -> Result<serde_json::Value> {
3745 use crate::community::v2::guestbook::GuestbookEntry;
3746 use nostr_sdk::prelude::PublicKey;
3747 let community = Self::load_held(community_id)?
3748 .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
3749 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3750 let owner = community.owner().map_err(VectorError::Other)?;
3751
3752 use crate::community::roles::Permissions;
3755 const MOD_MASK: u64 = Permissions::MANAGE_ROLES
3756 | Permissions::MANAGE_CHANNELS
3757 | Permissions::MANAGE_METADATA
3758 | Permissions::KICK
3759 | Permissions::BAN
3760 | Permissions::MANAGE_MESSAGES;
3761 let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3762 let staff: std::collections::HashSet<String> = roster
3763 .grants
3764 .iter()
3765 .filter(|g| {
3766 g.role_ids.iter().any(|rid| {
3767 roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0)
3768 })
3769 })
3770 .map(|g| g.member.clone())
3771 .collect();
3772 let roles_of: std::collections::HashMap<String, Vec<String>> =
3773 roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();
3774
3775 let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
3776 let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
3777 for e in events.iter() {
3778 let GuestbookEntry::Join { member, at_ms, .. } = &e.entry else { continue };
3779 let hex = member.to_hex();
3780 let slot = joined_at.entry(hex).or_insert(*at_ms);
3781 *slot = (*slot).min(*at_ms);
3782 }
3783
3784 let members: Vec<(PublicKey, Option<u64>, bool, Vec<String>)> =
3785 crate::community::v2::service::stored_memberlist(&community)
3786 .unwrap_or_default()
3787 .into_iter()
3788 .map(|pk| {
3789 let hex = pk.to_hex();
3790 (pk, joined_at.get(&hex).copied(), staff.contains(&hex), roles_of.get(&hex).cloned().unwrap_or_default())
3791 })
3792 .collect();
3793
3794 let assessments: Vec<(String, String)> = Self::raid_report(&cid_hex)
3796 .map(|r| {
3797 r.members
3798 .iter()
3799 .map(|m| (m.npub.clone(), format!("{:?}", m.verdict).to_lowercase()))
3800 .collect()
3801 })
3802 .unwrap_or_default();
3803
3804 let now_ms = crate::clock::now_ms();
3805 let diff = crate::community::policy::harness::run_side_by_side(
3806 &cid_hex, &owner, &members, &assessments, now_ms,
3807 )
3808 .map_err(VectorError::Other)?;
3809 serde_json::to_value(diff).map_err(|e| VectorError::Other(e.to_string()))
3810 }
3811
3812 pub fn invalidate_raid_report(community_id: &str) {
3816 policy_report_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(community_id);
3817 raid_report_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(community_id);
3818 }
3819
3820 pub async fn refound_community(&self, community_id: &str, retain: &[&str]) -> Result<()> {
3828 let community = Self::load_held(community_id)?
3829 .ok_or_else(|| VectorError::Other("re-founding requires a Concord v2 community".into()))?;
3830 let removed = Self::members_to_remove(&community, retain)?;
3831 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
3832 crate::community::v2::service::refound_community(&transport, &community, &removed)
3833 .await
3834 .map_err(VectorError::Other)?;
3835 Self::invalidate_raid_report(community_id);
3837 Ok(())
3838 }
3839
3840 fn members_to_remove(
3858 community: &crate::community::v2::community::CommunityV2,
3859 retain: &[&str],
3860 ) -> Result<Vec<nostr_sdk::prelude::PublicKey>> {
3861 use nostr_sdk::prelude::PublicKey;
3862 let keep: std::collections::HashSet<PublicKey> =
3863 retain.iter().filter_map(|n| PublicKey::parse(n).ok()).collect();
3864 if keep.is_empty() {
3865 return Ok(Vec::new());
3866 }
3867 let me = state::my_public_key();
3868 let owner = community.owner().ok();
3869 Ok(crate::community::v2::service::stored_memberlist(community)
3870 .map_err(VectorError::Other)?
3871 .into_iter()
3872 .filter(|pk| !keep.contains(pk))
3873 .filter(|pk| Some(*pk) != me && Some(*pk) != owner)
3874 .collect())
3875 }
3876
3877 pub async fn purge_and_refound(
3893 &self,
3894 community_id: &str,
3895 retain: &[&str],
3896 on_progress: &(dyn Fn(usize, usize) + Sync),
3897 ) -> Result<serde_json::Value> {
3898 let community = Self::load_held(community_id)?
3899 .ok_or_else(|| VectorError::Other("re-founding requires a Concord v2 community".into()))?;
3900 let removed = Self::members_to_remove(&community, retain)?;
3901 let keep: Vec<nostr_sdk::prelude::PublicKey> = retain
3906 .iter()
3907 .filter_map(|n| nostr_sdk::prelude::PublicKey::parse(n).ok())
3908 .collect();
3909 log_info!("[Moderation] purge: {} to remove, {} retained", removed.len(), keep.len());
3910 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
3911 if keep.is_empty() {
3922 crate::community::v2::service::refound_community(&transport, &community, &removed)
3923 .await
3924 .map_err(VectorError::Other)?;
3925 } else {
3926 crate::community::v2::service::refound_community_retaining(&transport, &community, &removed, &keep)
3927 .await
3928 .map_err(VectorError::Other)?;
3929 }
3930 let fresh = Self::load_held(community_id)?
3934 .ok_or_else(|| VectorError::Other("community gone during the purge".into()))?;
3935 let sweep = crate::community::v2::service::kick_members(&transport, &fresh, &removed, on_progress)
3936 .await
3937 .map_err(VectorError::Other)?;
3938 let _ = crate::community::v2::service::sync_guestbook(&transport, &fresh).await;
3941 log_info!(
3942 "[Moderation] purge: rotated to epoch {}, kicked {}/{} ({} refused, {} failed)",
3943 fresh.root_epoch.0,
3944 sweep.kicked.len(),
3945 removed.len(),
3946 sweep.refused.len(),
3947 sweep.failed.len()
3948 );
3949 Ok(serde_json::json!({
3950 "kicked": sweep.kicked.len(),
3951 "refused": sweep.refused.len(),
3952 "failed": sweep.failed.len(),
3953 "rotated": true,
3954 }))
3955 }
3956
3957 pub async fn kick_community_members(
3960 &self,
3961 community_id: &str,
3962 npubs: &[&str],
3963 on_progress: &(dyn Fn(usize, usize) + Sync),
3964 ) -> Result<serde_json::Value> {
3965 let community = Self::load_held(community_id)?
3966 .ok_or_else(|| VectorError::Other("kicking requires a Concord v2 community".into()))?;
3967 use nostr_sdk::prelude::PublicKey;
3968 let targets: Vec<PublicKey> = npubs.iter().filter_map(|n| PublicKey::parse(n).ok()).collect();
3969 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
3970 let sweep = crate::community::v2::service::kick_members(&transport, &community, &targets, on_progress)
3971 .await
3972 .map_err(VectorError::Other)?;
3973 let _ = crate::community::v2::service::sync_guestbook(&transport, &community).await;
3974 log_info!(
3975 "[Moderation] kick sweep: {}/{} kicked ({} refused, {} failed)",
3976 sweep.kicked.len(),
3977 targets.len(),
3978 sweep.refused.len(),
3979 sweep.failed.len()
3980 );
3981 Self::invalidate_raid_report(community_id);
3982 Ok(serde_json::json!({
3983 "kicked": sweep.kicked.len(),
3984 "refused": sweep.refused.iter().map(|(_, why)| why.clone()).collect::<Vec<_>>(),
3985 "failed": sweep.failed.len(),
3986 }))
3987 }
3988
3989 pub async fn revoke_all_public_invites(&self, community_id: &str) -> Result<(usize, usize)> {
3994 let tokens: Vec<String> = crate::db::community::list_public_invites(community_id)
3995 .map_err(VectorError::Other)?
3996 .into_iter()
3997 .map(|i| i.token)
3998 .collect();
3999 let mut revoked = 0usize;
4000 let mut failed = 0usize;
4001 for token in &tokens {
4002 match self.revoke_public_invite(community_id, token).await {
4003 Ok(()) => revoked += 1,
4004 Err(_) => failed += 1,
4005 }
4006 }
4007 Ok((revoked, failed))
4008 }
4009
4010 pub async fn v2_inline_follow(id: &crate::community::CommunityId) -> Vec<String> {
4018 crate::db::scoped(async move {
4019 use crate::community::transport::LiveTransport;
4020 let session = crate::db::current_session();
4021 let lock = crate::community::v2::realtime::follow_lock(id);
4026 let _guard = lock.lock().await;
4027 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4028 let mut warnings: Vec<String> = Vec::new();
4029 let Ok(Some(community)) = crate::db::community::load_community_v2(id) else {
4030 warnings.push("v2 community not found".to_string());
4031 return warnings;
4032 };
4033 let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
4034 match crate::community::v2::service::follow_rekeys(&transport, &community, &session).await {
4035 Ok(f) if f.dissolved => return warnings,
4037 Ok(f) if f.self_removed => {
4038 let _ = crate::db::community::delete_community_retain_keys(&cid_hex);
4046 return warnings;
4047 }
4048 Ok(_) => {}
4049 Err(e) => warnings.push(format!("v2 rekey follow failed: {e}")),
4050 }
4051 if let Ok(Some(fresh)) = crate::db::community::load_community_v2(id) {
4052 match crate::community::v2::service::follow_control(&transport, &fresh).await {
4053 Ok(control) if control.moved() => {
4062 if let Ok(Some(latest)) = crate::db::community::load_community_v2(id) {
4063 if let Err(e) = crate::community::v2::service::follow_rekeys(&transport, &latest, &session).await {
4064 warnings.push(format!("v2 rekey follow failed: {e}"));
4065 }
4066 }
4067 }
4068 Ok(_) => {}
4069 Err(e) => warnings.push(format!("v2 control follow failed: {e}")),
4070 }
4071 }
4072 if let Some(me) = crate::my_public_key() {
4077 if crate::db::community::is_author_banned(&cid_hex, &me) {
4078 let _ = crate::db::community::delete_community_retain_keys(&cid_hex);
4079 return warnings;
4080 }
4081 }
4082 let quiet = crate::event_handler::NoOpEventHandler;
4084 if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
4085 crate::community::v2::service::owe_new_departures(&folded);
4086 }
4087 crate::community::v2::realtime::settle_owed_retractions(id, &transport, &quiet).await;
4088 if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
4089 crate::community::v2::service::rejudge_held(&folded, &quiet).await;
4090 }
4091 warnings
4092 })
4093 .await
4094 }
4095
4096 #[allow(clippy::too_many_arguments)]
4107 pub(crate) async fn v2_backfill_channel(
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 ) -> usize {
4117 let (mut new, mut until) = (0, until);
4120 let mut waiting = Vec::new();
4121 for _ in 0..BACKFILL_CONTINUATIONS {
4122 let (count, still) = Self::v2_backfill_window(id, channel_id, limit, max_pages, since, until, evidence, transport_secs).await;
4123 new += count.new_messages;
4124 waiting.extend(still);
4125 match count.next_before {
4126 Some(next) if until.is_none_or(|u| next < u) => until = Some(next),
4127 _ => break,
4128 }
4129 }
4130 if !waiting.is_empty() {
4133 if let Some(me) = state::my_public_key() {
4134 Self::v2_ingest_chat_page_waiting(channel_id, me, crate::db::current_session(), waiting).await;
4135 }
4136 }
4137 new
4138 }
4139
4140 #[allow(clippy::too_many_arguments)]
4145 pub(crate) async fn v2_backfill_channel_counted(
4146 id: &crate::community::CommunityId,
4147 channel_id: &str,
4148 limit: usize,
4149 max_pages: usize,
4150 since: Option<u64>,
4151 until: Option<u64>,
4152 evidence: crate::community::transport::Evidence,
4153 transport_secs: u64,
4154 ) -> BackfillCount {
4155 Self::v2_backfill_window(id, channel_id, limit, max_pages, since, until, evidence, transport_secs).await.0
4156 }
4157
4158 #[allow(clippy::too_many_arguments)]
4161 async fn v2_backfill_window(
4162 id: &crate::community::CommunityId,
4163 channel_id: &str,
4164 limit: usize,
4165 max_pages: usize,
4166 since: Option<u64>,
4167 until: Option<u64>,
4168 evidence: crate::community::transport::Evidence,
4169 transport_secs: u64,
4170 ) -> (BackfillCount, Vec<crate::community::v2::service::FetchedEvent>) {
4171 let session = crate::db::current_session();
4174 let Some(my_pk) = state::my_public_key() else { return (BackfillCount::default(), Vec::new()) };
4175 if crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false) {
4179 return (BackfillCount::default(), Vec::new());
4180 }
4181 let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return (BackfillCount::default(), Vec::new()) };
4182 let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4183 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(transport_secs));
4184 let held = std::sync::atomic::AtomicUsize::new(0);
4185 let began = crate::clock::now_secs();
4186 let floor = crate::history_gaps::floor(channel_id, until, began);
4187 let reach = crate::history_gaps::reach(since, floor);
4188 let live = community.channel(&ch).map_or(community.root_epoch, |c| community.channel_secret(c).1);
4189 let past = until.is_none().then(|| match crate::history_gaps::proven_epoch(channel_id) {
4192 Some(e) => (crate::community::Epoch(e), since),
4193 None => (crate::community::Epoch(live.0.saturating_sub(UNPROVEN_EPOCHS)), reach),
4194 });
4195 let unread: Vec<nostr_sdk::prelude::PublicKey> = match community.channel(&ch).filter(|_| until.is_none()) {
4198 Some(c) => {
4199 let read = crate::history_gaps::history_read(channel_id);
4200 let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
4201 let views = crate::db::community::history_views(&cid_hex, channel_id).unwrap_or_default().into_iter().filter_map(|(_, v)| nostr_sdk::prelude::PublicKey::from_slice(&v.address).ok());
4202 c.published_history().into_iter().map(|(_, g)| g.pk()).chain(views).filter(|pk| !read.contains(&pk.to_hex())).collect()
4203 }
4204 None => Vec::new(),
4205 };
4206 let Ok((page, next_before, complete)) = crate::community::v2::service::fetch_channel_history_since_epoch(
4207 &transport,
4208 &community,
4209 &ch,
4210 limit.max(50),
4211 max_pages,
4212 reach,
4213 until,
4214 evidence,
4215 |page, settled, next| {
4217 crate::community::v2::service::catch_up_pages_on(page, settled, next, floor, |id| crate::db::events::event_exists(id).unwrap_or(false))
4218 },
4219 |wraps| {
4221 if until.is_some() {
4222 return Default::default();
4223 }
4224 let hex: Vec<String> = wraps.iter().map(|w| w.to_hex()).collect();
4225 let settled = crate::db::events::community_wraps_settled(&hex);
4226 let skip: std::collections::HashSet<_> = wraps.iter().zip(&hex).filter(|(_, h)| settled.contains(*h)).map(|(w, _)| *w).collect();
4227 held.fetch_add(skip.len(), std::sync::atomic::Ordering::Relaxed);
4228 skip
4229 },
4230 past,
4231 &unread,
4232 )
4233 .await
4234 else {
4235 return (BackfillCount { unreachable: true, ..Default::default() }, Vec::new());
4236 };
4237 let fetched = page.len() + held.into_inner();
4238 let (new_messages, waiting) = Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await;
4239 crate::history_gaps::note_walk(channel_id, until, next_before, floor, |t| crate::db::events::newest_message_before(channel_id, t));
4241 if until.is_none() && since.is_none() && complete {
4244 crate::history_gaps::prove(channel_id, began, live.0);
4245 }
4246 if complete && !unread.is_empty() {
4248 crate::history_gaps::mark_history_read(channel_id, unread.iter().map(|pk| pk.to_hex()));
4249 }
4250 (BackfillCount { fetched, new_messages, next_before, unreachable: false }, waiting)
4251 }
4252
4253 pub(crate) async fn v2_ingest_chat_page(
4257 channel_id: &str,
4258 my_pk: nostr_sdk::prelude::PublicKey,
4259 session: std::sync::Arc<crate::db::Session>,
4260 page: Vec<crate::community::v2::service::FetchedEvent>,
4261 ) -> usize {
4262 Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await.0
4263 }
4264
4265 async fn v2_ingest_chat_page_waiting(
4267 channel_id: &str,
4268 my_pk: nostr_sdk::prelude::PublicKey,
4269 session: std::sync::Arc<crate::db::Session>,
4270 page: Vec<crate::community::v2::service::FetchedEvent>,
4271 ) {
4272 Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await;
4273 }
4274
4275 async fn v2_ingest_chat_page_keeping(
4278 channel_id: &str,
4279 my_pk: nostr_sdk::prelude::PublicKey,
4280 session: std::sync::Arc<crate::db::Session>,
4281 page: Vec<crate::community::v2::service::FetchedEvent>,
4282 ) -> (usize, Vec<crate::community::v2::service::FetchedEvent>) {
4283 crate::db::scoped(async move {
4284 use crate::community::v2::inbound::ChatPersist;
4285 let judged_on = crate::community::v2::service::writers_head(channel_id);
4286 let page = crate::community::v2::service::rejudge_page(channel_id, page);
4287 let since = page.iter().map(|f| f.event.opened().at_ms).min();
4288 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();
4289 let mut new = 0usize;
4290 let mut unapplied: Vec<usize> = Vec::new();
4291 let mut outcomes: Vec<ChatPersist> = Vec::with_capacity(page.len());
4293 let mut sources: Vec<usize> = Vec::with_capacity(page.len());
4295 let stored = crate::db::events::existing_event_ids(&crate::community::v2::inbound::page_event_ids(page.iter().map(|f| &f.event))).unwrap_or_default();
4296 for (i, f) in page.iter().enumerate() {
4297 if let crate::community::v2::chat::ChatEvent::Webxdc { opened } = &f.event {
4302 if opened.author != my_pk {
4303 if let Some((topic, addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) {
4304 let Ok(npub) = ToBech32::to_bech32(&opened.author);
4305 crate::community::v2::inbound::persist_webxdc_signal(
4306 channel_id,
4307 &npub,
4308 &topic,
4309 addr.as_deref(),
4310 &opened.rumor_id.to_hex(),
4311 opened.at_ms / 1000,
4312 )
4313 .await;
4314 }
4315 }
4316 continue;
4317 }
4318 crate::community::v2::inbound::hydrate_target(&f.event, channel_id).await;
4319 let outcome = {
4320 let mut st = state::STATE.lock().await;
4321 crate::community::v2::inbound::apply_page_event_to_state(&mut st, &f.event, channel_id, &my_pk, &stored)
4322 };
4323 match outcome {
4324 Some(outcome) => {
4325 if matches!(outcome, ChatPersist::New(_)) {
4326 new += 1;
4327 }
4328 outcomes.push(outcome);
4329 sources.push(i);
4330 }
4331 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),
4332 None => {}
4333 }
4334 }
4335 for o in &mut outcomes {
4342 if let ChatPersist::New(m) | ChatPersist::Updated { message: m, .. } = o {
4343 crate::db::attachments::verify_message_attachments(m, Some(channel_id)).await;
4344 }
4345 }
4346 crate::community::v2::inbound::persist_chat_page(channel_id, &outcomes, &session).await;
4347 if let Some(since) = since {
4348 crate::community::v2::service::owe_if_moved(channel_id, judged_on, since);
4349 }
4350 crate::community::v2::service::owe_if_departed(channel_id, &posted);
4351 {
4355 let quoted: Vec<&mut crate::types::Message> = outcomes
4356 .iter_mut()
4357 .filter_map(|o| match o {
4358 ChatPersist::New(m)
4359 | ChatPersist::Updated { message: m, .. }
4360 | ChatPersist::ReactionRemoved { message: m, .. } => Some(m),
4361 ChatPersist::Removed { .. } => None,
4362 })
4363 .collect();
4364 let _ = crate::db::events::populate_reply_contexts(quoted).await;
4365 }
4366 for outcome in &outcomes {
4372 match outcome {
4373 ChatPersist::New(msg) => crate::traits::emit_message_new(channel_id, msg),
4374 ChatPersist::Updated { message, .. }
4375 | ChatPersist::ReactionRemoved { message, .. } => {
4376 let mut message = message.clone();
4377 let target_id = message.id.clone();
4378 crate::traits::emit_message_update(channel_id, &target_id, &mut message).await;
4379 }
4380 ChatPersist::Removed { id: target_id, .. } => crate::traits::emit_event(
4381 "message_removed",
4382 &serde_json::json!({ "id": target_id, "chat_id": channel_id, "reason": "deleted" }),
4383 ),
4384 }
4385 }
4386 if let Some(listener) = crate::news::listener() {
4389 for (outcome, i) in outcomes.into_iter().zip(sources) {
4390 let event = &page[i].event;
4391 let at = match &outcome {
4392 ChatPersist::New(m) => m.at,
4393 _ => event.opened().at_ms,
4394 };
4395 if crate::news::is_news(at) {
4396 crate::community::v2::inbound::notify_chat_outcome(&*listener, channel_id, event, outcome, true).await;
4397 }
4398 }
4399 }
4400 let mut waiting = Vec::new();
4401 for i in unapplied {
4402 let f = &page[i];
4403 if crate::community::v2::inbound::awaits_target(&f.event).await {
4404 waiting.push(crate::community::v2::service::FetchedEvent { event: f.event.clone(), epoch: f.epoch, wrap: f.wrap.clone() });
4405 }
4406 }
4407 (new, waiting)
4408 })
4409 .await
4410 }
4411
4412 fn unheld_id(community_id: &str) -> Result<crate::community::CommunityId> {
4416 crate::simd::hex::hex_to_bytes_32_checked(community_id)
4417 .map(crate::community::CommunityId)
4418 .ok_or_else(|| VectorError::Other("malformed community id".into()))
4419 }
4420
4421 fn load_held(community_id: &str) -> Result<Option<crate::community::v2::community::CommunityV2>> {
4422 if community_id.len() != 64 {
4423 return Ok(None);
4424 }
4425 let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
4426 crate::db::community::load_community_v2(&cid).map_err(VectorError::Other)
4427 }
4428
4429 pub fn community_capabilities(&self, community_id: &str) -> Result<serde_json::Value> {
4437 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4438 use crate::community::roles::Permissions;
4439 let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
4440 let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
4441 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4442 let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
4445 if banned.contains(&me) && me != owner_hex {
4446 return Ok(serde_json::json!({
4447 "manage_metadata": false, "manage_channels": false, "create_invite": false, "kick": false,
4448 "ban": false, "manage_messages": false, "manage_roles": false, "manage_admin_role": false,
4449 "pin_messages": false, "control_write": false, "moderate_members": false, "view_audit_log": false,
4450 "manage_nicknames": false, "change_nickname": false,
4451 }));
4452 }
4453 let control_write = crate::community::v2::control::ControlPlane::of(&v2).can_write();
4459 let has = |p: u64| roster.is_authorized(&me, Some(&owner_hex), p);
4460 let has_ctl = |p: u64| control_write && has(p);
4461 Ok(serde_json::json!({
4462 "manage_metadata": has_ctl(Permissions::MANAGE_METADATA), "manage_channels": has_ctl(Permissions::MANAGE_CHANNELS),
4463 "create_invite": has_ctl(Permissions::CREATE_INVITE), "kick": has(Permissions::KICK), "ban": has_ctl(Permissions::BAN),
4464 "manage_messages": has(Permissions::MANAGE_MESSAGES), "manage_roles": has_ctl(Permissions::MANAGE_ROLES),
4465 "manage_admin_role": me == owner_hex && control_write,
4467 "pin_messages": has_ctl(Permissions::PIN_MESSAGES),
4468 "control_write": control_write,
4469 "moderate_members": has(Permissions::MODERATE_MEMBERS),
4471 "view_audit_log": has(Permissions::VIEW_AUDIT_LOG),
4472 "manage_nicknames": has(Permissions::MANAGE_NICKNAMES),
4474 "change_nickname": roster.may_name(&me, Some(&owner_hex), &me),
4475 }))
4476 }
4477
4478 pub async fn check_community_relays(&self, community_id: &str, relays: &[String]) -> Result<Vec<crate::community::v2::service::RelayCheck>> {
4481 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4482 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
4483 crate::community::v2::service::check_relays(&transport, &v2, relays).await.map_err(VectorError::Other)
4484 }
4485
4486 pub async fn move_community_relays(&self, community_id: &str, relays: &[String]) -> Result<crate::community::v2::service::RelayMove> {
4489 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4490 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
4491 crate::community::v2::service::move_relays(&transport, &v2, relays).await.map_err(VectorError::Other)
4492 }
4493
4494 pub async fn community_audit_log(&self, community_id: &str) -> Result<crate::community::v2::service::AuditLog> {
4497 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
4498 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
4499 crate::community::v2::service::audit_log(&transport, &v2).await.map_err(VectorError::Other)
4500 }
4501
4502 pub async fn pin_community_message(&self, community_id: &str, channel_id: &str, message_id: &str) -> Result<()> {
4505 use crate::community::{transport::LiveTransport, ChannelId};
4506 let v2 = Self::load_held(community_id)?
4507 .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
4508 let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4509 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4510 crate::community::v2::service::pin_message(&transport, &v2, &ch, message_id)
4511 .await
4512 .map_err(VectorError::Other)
4513 }
4514
4515 pub async fn unpin_community_message(&self, community_id: &str, channel_id: &str, message_id: &str) -> Result<()> {
4517 use crate::community::{transport::LiveTransport, ChannelId};
4518 let v2 = Self::load_held(community_id)?
4519 .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
4520 let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4521 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4522 crate::community::v2::service::unpin_message(&transport, &v2, &ch, message_id)
4523 .await
4524 .map_err(VectorError::Other)
4525 }
4526
4527 pub async fn fetch_pinned_attachment(
4535 &self,
4536 community_id: &str,
4537 channel_id: &str,
4538 rumor_id: &str,
4539 ) -> Result<serde_json::Value> {
4540 crate::db::scoped(async move {
4541 use crate::community::ChannelId;
4542 let v2 = Self::load_held(community_id)?
4543 .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
4544 let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4545 let pins = crate::community::v2::service::read_channel_pins(&v2, &ch).map_err(VectorError::Other)?;
4546 let pin = pins
4547 .pins
4548 .iter()
4549 .find(|p| p.rumor_id == rumor_id)
4550 .ok_or_else(|| VectorError::Other("that message is not pinned".into()))?;
4551 let dir = crate::db::get_download_dir();
4552 let tag = pin
4553 .tags
4554 .iter()
4555 .find(|t| t.first().map(String::as_str) == Some("imeta"))
4556 .map(|t| nostr_sdk::prelude::Tag::custom("imeta", t[1..].to_vec()))
4557 .ok_or_else(|| VectorError::Other("this pin carries no attachment".into()))?;
4558 let attachment = crate::community::attachments::attachment_from_imeta(&tag, &dir)
4559 .ok_or_else(|| VectorError::Other("this pin's attachment metadata is malformed".into()))?;
4560
4561 let respond = |path: &str| {
4562 serde_json::json!({
4563 "path": path,
4564 "name": attachment.name.to_string(),
4565 "extension": attachment.extension.to_string(),
4566 })
4567 };
4568
4569 let expected = attachment.original_hash.as_deref();
4573 let in_memory = crate::media::ram::cache().admits(attachment.size);
4576 let keep = !in_memory || crate::media::keep_media();
4577 if let Some(hash) = expected.and_then(crate::simd::hex::hex_to_bytes_32_checked).filter(|h| crate::media::resident(h)) {
4578 return Ok(respond(&crate::media::MediaRef::held(&hash)));
4579 }
4580 let path = std::path::PathBuf::from(&*attachment.path);
4581 if let Ok(bytes) = std::fs::read(&path) {
4582 match expected {
4583 Some(want) if crate::crypto::sha256_hex(&bytes) == want => return Ok(respond(&path.to_string_lossy())),
4584 None => return Ok(respond(&path.to_string_lossy())),
4585 _ => {} }
4587 }
4588
4589 let author_npub = nostr_sdk::prelude::PublicKey::from_hex(&pin.author)
4590 .ok()
4591 .and_then(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok());
4592 let bytes = self.download_attachment_from(&attachment, author_npub.as_deref()).await?;
4593 let hash = crate::crypto::sha256_hex(&bytes);
4594 if expected.is_some_and(|want| hash != want) {
4595 return Err(VectorError::Other("downloaded bytes do not match the pinned content hash".into()));
4596 }
4597 let held = crate::simd::hex::hex_to_bytes_32(&hash);
4598 let mime = crate::crypto::mime_from_extension(&attachment.extension.to_ascii_lowercase());
4599 if keep {
4601 #[cfg(not(target_arch = "wasm32"))]
4602 crate::media::store::keep_sealed(&bytes, held, mime, crate::db::media_store::Origin::Sealed)
4603 .map_err(|e| VectorError::Other(format!("could not keep the attachment: {e}")))?;
4604 #[cfg(target_arch = "wasm32")]
4605 crate::media::store::keep_sealed(&bytes, held, mime, crate::db::media_store::Origin::Sealed)
4606 .await
4607 .map_err(|e| VectorError::Other(format!("could not keep the attachment: {e}")))?;
4608 }
4609 if in_memory {
4610 match crate::media::ram::insert(held, bytes, mime) {
4611 Ok(_) => {}
4612 Err(_) if keep => {}
4613 Err(_) => return Err(VectorError::Other("too much media is open to show this one".into())),
4614 }
4615 }
4616 Ok(respond(&crate::media::MediaRef::held(&held)))
4617 })
4618 .await
4619 }
4620
4621 pub fn get_channel_pins(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
4625 use crate::community::ChannelId;
4626 let Some(v2) = Self::load_held(community_id)? else {
4627 return Ok(serde_json::json!({ "pins": [], "sealed": false, "version": 0 }));
4628 };
4629 let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
4630 let pins = crate::community::v2::service::read_channel_pins(&v2, &ch).map_err(VectorError::Other)?;
4631 serde_json::to_value(&pins).map_err(|e| VectorError::Other(e.to_string()))
4632 }
4633
4634 pub fn community_role_graph(&self, community_id: &str) -> Result<serde_json::Value> {
4642 use nostr_sdk::prelude::{PublicKey, ToBech32};
4643 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4644 let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
4646 let roles: Vec<serde_json::Value> = roster
4647 .roles
4648 .iter()
4649 .map(|r| {
4650 let channel_id = match &r.scope {
4653 crate::community::roles::RoleScope::Channel(c) => Some(c.to_ascii_lowercase()),
4654 crate::community::roles::RoleScope::Server => None,
4655 };
4656 serde_json::json!({
4657 "role_id": r.role_id,
4658 "name": r.name,
4659 "position": r.position,
4660 "color": r.color,
4661 "channel_id": channel_id,
4662 "display": r.display,
4663 })
4664 })
4665 .collect();
4666 let grants: Vec<serde_json::Value> = roster
4667 .grants
4668 .iter()
4669 .filter(|g| !banned.contains(&g.member))
4670 .filter_map(|g| {
4671 let npub = PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok())?;
4672 Some(serde_json::json!({ "npub": npub, "role_ids": g.role_ids }))
4673 })
4674 .collect();
4675 let activated = roster.everyone.is_some();
4677 let mut readers = serde_json::Map::new();
4678 if activated {
4679 if let Some(v2) = Self::load_held(community_id)? {
4680 let owner_hex = v2.owner().ok().map(|o| o.to_hex());
4681 let mut candidates: std::collections::BTreeSet<PublicKey> =
4682 crate::community::v2::service::stored_memberlist(&v2).unwrap_or_default().into_iter().collect();
4683 candidates.extend(roster.grants.iter().filter_map(|g| PublicKey::from_hex(&g.member).ok()));
4684 for ch in v2.channels.iter().filter(|c| c.private) {
4685 let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
4686 let npubs: Vec<String> = candidates
4687 .iter()
4688 .filter(|pk| !banned.contains(&pk.to_hex()) && roster.is_entitled(owner_hex.as_deref(), &pk.to_hex(), &chan, &[], &[]))
4689 .filter_map(|pk| pk.to_bech32().ok())
4690 .collect();
4691 readers.insert(chan, npubs.into());
4692 }
4693 }
4694 }
4695 Ok(serde_json::json!({ "roles": roles, "grants": grants, "activated": activated, "readers": readers }))
4696 }
4697
4698 pub fn community_roles_view(&self, community_id: &str) -> Result<serde_json::Value> {
4703 use crate::community::roles::{Permissions, RoleScope};
4704 let v2 = Self::load_held(community_id)?
4705 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4706 let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
4707 let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
4708 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4709 let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
4710 let is_owner = me == owner_hex;
4711 let can_manage = is_owner
4712 || (!banned.contains(&me) && roster.is_authorized(&me, Some(&owner_hex), Permissions::MANAGE_ROLES));
4713 let rank = if is_owner { Some(0) } else { roster.highest_position(&me) };
4714 let grantable = if is_owner { u64::MAX } else { roster.effective_permissions(&me).0 };
4715 let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().collect();
4716 roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
4717 let activated = Self::roles_v2_active(community_id, &roster);
4718 let roles: Vec<serde_json::Value> = roles
4719 .into_iter()
4720 .map(|r| {
4721 let holders: Vec<String> = roster
4722 .grants
4723 .iter()
4724 .filter(|g| !banned.contains(&g.member) && g.role_ids.iter().any(|id| id == &r.role_id))
4725 .filter_map(|g| nostr_sdk::prelude::PublicKey::from_hex(&g.member).ok())
4726 .filter_map(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok())
4727 .collect();
4728 serde_json::json!({
4729 "role_id": r.role_id,
4730 "name": r.name,
4731 "position": r.position,
4732 "color": r.color,
4733 "permissions": r.permissions.0.to_string(),
4734 "channel_id": match &r.scope { RoleScope::Channel(c) => Some(c.to_ascii_lowercase()), RoleScope::Server => None },
4735 "holders": holders,
4736 "display": r.display,
4737 "mentionable": r.mentionable,
4738 "manageable": can_manage && (is_owner || {
4739 let support = roster.permissions_above(&me, r.position);
4740 support.contains(Permissions::MANAGE_ROLES) && r.permissions.0 & !support.0 == 0
4741 }),
4742 })
4743 })
4744 .collect();
4745 let channels: Vec<serde_json::Value> = v2
4746 .channels
4747 .iter()
4748 .map(|c| serde_json::json!({
4749 "channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
4750 "name": c.name,
4751 "private": c.private,
4752 }))
4753 .collect();
4754 Ok(serde_json::json!({
4755 "is_owner": is_owner,
4756 "can_manage": can_manage,
4757 "rank": rank,
4758 "grantable": grantable.to_string(),
4759 "activated": activated,
4761 "everyone": roster.everyone.map(|p| p.0.to_string()),
4762 "everyone_editable": activated && (is_owner || roster.permissions_above(&me, u32::MAX).contains(Permissions::MANAGE_ROLES)),
4763 "everyone_default": crate::community::v2::roles::EVERYONE_DEFAULT.to_string(),
4764 "roles": roles,
4765 "channels": channels,
4766 "max_roles": crate::community::v2::roles::MAX_ROLES_PER_COMMUNITY,
4767 "max_per_member": crate::community::v2::roles::MAX_ROLES_PER_MEMBER,
4768 }))
4769 }
4770
4771 fn parse_permissions(s: &str) -> Result<u64> {
4772 if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
4773 return Err(VectorError::Other(format!("permissions must be a decimal string, got {s:?}")));
4774 }
4775 s.parse::<u64>().map_err(|_| VectorError::Other("permissions out of range".into()))
4776 }
4777
4778 fn role_scope(channel_id: Option<&str>) -> Result<crate::community::roles::RoleScope> {
4779 use crate::community::roles::RoleScope;
4780 match channel_id {
4781 None => Ok(RoleScope::Server),
4782 Some(c) if c.len() == 64 && c.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(RoleScope::Channel(c.to_ascii_lowercase())),
4783 Some(_) => Err(VectorError::Other("channel_id must be 32-byte hex".into())),
4784 }
4785 }
4786
4787 pub async fn create_role(&self, community_id: &str, name: &str, color: u32, permissions: &str, channel_id: Option<&str>) -> Result<String> {
4789 let v2 = Self::load_held(community_id)?
4790 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4791 let perms = Self::parse_permissions(permissions)?;
4792 let scope = Self::role_scope(channel_id)?;
4793 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4794 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4795 let id = if Self::roles_v2_active(community_id, &roster) {
4796 if channel_id.is_some() {
4797 return Err(VectorError::Other("on the new roles, channel access is set on the channel".into()));
4798 }
4799 crate::community::v2::service::create_role_v2(&transport, &v2, name, color, perms).await
4800 } else {
4801 crate::community::v2::service::create_role(&transport, &v2, name, color, perms, scope).await
4802 }
4803 .map_err(VectorError::Other)?;
4804 Self::converge_v2_authority(&transport, community_id).await;
4805 Ok(id)
4806 }
4807
4808 pub async fn edit_role(&self, community_id: &str, role_id: &str, name: &str, color: u32, permissions: &str, channel_id: Option<&str>) -> Result<()> {
4810 self.edit_role_shown(community_id, role_id, name, color, permissions, channel_id, None, None).await
4811 }
4812
4813 #[allow(clippy::too_many_arguments)]
4816 pub async fn edit_role_shown(
4817 &self,
4818 community_id: &str,
4819 role_id: &str,
4820 name: &str,
4821 color: u32,
4822 permissions: &str,
4823 channel_id: Option<&str>,
4824 display: Option<bool>,
4825 mentionable: Option<bool>,
4826 ) -> Result<()> {
4827 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4828 if Self::roles_v2_active(community_id, &roster) {
4829 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4830 let perms = Self::parse_permissions(permissions)?;
4831 let current = roster.role(role_id).ok_or_else(|| VectorError::Other("no such role".into()))?;
4832 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4833 crate::community::v2::service::edit_role_v2(
4834 &transport,
4835 &v2,
4836 role_id,
4837 name,
4838 color,
4839 perms,
4840 display.unwrap_or(current.display),
4841 mentionable.unwrap_or(current.mentionable),
4842 )
4843 .await
4844 .map_err(VectorError::Other)?;
4845 Self::converge_v2_authority(&transport, community_id).await;
4846 return Ok(());
4847 }
4848 let v2 = Self::load_held(community_id)?
4849 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4850 let perms = Self::parse_permissions(permissions)?;
4851 let scope = Self::role_scope(channel_id)?;
4852 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4853 crate::community::v2::service::edit_role(&transport, &v2, role_id, name, color, perms, scope)
4854 .await
4855 .map_err(VectorError::Other)?;
4856 Self::converge_v2_authority(&transport, community_id).await;
4857 Ok(())
4858 }
4859
4860 pub async fn reorder_roles(&self, community_id: &str, ordered: &[String]) -> Result<usize> {
4862 let v2 = Self::load_held(community_id)?
4863 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
4864 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
4865 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4866 if Self::roles_v2_active(community_id, &roster) {
4867 let moved = crate::community::v2::service::reorder_roles_v2(&transport, &v2, ordered).await.map_err(VectorError::Other)?;
4868 if moved > 0 {
4869 Self::converge_v2_authority(&transport, community_id).await;
4870 }
4871 return Ok(moved);
4872 }
4873 let moved = crate::community::v2::service::reorder_roles(&transport, &v2, ordered)
4874 .await
4875 .map_err(VectorError::Other)?;
4876 if moved > 0 {
4877 Self::converge_v2_authority(&transport, community_id).await;
4878 }
4879 Ok(moved)
4880 }
4881
4882 fn roles_v2_active(community_id: &str, roster: &crate::community::roles::CommunityRoles) -> bool {
4884 if roster.everyone.is_some() {
4885 return true;
4886 }
4887 let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(community_id) else { return false };
4888 let everyone = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(&crate::community::CommunityId(cid)));
4889 crate::db::community::get_edition_head(community_id, &everyone).ok().flatten().is_some()
4890 }
4891
4892 fn held_v2(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
4893 Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("this needs a Concord v2 community".into()))
4894 }
4895
4896 fn short_transport() -> crate::community::transport::LiveTransport {
4897 crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12))
4898 }
4899
4900 fn view_named(view: &str) -> Result<crate::community::v2::community::ChannelView> {
4902 crate::community::v2::community::ChannelView::try_parse(view)
4903 .ok_or_else(|| VectorError::Other(format!("no channel view named {view:?}: chat, forum or voice")))
4904 }
4905
4906 fn id32(hex: &str, what: &str) -> Result<[u8; 32]> {
4907 crate::simd::hex::hex_to_bytes_32_checked(hex).ok_or_else(|| VectorError::Other(format!("{what} must be 32-byte hex")))
4908 }
4909
4910 pub fn channel_permissions_view(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
4913 use crate::community::roles::{OverwriteTarget, Permissions};
4914 let v2 = Self::held_v2(community_id)?;
4915 let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
4916 let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
4917 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
4918 let is_owner = me == owner_hex;
4919 let chan = channel_id.to_ascii_lowercase();
4920 let support = |target: &OverwriteTarget| roster.overwrite_support(&me, &owner_hex, target).map(|b| b.to_string());
4921 let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().collect();
4922 roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
4923 let overwrites: Vec<serde_json::Value> = roster
4924 .overwrites
4925 .iter()
4926 .filter(|o| o.scope == chan)
4927 .map(|o| {
4928 let (kind, id) = match &o.target {
4929 OverwriteTarget::Everyone => ("everyone", None),
4930 OverwriteTarget::Role(id) => ("role", Some(id.clone())),
4931 OverwriteTarget::Member(m) => ("member", Some(m.clone())),
4932 };
4933 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();
4934 serde_json::json!({ "kind": kind, "id": id, "npub": npub, "allow": o.allow.0.to_string(), "deny": o.deny.0.to_string(), "support": support(&o.target) })
4935 })
4936 .collect();
4937 let category = crate::simd::hex::hex_to_bytes_32_checked(&chan)
4938 .and_then(|b| v2.channel(&crate::community::ChannelId(b)))
4939 .and_then(|c| c.category())
4940 .filter(|k| v2.categories.iter().any(|x| x.id == *k))
4941 .map(|k| crate::simd::hex::bytes_to_hex_32(&k));
4942 let can_sync = {
4944 let mut scopes = vec![chan.as_str()];
4945 scopes.extend(category.as_deref());
4946 scopes.extend(roster.syncs.get(&chan).map(String::as_str));
4947 crate::community::v2::service::may_swap_overwrites(&roster, Some(&owner_hex), &me, &scopes, &|_| 0)
4948 };
4949 Ok(serde_json::json!({
4950 "activated": Self::roles_v2_active(community_id, &roster),
4951 "category": category,
4953 "synced": roster.syncs.get(&chan),
4954 "can_sync": can_sync,
4955 "can_manage": is_owner || roster.is_authorized(&me, Some(&owner_hex), Permissions::MANAGE_ROLES),
4956 "grantable": if is_owner { u64::MAX.to_string() } else { roster.effective_permissions(&me).0.to_string() },
4957 "me": me,
4959 "everyone_support": support(&OverwriteTarget::Everyone),
4960 "roles": roles
4961 .iter()
4962 .map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name, "color": r.color, "position": r.position, "support": support(&OverwriteTarget::Role(r.role_id.clone())) }))
4963 .collect::<Vec<_>>(),
4964 "overwrites": overwrites,
4965 "members": crate::community::v2::service::stored_memberlist(&v2)
4967 .unwrap_or_default()
4968 .into_iter()
4969 .filter(|pk| pk.to_hex() != owner_hex)
4970 .map(|pk| serde_json::json!({ "id": pk.to_hex(), "npub": ToBech32::to_bech32(&pk).ok(), "support": support(&OverwriteTarget::Member(pk.to_hex())) }))
4971 .collect::<Vec<_>>(),
4972 }))
4973 }
4974
4975 pub async fn set_channel_overwrite(&self, community_id: &str, scope_id: &str, kind: &str, target_id: Option<&str>, allow: &str, deny: &str) -> Result<()> {
4978 use crate::community::roles::OverwriteTarget;
4979 let v2 = Self::held_v2(community_id)?;
4980 let target = match (kind, target_id) {
4981 ("everyone", _) => OverwriteTarget::Everyone,
4982 ("role", Some(id)) => OverwriteTarget::Role(crate::simd::hex::bytes_to_hex_32(&Self::id32(id, "role_id")?)),
4983 ("member", Some(m)) => OverwriteTarget::Member(
4984 nostr_sdk::prelude::PublicKey::parse(m).map_err(|_| VectorError::Other("invalid member key".into()))?.to_hex(),
4985 ),
4986 _ => return Err(VectorError::Other("an overwrite targets everyone, a role or a member".into())),
4987 };
4988 let (allow, deny) = (Self::parse_permissions(allow)?, Self::parse_permissions(deny)?);
4989 let transport = Self::short_transport();
4990 crate::community::v2::service::set_overwrite(&transport, &v2, Self::id32(scope_id, "scope_id")?, target, allow, deny)
4991 .await
4992 .map_err(VectorError::Other)?;
4993 Self::converge_v2_authority(&transport, community_id).await;
4994 Ok(())
4995 }
4996
4997 pub async fn set_channel_sync(&self, community_id: &str, channel_id: &str, category_id: Option<&str>) -> Result<()> {
4999 let v2 = Self::held_v2(community_id)?;
5000 let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
5001 let category = category_id.map(|c| Self::id32(c, "category_id")).transpose()?;
5002 let transport = Self::short_transport();
5003 crate::community::v2::service::set_channel_sync(&transport, &v2, &channel, category).await.map_err(VectorError::Other)?;
5004 Self::converge_v2_authority(&transport, community_id).await;
5005 Ok(())
5006 }
5007
5008 pub fn channel_synced_to(&self, community_id: &str, channel_id: &str) -> Result<Option<String>> {
5011 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5012 Ok(roster.syncs.get(&channel_id.to_ascii_lowercase()).cloned())
5013 }
5014
5015 pub fn channel_send_denied(&self, community_id: &str, channel_id: &str, npubs: &[String]) -> Result<Vec<String>> {
5018 Self::channel_denied(community_id, channel_id, npubs, crate::community::roles::Permissions::SEND_MESSAGES)
5019 }
5020
5021 pub fn channel_react_denied(&self, community_id: &str, channel_id: &str, npubs: &[String]) -> Result<Vec<String>> {
5024 Self::channel_denied(community_id, channel_id, npubs, crate::community::roles::Permissions::ADD_REACTIONS)
5025 }
5026
5027 fn channel_denied(community_id: &str, channel_id: &str, npubs: &[String], perm: u64) -> Result<Vec<String>> {
5028 let v2 = Self::held_v2(community_id)?;
5029 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5030 if roster.everyone.is_none() {
5031 return Ok(Vec::new());
5032 }
5033 let owner = v2.owner().ok().map(|o| o.to_hex());
5034 let chan = channel_id.to_ascii_lowercase();
5035 let ch = Self::id32(channel_id, "channel_id").ok().and_then(|b| v2.channel(&crate::community::ChannelId(b)));
5036 let private = ch.is_some_and(|c| c.private);
5037 Ok(npubs
5038 .iter()
5039 .filter(|n| {
5040 nostr_sdk::prelude::PublicKey::parse(n.as_str())
5041 .is_ok_and(|pk| !roster.channel_permissions(owner.as_deref(), &pk.to_hex(), &chan, private).contains(perm))
5042 })
5043 .cloned()
5044 .collect())
5045 }
5046
5047 pub fn community_mentions(&self, community_id: &str) -> Result<serde_json::Value> {
5051 use crate::community::roles::Permissions;
5052 use nostr_sdk::prelude::PublicKey;
5053 let v2 = Self::held_v2(community_id)?;
5054 let owner = v2.owner().map_err(VectorError::Other)?.to_hex();
5055 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5056 let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
5057 let me = crate::state::my_public_key().map(|pk| pk.to_hex()).unwrap_or_default();
5058 let members: std::collections::BTreeSet<&str> = std::iter::once(owner.as_str()).chain(roster.grants.iter().map(|g| g.member.as_str())).collect();
5059 let pingers: Vec<String> = members
5060 .into_iter()
5061 .filter(|m| !banned.iter().any(|b| b == m) && roster.is_authorized(m, Some(&owner), Permissions::MENTION_EVERYONE))
5062 .filter_map(|m| PublicKey::from_hex(m).ok()?.to_bech32().ok())
5063 .collect();
5064 let held: std::collections::HashSet<&str> = roster.roles_of(&me).map(|r| r.role_id.as_str()).collect();
5065 let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().filter(|r| crate::community::mentions::is_role_id(&r.role_id)).collect();
5066 roles.sort_by_key(|r| r.position);
5067 let roles: Vec<serde_json::Value> = roles
5068 .into_iter()
5069 .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()) }))
5070 .collect();
5071 Ok(serde_json::json!({
5072 "anyone": roster.everyone.is_some_and(|e| e.contains(Permissions::MENTION_EVERYONE)),
5073 "pingers": pingers,
5074 "roles": roles,
5075 }))
5076 }
5077
5078 pub fn role_mentions_ping_me(&self, community_id: &str, author_npub: &str, content: &str, role_ids: &[String]) -> bool {
5080 if role_ids.is_empty() {
5081 return false;
5082 }
5083 let (Some(me), Ok(author), Ok(Some(held))) = (
5084 crate::state::my_public_key(),
5085 nostr_sdk::prelude::PublicKey::parse(author_npub),
5086 Self::load_held(community_id),
5087 ) else {
5088 return false;
5089 };
5090 let (Ok(owner), Ok(roster)) = (held.owner(), crate::db::community::get_community_roles(community_id)) else { return false };
5091 let author = author.to_hex();
5092 if crate::db::community::get_community_banlist(community_id).unwrap_or_default().contains(&author) {
5093 return false;
5094 }
5095 crate::community::mentions::pings(&roster, Some(&owner.to_hex()), &author, &me.to_hex(), content, role_ids)
5096 }
5097
5098 pub fn post_silenced(&self, community_id: &str, channel_id: &str, author_npub: &str) -> bool {
5101 if self.channel_send_denied(community_id, channel_id, &[author_npub.to_string()]).is_ok_and(|d| !d.is_empty()) {
5102 return true;
5103 }
5104 let (Ok(v2), Ok(author)) = (Self::held_v2(community_id), nostr_sdk::prelude::PublicKey::parse(author_npub)) else { return false };
5105 crate::community::v2::service::community_timeouts(&v2).is_ok_and(|t| t.contains_key(&author))
5106 }
5107
5108 pub fn community_timeouts(&self, community_id: &str) -> Result<serde_json::Value> {
5110 let v2 = Self::held_v2(community_id)?;
5111 let running = crate::community::v2::service::community_timeouts(&v2).map_err(VectorError::Other)?;
5112 Ok(running
5113 .into_iter()
5114 .filter_map(|(pk, (from, until))| Some((pk.to_bech32().ok()?, serde_json::json!({ "from": from, "until": until }))))
5115 .collect::<serde_json::Map<_, _>>()
5116 .into())
5117 }
5118
5119 pub async fn timeout_member(&self, community_id: &str, npub: &str, seconds: u64) -> Result<()> {
5121 let v2 = Self::held_v2(community_id)?;
5122 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5123 crate::community::v2::service::timeout_member(&Self::short_transport(), &v2, &member, seconds).await.map_err(VectorError::Other)
5124 }
5125
5126 pub fn community_nicknames(&self, community_id: &str) -> Result<serde_json::Value> {
5128 let v2 = Self::held_v2(community_id)?;
5129 let named = crate::community::v2::service::community_nicknames(&v2).map_err(VectorError::Other)?;
5130 Ok(named
5131 .into_iter()
5132 .filter_map(|(pk, nick)| Some((pk.to_bech32().ok()?, serde_json::Value::String(nick))))
5133 .collect::<serde_json::Map<_, _>>()
5134 .into())
5135 }
5136
5137 pub fn member_nickname(&self, community_id: &str, npub: &str) -> Option<String> {
5139 let v2 = Self::held_v2(community_id).ok()?;
5140 let member = nostr_sdk::prelude::PublicKey::parse(npub).ok()?;
5141 crate::community::v2::service::community_nicknames(&v2).ok()?.remove(&member)
5142 }
5143
5144 pub async fn set_community_nickname(&self, community_id: &str, npub: &str, nickname: &str) -> Result<()> {
5146 let v2 = Self::held_v2(community_id)?;
5147 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5148 crate::community::v2::service::set_nickname(&Self::short_transport(), &v2, &member, nickname).await.map_err(VectorError::Other)
5149 }
5150
5151 pub async fn delete_role(&self, community_id: &str, role_id: &str) -> Result<()> {
5153 let v2 = Self::held_v2(community_id)?;
5154 let transport = Self::short_transport();
5155 crate::community::v2::service::delete_role_v2(&transport, &v2, role_id).await.map_err(VectorError::Other)?;
5156 Self::converge_v2_authority(&transport, community_id).await;
5157 Ok(())
5158 }
5159
5160 pub async fn set_everyone_permissions(&self, community_id: &str, permissions: &str) -> Result<()> {
5162 let v2 = Self::held_v2(community_id)?;
5163 let perms = Self::parse_permissions(permissions)?;
5164 let transport = Self::short_transport();
5165 crate::community::v2::service::set_everyone(&transport, &v2, perms).await.map_err(VectorError::Other)?;
5166 Self::converge_v2_authority(&transport, community_id).await;
5167 Ok(())
5168 }
5169
5170 pub async fn activate_roles_v2(&self, community_id: &str, everyone: &str) -> Result<usize> {
5172 let v2 = Self::held_v2(community_id)?;
5173 let perms = Self::parse_permissions(everyone)?;
5174 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
5175 let carried = crate::community::v2::service::activate_roles_v2(&transport, &v2, perms).await.map_err(VectorError::Other)?;
5176 Self::converge_v2_authority(&transport, community_id).await;
5177 Ok(carried)
5178 }
5179
5180 pub async fn create_category(&self, community_id: &str, name: &str) -> Result<String> {
5182 let v2 = Self::held_v2(community_id)?;
5183 let id = crate::community::v2::service::create_category(&Self::short_transport(), &v2, name).await.map_err(VectorError::Other)?;
5184 Ok(crate::simd::hex::bytes_to_hex_32(&id))
5185 }
5186
5187 pub async fn rename_category(&self, community_id: &str, category_id: &str, name: &str) -> Result<()> {
5188 let v2 = Self::held_v2(community_id)?;
5189 crate::community::v2::service::rename_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?, name).await.map_err(VectorError::Other)
5190 }
5191
5192 pub async fn delete_category(&self, community_id: &str, category_id: &str) -> Result<()> {
5194 let v2 = Self::held_v2(community_id)?;
5195 crate::community::v2::service::delete_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?).await.map_err(VectorError::Other)
5196 }
5197
5198 pub async fn move_category(&self, community_id: &str, category_id: &str, index: usize) -> Result<()> {
5200 let v2 = Self::held_v2(community_id)?;
5201 crate::community::v2::service::move_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?, index).await.map_err(VectorError::Other)
5202 }
5203
5204 pub async fn move_channel(&self, community_id: &str, channel_id: &str, category_id: Option<&str>, index: usize) -> Result<()> {
5206 let v2 = Self::held_v2(community_id)?;
5207 let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
5208 let category = category_id.map(|c| Self::id32(c, "category_id")).transpose()?;
5209 crate::community::v2::service::move_channel(&Self::short_transport(), &v2, &channel, category, index).await.map_err(VectorError::Other)
5210 }
5211
5212 pub async fn edit_channel_details(&self, community_id: &str, channel_id: &str, name: &str, topic: Option<&str>, view: &str) -> Result<()> {
5214 let view = Self::view_named(view)?;
5215 let v2 = Self::held_v2(community_id)?;
5216 let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
5217 crate::community::v2::service::edit_channel_details(&Self::short_transport(), &v2, &channel, name, topic, view).await.map_err(VectorError::Other)
5218 }
5219
5220 pub async fn set_channel_private(&self, community_id: &str, channel_id: &str, private: bool) -> Result<()> {
5222 let v2 = Self::held_v2(community_id)?;
5223 let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
5224 let transport = Self::short_transport();
5225 if private {
5226 return crate::community::v2::service::privatize_channel(&transport, &v2, &channel).await.map_err(VectorError::Other);
5227 }
5228 crate::community::v2::service::publicize_channel(&transport, &v2, &channel).await.map_err(VectorError::Other)
5229 }
5230
5231 pub async fn set_member_roles(&self, community_id: &str, npub: &str, role_ids: Vec<String>) -> Result<()> {
5233 let v2 = Self::load_held(community_id)?
5234 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
5235 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5236 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5237 crate::community::v2::service::set_member_roles(&transport, &v2, &member, role_ids)
5238 .await
5239 .map_err(VectorError::Other)?;
5240 Self::converge_v2_authority_soon(community_id);
5241 Ok(())
5242 }
5243
5244 pub async fn modify_member_roles(&self, community_id: &str, npub: &str, add: &[String], remove: &[String]) -> Result<()> {
5247 let v2 = Self::load_held(community_id)?
5248 .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
5249 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5250 let (add, remove): (Vec<String>, Vec<String>) =
5251 (add.iter().map(|r| r.to_ascii_lowercase()).collect(), remove.iter().map(|r| r.to_ascii_lowercase()).collect());
5252 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5253 crate::community::v2::service::change_member_roles(&transport, &v2, &member, move |current| {
5254 let mut next: Vec<String> = current.iter().map(|r| r.to_ascii_lowercase()).filter(|r| !remove.contains(r)).collect();
5255 next.extend(add.into_iter().filter(|r| !remove.contains(r)));
5256 next
5257 })
5258 .await
5259 .map_err(VectorError::Other)?;
5260 Self::converge_v2_authority_soon(community_id);
5261 Ok(())
5262 }
5263
5264 pub fn member_has_permission(&self, community_id: &str, npub: &str, permission: u64) -> Result<bool> {
5280 use nostr_sdk::prelude::PublicKey;
5281 let who = PublicKey::parse(npub).map_err(|_| VectorError::Other(format!("invalid npub: {npub}")))?.to_hex();
5282 let owner_hex = Self::load_held(community_id)?
5283 .ok_or_else(|| VectorError::Other("community not found".into()))?
5284 .owner()
5285 .map_err(VectorError::Other)?
5286 .to_hex();
5287 if who != owner_hex && crate::db::community::get_community_banlist(community_id).unwrap_or_default().contains(&who) {
5288 return Ok(false);
5289 }
5290 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5291 Ok(roster.is_authorized(&who, Some(&owner_hex), permission))
5292 }
5293
5294 pub fn community_roles(&self, community_id: &str) -> Result<serde_json::Value> {
5297 use nostr_sdk::prelude::{PublicKey, ToBech32};
5298 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5299 let owner = v2.owner().map_err(VectorError::Other)?;
5300 let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5301 let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
5303 let admins: Vec<String> = roster.grants.iter()
5304 .filter(|g| roster.is_admin(&g.member) && !banned.contains(&g.member))
5305 .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
5306 .collect();
5307 Ok(serde_json::json!({ "owner": owner.to_bech32().ok(), "admins": admins }))
5308 }
5309
5310 fn converge_v2_authority_soon(community_id: &str) {
5314 let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(community_id).map(crate::community::CommunityId) else { return };
5315 if crate::community::v2::realtime::follow_worker_running() {
5317 crate::community::v2::realtime::enqueue_follow(&id);
5318 return;
5319 }
5320 let community_id = community_id.to_string();
5321 crate::db::spawn_bound(async move {
5322 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5323 Self::converge_v2_authority(&transport, &community_id).await;
5324 });
5325 }
5326
5327 async fn converge_v2_authority(
5336 transport: &crate::community::transport::LiveTransport,
5337 community_id: &str,
5338 ) {
5339 crate::db::scoped(async move {
5340 if let Ok(Some(fresh)) = Self::load_held(community_id) {
5343 let _ = crate::community::v2::service::follow_control(transport, &fresh).await;
5344 if let Ok(added) = crate::community::v2::service::sync_guestbook(transport, &fresh).await {
5349 if !added.is_empty() {
5350 traits::emit_event_json(
5351 "community_refreshed",
5352 serde_json::json!({ "community_id": community_id }),
5353 );
5354 }
5355 }
5356 }
5357 })
5358 .await
5359 }
5360
5361 pub async fn grant_admin(&self, community_id: &str, npub: &str) -> Result<()> {
5363 use crate::community::transport::LiveTransport;
5364 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5365 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5366 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5367 crate::community::v2::service::grant_admin(&transport, &v2, &member)
5368 .await
5369 .map_err(VectorError::Other)?;
5370 Self::converge_v2_authority(&transport, community_id).await;
5371 Ok(())
5372 }
5373
5374 pub async fn revoke_admin(&self, community_id: &str, npub: &str) -> Result<()> {
5376 use crate::community::transport::LiveTransport;
5377 let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5378 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5379 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5380 crate::community::v2::service::revoke_admin(&transport, &v2, &member)
5381 .await
5382 .map_err(VectorError::Other)?;
5383 Self::converge_v2_authority(&transport, community_id).await;
5384 Ok(())
5385 }
5386
5387 pub async fn kick_member(&self, community_id: &str, npub: &str) -> Result<()> {
5389 crate::db::scoped(async move {
5390 use crate::community::transport::LiveTransport;
5391 let pk = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
5392 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5393 let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
5394 crate::community::v2::service::kick_member(&transport, &v2, &pk)
5395 .await
5396 .map_err(VectorError::Other)?;
5397 if let Ok(fresh) = crate::community::v2::service::sync_guestbook(&transport, &v2).await {
5402 if !fresh.is_empty() {
5403 emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
5404 }
5405 }
5406 Self::converge_v2_authority(&transport, community_id).await;
5407 Ok(())
5408 })
5409 .await
5410 }
5411
5412 pub async fn set_member_banned(&self, community_id: &str, npub: &str, banned: bool) -> Result<()> {
5418 self.set_members_banned(community_id, &[npub], banned).await
5419 }
5420
5421 pub async fn set_members_banned(&self, community_id: &str, npubs: &[&str], banned: bool) -> Result<()> {
5431 use crate::community::{transport::LiveTransport, CommunityId};
5432 if npubs.is_empty() {
5433 return Ok(());
5434 }
5435 let mut pks: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(npubs.len());
5437 for n in npubs {
5438 let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5439 if !pks.contains(&pk) {
5440 pks.push(pk);
5441 }
5442 }
5443 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5444 if community_id.len() != 64 {
5448 return Err(VectorError::Other("malformed community id".into()));
5449 }
5450 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5451 crate::community::v2::service::set_members_banned(&transport, &cid, &pks, banned)
5452 .await
5453 .map_err(VectorError::Other)?;
5454 Self::invalidate_raid_report(community_id);
5457 Self::announce_ban_change(community_id);
5458 Ok(())
5459 }
5460
5461 fn announce_ban_change(community_id: &str) {
5465 emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
5466 }
5467
5468 pub async fn rescue_stranded_members(&self, community_id: &str, npubs: &[&str]) -> Result<serde_json::Value> {
5479 use nostr_sdk::prelude::PublicKey;
5480 let community = Self::load_held(community_id)?
5481 .ok_or_else(|| VectorError::Other("rescuing requires a Concord v2 community".into()))?;
5482 let mut targets: Vec<PublicKey> = Vec::with_capacity(npubs.len());
5483 for n in npubs {
5484 let pk = PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5485 if !targets.contains(&pk) {
5486 targets.push(pk);
5487 }
5488 }
5489 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
5490 let report = crate::community::v2::service::rescue_stranded_members(&transport, &community, &targets)
5491 .await
5492 .map_err(VectorError::Other)?;
5493 serde_json::to_value(report).map_err(|e| VectorError::Other(e.to_string()))
5494 }
5495
5496 pub async fn repair_community_roster(&self, community_id: &str) -> Result<serde_json::Value> {
5507 use crate::community::CommunityId;
5508 if community_id.len() != 64 {
5509 return Err(VectorError::Other("malformed community id".into()));
5510 }
5511 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5512 if crate::db::community::load_community_v2(&cid).map_err(VectorError::Other)?.is_none() {
5513 return Err(VectorError::Other("not a held Concord v2 community".into()));
5514 }
5515 let before = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5516 let before_at = crate::db::community::get_community_roles_at(community_id).map_err(VectorError::Other)?;
5517 crate::db::community::set_community_roles(community_id, &before, 0).map_err(VectorError::Other)?;
5518 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
5520 let community = crate::db::community::load_community_v2(&cid)
5521 .map_err(VectorError::Other)?
5522 .ok_or_else(|| VectorError::Other("community vanished mid-repair".into()))?;
5523 let follow = crate::community::v2::service::follow_control(&transport, &community).await;
5524 let after = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
5525 Ok(serde_json::json!({
5526 "provenance_before": before_at,
5527 "provenance_after": crate::db::community::get_community_roles_at(community_id).unwrap_or(0),
5528 "roles_before": before.roles.len(),
5529 "grants_before": before.grants.len(),
5530 "roles_after": after.roles.len(),
5531 "grants_after": after.grants.len(),
5532 "fold_error": follow.as_ref().err().cloned(),
5533 "repaired": after.grants.len() > before.grants.len(),
5534 }))
5535 }
5536
5537 pub async fn explain_epoch_state(&self, community_id: &str) -> Result<serde_json::Value> {
5547 use crate::community::{transport::LiveTransport, CommunityId};
5548 if community_id.len() != 64 {
5549 return Err(VectorError::Other("malformed community id".into()));
5550 }
5551 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5552 let community = crate::db::community::load_community_v2(&cid)
5553 .map_err(VectorError::Other)?
5554 .ok_or_else(|| VectorError::Other("not a held Concord v2 community".into()))?;
5555 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(15));
5556 crate::community::v2::service::explain_epoch_state(&transport, &community)
5557 .await
5558 .map_err(VectorError::Other)
5559 }
5560
5561 pub async fn contain_raid(
5574 &self,
5575 community_id: &str,
5576 npubs: &[&str],
5577 window_start_secs: u64,
5578 cut_also: &[&str],
5579 ) -> Result<crate::community::v2::service::ContainmentReport> {
5580 use crate::community::{transport::LiveTransport, CommunityId};
5581 if community_id.len() != 64 {
5582 return Err(VectorError::Other("malformed community id".into()));
5583 }
5584 let mut pks: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(npubs.len());
5585 for n in npubs {
5586 let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5587 if !pks.contains(&pk) {
5588 pks.push(pk);
5589 }
5590 }
5591 let mut extra: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(cut_also.len());
5592 for n in cut_also {
5593 let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
5594 if !extra.contains(&pk) {
5595 extra.push(pk);
5596 }
5597 }
5598 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5599 if !crate::db::community::community_held(&cid).map_err(VectorError::Other)? {
5600 return Err(VectorError::Other("community not found".into()));
5601 }
5602 let session = crate::db::current_session();
5605 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
5606 let report = crate::community::v2::service::contain_raid(&transport, &cid, &pks, window_start_secs, &extra)
5607 .await
5608 .map_err(VectorError::Other)?;
5609 if !session.is_live() {
5610 return Err(VectorError::Other("account changed during raid containment".into()));
5611 }
5612 Self::invalidate_raid_report(community_id);
5613 Ok(report)
5614 }
5615
5616 pub async fn dissolve_community(&self, community_id: &str) -> Result<()> {
5620 use crate::community::{transport::LiveTransport, CommunityId};
5621 if community_id.len() != 64 {
5622 return Err(VectorError::Other("malformed community id".into()));
5623 }
5624 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5625 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5626 let community = crate::db::community::load_community_v2(&cid)
5628 .map_err(VectorError::Other)?
5629 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5630 crate::community::v2::service::dissolve_community(&transport, &community)
5631 .await
5632 .map_err(VectorError::Other)?;
5633 drop_community_image(community.icon.as_ref().map(|i| i.url.clone()), None);
5635 drop_community_image(community.banner.as_ref().map(|i| i.url.clone()), community.icon.as_ref().map(|i| i.url.as_str()));
5636 Ok(())
5637 }
5638
5639 pub async fn edit_community_metadata(&self, community_id: &str, name: Option<&str>, description: Option<&str>) -> Result<()> {
5642 use crate::community::{transport::LiveTransport, CommunityId};
5643 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5644 if community_id.len() != 64 {
5648 return Err(VectorError::Other("malformed community id".into()));
5649 }
5650 let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
5651 let community = crate::db::community::load_community_v2(&cid)
5652 .map_err(VectorError::Other)?
5653 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5654 let mut meta = community.metadata();
5655 if let Some(n) = name {
5656 meta.name = n.to_string();
5657 }
5658 if let Some(d) = description {
5659 meta.description = if d.is_empty() { None } else { Some(d.to_string()) };
5660 }
5661 crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
5662 .await
5663 .map_err(VectorError::Other)
5664 }
5665
5666 pub async fn remove_community_image(&self, community_id: &str, is_banner: bool) -> Result<()> {
5669 use crate::community::{transport::LiveTransport, CommunityId};
5670 let session = crate::db::current_session();
5671 let cid = CommunityId(Self::id32(community_id, "community_id")?);
5672 let community = crate::db::community::load_community_v2(&cid)
5673 .map_err(VectorError::Other)?
5674 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5675 let mut meta = community.metadata();
5676 let gone = if is_banner { meta.banner.take() } else { meta.icon.take() };
5677 let kept = if is_banner { meta.icon.as_ref() } else { meta.banner.as_ref() }.map(|i| i.url.clone());
5678 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5679 crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
5680 .await
5681 .map_err(VectorError::Other)?;
5682 if !session.is_live() {
5684 return Err(VectorError::Other("account changed while removing the image".into()));
5685 }
5686 drop_community_image(gone.map(|i| i.url), kept.as_deref());
5687 if let Some(updated) = crate::community::v2::service::persist_community_image(&cid, None, is_banner).await {
5688 self.register_v2_chats(&updated, &session).await;
5689 }
5690 Ok(())
5691 }
5692
5693 pub async fn set_community_image(&self, community_id: &str, bytes: &[u8], is_banner: bool) -> Result<String> {
5697 let usage = if is_banner { crate::image_prep::ImageUse::Banner } else { crate::image_prep::ImageUse::Icon };
5698 let raw = bytes.to_vec();
5699 let prepared = crate::rt::spawn_blocking(move || crate::image_prep::prepare(&raw, usage))
5700 .await
5701 .map_err(|e| VectorError::Other(format!("image preparation stopped: {e}")))?
5702 .map_err(VectorError::Other)?;
5703 self.publish_community_image(community_id, prepared.bytes, prepared.extension, is_banner, None).await
5704 }
5705
5706 pub async fn publish_community_image(
5709 &self,
5710 community_id: &str,
5711 bytes: Vec<u8>,
5712 extension: &str,
5713 is_banner: bool,
5714 progress: Option<crate::blossom::ProgressCallback>,
5715 ) -> Result<String> {
5716 use crate::community::{transport::LiveTransport, CommunityId};
5717 let session = crate::db::current_session();
5718 let cid = CommunityId(Self::id32(community_id, "community_id")?);
5719 crate::db::community::load_community_v2(&cid)
5720 .map_err(VectorError::Db)?
5721 .ok_or_else(|| VectorError::NotFound("community".into()))?;
5722 if crate::svg::looks_like_svg(&bytes) {
5723 return Err(VectorError::Other(crate::community::SVG_REFUSED.to_string()));
5724 }
5725 let hash = crate::crypto::sha256_hex(&bytes);
5726 let params = crate::crypto::generate_encryption_params();
5728 let encrypted = crate::crypto::encrypt_data(&bytes, ¶ms).map_err(VectorError::Other)?;
5729 let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("signer: {e}")))?;
5730 let servers = state::get_blossom_servers();
5731 if servers.is_empty() {
5732 return Err(VectorError::Other("no Blossom servers configured".into()));
5733 }
5734 let progress = progress.unwrap_or_else(|| std::sync::Arc::new(|_, _| Ok(())));
5735 let url = crate::blossom::upload_blob_with_progress_and_failover(
5736 signer,
5737 servers,
5738 std::sync::Arc::new(encrypted),
5739 Some("application/octet-stream"),
5740 true,
5741 progress,
5742 None,
5743 None,
5744 None,
5745 )
5746 .await
5747 .map_err(VectorError::Other)?
5748 .url;
5749 let mut extra = serde_json::Map::new();
5750 extra.insert("ext".into(), serde_json::Value::String(extension.to_string()));
5751 let image = crate::community::v2::control::ImageRef { url: url.clone(), key: params.key.clone(), nonce: params.nonce.clone(), hash, extra };
5752 if !session.is_live() {
5754 return Err(VectorError::Other("account changed while setting the image".into()));
5755 }
5756 let community = crate::db::community::load_community_v2(&cid)
5759 .map_err(VectorError::Db)?
5760 .ok_or_else(|| VectorError::NotFound("community".into()))?;
5761 let mut meta = community.metadata();
5762 let replaced = if is_banner { meta.banner.replace(image.clone()) } else { meta.icon.replace(image.clone()) };
5763 let kept = if is_banner { meta.icon.as_ref() } else { meta.banner.as_ref() }.map(|i| i.url.clone());
5764 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5765 crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
5766 .await
5767 .map_err(VectorError::Other)?;
5768 if !session.is_live() {
5769 return Err(VectorError::Other("account changed while setting the image".into()));
5770 }
5771 drop_community_image(replaced.map(|i| i.url).filter(|u| *u != url), kept.as_deref());
5772 if let Some(updated) = crate::community::v2::service::persist_community_image(&cid, Some(image), is_banner).await {
5773 self.register_v2_chats(&updated, &session).await;
5774 }
5775 Ok(url)
5776 }
5777
5778 pub async fn community_image(&self, community_id: &str, is_banner: bool) -> Result<Option<Vec<u8>>> {
5781 use crate::community::CommunityId;
5782 let cid = CommunityId(Self::id32(community_id, "community_id")?);
5783 let community = crate::db::community::load_community_v2(&cid)
5784 .map_err(VectorError::Other)?
5785 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5786 let Some(image) = (if is_banner { community.banner } else { community.icon }) else {
5787 return Ok(None);
5788 };
5789 let cap: usize = if is_banner { 16 } else { 10 } * 1024 * 1024;
5790 crate::net::validate_url_not_private(&image.url).map_err(|e| VectorError::Network(format!("community image URL refused: {e}")))?;
5792 let client = crate::net::build_http_client(std::time::Duration::from_secs(30)).map_err(VectorError::Network)?;
5793 let resp = crate::net::proxied_request(&client, reqwest::Method::GET, &image.url)
5794 .await
5795 .send()
5796 .await
5797 .map_err(|e| VectorError::Network(format!("download: {e}")))?;
5798 if !resp.status().is_success() {
5799 return Err(VectorError::Network(format!("download failed: HTTP {}", resp.status())));
5800 }
5801 let mut encrypted: Vec<u8> = Vec::with_capacity(resp.content_length().map_or(64 * 1024, |l| (l as usize).min(cap)));
5802 let mut body = resp.bytes_stream();
5803 while let Some(chunk) = futures_util::StreamExt::next(&mut body).await {
5804 let chunk = chunk.map_err(|e| VectorError::Network(format!("read body: {e}")))?;
5805 if encrypted.len() + chunk.len() > cap {
5806 return Err(VectorError::Other("community image too large".into()));
5807 }
5808 encrypted.extend_from_slice(&chunk);
5809 }
5810 let plain = crate::crypto::decrypt_data_owned(encrypted, &image.key, &image.nonce).map_err(VectorError::Crypto)?;
5811 if crate::crypto::sha256_hex(&plain) != image.hash {
5812 return Err(VectorError::Crypto("community image failed its integrity check".into()));
5813 }
5814 if crate::svg::looks_like_svg(&plain) {
5815 return Err(VectorError::Other(crate::community::SVG_REFUSED.to_string()));
5816 }
5817 Ok(Some(plain))
5818 }
5819
5820 pub async fn set_voice_relays(&self, community_id: &str, relays: &[String]) -> Result<Vec<String>> {
5823 use crate::community::{transport::LiveTransport, CommunityId};
5824 let cid = CommunityId(Self::id32(community_id, "community_id")?);
5825 let community = crate::db::community::load_community_v2(&cid)
5826 .map_err(VectorError::Other)?
5827 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5828 let mut clean: Vec<String> = Vec::new();
5829 for r in relays.iter().map(|r| r.trim().trim_end_matches('/').to_string()).filter(|r| !r.is_empty()) {
5830 let parsed = url::Url::parse(&r).map_err(|_| VectorError::Other(format!("{r} isn't a relay address")))?;
5831 if parsed.scheme() != "https" || parsed.host_str().is_none() {
5832 return Err(VectorError::Other(format!("{r}: a voice relay is an https:// address")));
5833 }
5834 let normal = format!("{}/", parsed.as_str().trim_end_matches('/'));
5835 if !clean.contains(&normal) {
5836 clean.push(normal);
5837 }
5838 }
5839 if clean.len() > crate::community::v2::community::MAX_VOICE_RELAYS {
5840 return Err(VectorError::Other(format!("at most {} voice relays", crate::community::v2::community::MAX_VOICE_RELAYS)));
5841 }
5842 let mut meta = community.metadata();
5843 if clean.is_empty() {
5844 meta.extra.remove("voice_relays");
5845 } else {
5846 meta.extra.insert("voice_relays".into(), serde_json::json!(clean));
5847 }
5848 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5849 crate::community::v2::service::edit_community_metadata(&transport, &community, &meta).await.map_err(VectorError::Other)?;
5850 Ok(clean)
5851 }
5852
5853 pub async fn set_system_channel(&self, community_id: &str, channel_id: Option<&str>) -> Result<()> {
5856 use crate::community::{transport::LiveTransport, ChannelId, CommunityId};
5857 let cid = CommunityId(Self::id32(community_id, "community_id")?);
5858 let community = crate::db::community::load_community_v2(&cid)
5859 .map_err(VectorError::Other)?
5860 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5861 let named = match channel_id {
5862 Some(ch) => {
5863 let id = ChannelId(Self::id32(ch, "channel_id")?);
5864 let channel = community.channel(&id).ok_or_else(|| VectorError::Other("no such channel in this community".into()))?;
5865 if !crate::community::v2::community::takes_system_lines(channel) {
5866 return Err(VectorError::Other("join and leave messages go to a chat channel".into()));
5867 }
5868 Some(id)
5869 }
5870 None => None,
5871 };
5872 let mut meta = community.metadata();
5873 crate::community::v2::community::set_system_channel_in(&mut meta, named.as_ref());
5874 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5875 crate::community::v2::service::edit_community_metadata(&transport, &community, &meta).await.map_err(VectorError::Other)
5876 }
5877
5878 pub async fn set_landing_channel(&self, community_id: &str, channel_id: Option<&str>) -> Result<()> {
5880 use crate::community::{transport::LiveTransport, ChannelId, CommunityId};
5881 let cid = CommunityId(Self::id32(community_id, "community_id")?);
5882 let community = crate::db::community::load_community_v2(&cid)
5883 .map_err(VectorError::Other)?
5884 .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
5885 let named = match channel_id {
5886 Some(ch) => {
5887 let id = ChannelId(Self::id32(ch, "channel_id")?);
5888 let channel = community.channel(&id).ok_or_else(|| VectorError::Other("no such channel in this community".into()))?;
5889 if !crate::community::v2::community::can_land_in(channel) {
5890 return Err(VectorError::Other("new members start in a public text or forum channel".into()));
5891 }
5892 Some(id)
5893 }
5894 None => None,
5895 };
5896 let mut meta = community.metadata();
5897 crate::community::v2::community::set_landing_channel_in(&mut meta, named.as_ref());
5898 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5899 crate::community::v2::service::edit_community_metadata(&transport, &community, &meta).await.map_err(VectorError::Other)
5900 }
5901
5902 pub async fn leave_community(&self, community_id: &str) -> Result<()> {
5905 crate::db::scoped(async move {
5906 use crate::community::transport::LiveTransport;
5907 if community_id.len() != 64 {
5908 return Err(VectorError::Other("malformed community id".into()));
5909 }
5910 use crate::community::v2::service;
5911 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5912 let Some(v2) = Self::load_held(community_id)? else {
5913 let cid = Self::unheld_id(community_id)?;
5914 let at_ms = service::leave_unheld_locally(&cid).await.ok_or_else(|| VectorError::Other("community not found".into()))?;
5915 service::announce_unheld_leave(&transport, &cid, at_ms).await;
5916 return Ok(());
5917 };
5918 let channel_ids: Vec<String> =
5920 v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
5921 service::leave_community(&transport, &v2).await.map_err(VectorError::Other)?;
5922 service::forget_community_chats(&crate::simd::hex::bytes_to_hex_32(&v2.id().0), &channel_ids).await;
5923 Ok(())
5924 })
5925 .await
5926 }
5927
5928 pub async fn leave_community_now(&self, community_id: &str) -> Result<()> {
5932 crate::db::scoped(async move {
5933 use crate::community::v2::service;
5934 let Some(v2) = Self::load_held(community_id)? else {
5935 let cid = Self::unheld_id(community_id)?;
5936 let at_ms = service::leave_unheld_locally(&cid).await.ok_or_else(|| VectorError::Other("community not found".into()))?;
5937 crate::db::spawn_bound(async move {
5938 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5939 service::announce_unheld_leave(&transport, &cid, at_ms).await;
5940 });
5941 return Ok(());
5942 };
5943 let channel_ids: Vec<String> =
5944 v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
5945 let at_ms = service::leave_locally(&v2).map_err(VectorError::Other)?;
5946 service::forget_community_chats(&crate::simd::hex::bytes_to_hex_32(&v2.id().0), &channel_ids).await;
5947 crate::db::spawn_bound(async move {
5948 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
5949 service::announce_leave(&transport, &v2, at_ms).await;
5950 if let Some(client) = state::nostr_client() {
5951 crate::community::v2::realtime::refresh_subscription(&client).await;
5952 }
5953 crate::community::transport::prune_unneeded_community_relays(&v2.relays).await;
5955 });
5956 Ok(())
5957 })
5958 .await
5959 }
5960
5961 pub async fn decline_community_invite(&self, community_id: &str) -> Result<()> {
5965 crate::db::scoped(async move {
5966 use crate::db::community as db;
5967 let bundle = db::get_pending_invite(community_id)
5969 .ok()
5970 .flatten()
5971 .and_then(|j| crate::community::v2::invite::CommunityInvite::from_bundle_json(&j).ok());
5972 let relays: Vec<String> = bundle.as_ref().map(|b| b.relays.clone()).unwrap_or_default();
5973 let wraps = db::pending_invite_wraps(community_id).unwrap_or_default();
5974 db::delete_pending_invite(community_id).map_err(VectorError::Other)?;
5975 if let Some(cid) = bundle.and_then(|_| crate::simd::hex::hex_to_bytes_32_checked(community_id)) {
5976 let removed_at = crate::clock::now_ms();
5977 crate::community::v2::service::tombstone_community_list_durable(crate::community::CommunityId(cid), relays.clone(), removed_at);
5978 }
5979 for wrap in wraps.iter().filter_map(|w| nostr_sdk::prelude::EventId::from_hex(w).ok()) {
5980 crate::deletion::delete_received_wrap(wrap);
5981 }
5982 if !relays.is_empty() {
5983 crate::community::transport::prune_unneeded_community_relays(&relays).await;
5984 }
5985 Ok(())
5986 })
5987 .await
5988 }
5989
5990 pub async fn sync_dms(
6007 &self,
6008 since_days: Option<u64>,
6009 handler: &dyn InboundEventHandler,
6010 ) -> Result<(u32, u32)> {
6011 crate::db::scoped(async move {
6012 use futures_util::StreamExt;
6013 use nostr_sdk::prelude::*;
6014
6015 let client = state::nostr_client()
6016 .ok_or(VectorError::Other("Not connected".into()))?;
6017 let my_pk = state::my_public_key()
6018 .ok_or(VectorError::Other("Not logged in".into()))?;
6019
6020 let (items, filter) = if let Some(days) = since_days {
6025 let since_ts = crate::clock::timestamp().as_secs().saturating_sub(days * 24 * 3600);
6026 let items = db::wrappers::load_negentropy_items_since(since_ts)
6027 .unwrap_or_default();
6028 let filter = Filter::new()
6029 .pubkey(my_pk)
6030 .kind(Kind::GiftWrap)
6031 .since(Timestamp::from_secs(since_ts));
6032 (items, filter)
6033 } else {
6034 let items = db::wrappers::load_negentropy_items().unwrap_or_default();
6035 let filter = Filter::new()
6036 .pubkey(my_pk)
6037 .kind(Kind::GiftWrap);
6038 (items, filter)
6039 };
6040
6041 log_info!("[SyncDMs] {} negentropy items, since_days={:?}", items.len(), since_days);
6042 let items = std::sync::Arc::new(items);
6043
6044 let sync_opts = nostr_sdk::prelude::SyncOptions::new()
6046 .direction(nostr_sdk::prelude::SyncDirection::Down)
6047 .initial_timeout(relay_request_timeout(std::time::Duration::from_secs(10)))
6048 .dry_run();
6049
6050 let relay_map = client.relays().await;
6054 let (all_relays, no_neg_relays): (Vec<_>, Vec<_>) =
6055 relay_map.iter()
6056 .map(|(url, relay)| (url.clone(), relay.clone()))
6057 .partition(|(url, _)| negentropy::neg_supported_cached(url.as_str()) != Some(false));
6058 drop(relay_map);
6059 let skipped_no_neg: Vec<String> = no_neg_relays.iter().map(|(u, _)| u.to_string()).collect();
6060 if !skipped_no_neg.is_empty() {
6061 log_info!("[SyncDMs] {} relay(s) on REQ path (no NIP-77)", skipped_no_neg.len());
6062 }
6063
6064 let neg_budget = relay_request_timeout(std::time::Duration::from_secs(10));
6068 let neg_outer = neg_budget + std::time::Duration::from_secs(5);
6069 let connect_allowance = relay_request_timeout(std::time::Duration::from_secs(3))
6070 .min(neg_outer);
6071 let mut relay_futs = futures_util::stream::FuturesUnordered::new();
6072 for (url, relay) in &all_relays {
6073 let url = url.clone();
6074 let relay = relay.clone();
6075 let f = filter.clone();
6076 let i = items.clone();
6077 let o = sync_opts.clone();
6078 relay_futs.push(async move {
6079 if !negentropy::wait_connected(&relay, connect_allowance).await {
6080 return (url, None, false);
6081 }
6082 let result = crate::rt::time::timeout(
6085 neg_outer,
6086 relay.sync(f).items(i.iter().copied()).opts(o),
6087 ).await;
6088 let connected = relay.status() == RelayStatus::Connected;
6089 (url, Some(result), connected)
6090 });
6091 }
6092
6093 let cap_session = crate::db::current_session();
6095 let mut all_missing: std::collections::HashSet<EventId> = std::collections::HashSet::new();
6096 while let Some((url, result, connected)) = relay_futs.next().await {
6097 let Some(result) = result else {
6098 log_warn!("[SyncDMs] {} skipped: not connected", url);
6099 continue;
6100 };
6101 match result {
6102 Ok(Ok(recon)) => {
6103 let count = recon.remote.len();
6104 all_missing.extend(recon.remote);
6105 log_info!("[SyncDMs] {} reconciled: {} missing", url, count);
6106 negentropy::record_neg_support(url.as_str(), true);
6107 }
6108 Ok(Err(e)) => {
6109 log_warn!("[SyncDMs] {} failed: {}", url, e);
6110 if cap_session.is_live()
6111 && negentropy::classify_neg_sync_error(&e.to_string(), connected && !negentropy::neg_ever_confirmed(url.as_str())) == Some(false)
6112 {
6113 log_info!("[SyncDMs] {} marked no-NIP-77 for 24h", url);
6114 negentropy::record_neg_support(url.as_str(), false);
6115 }
6116 }
6117 Err(_) => log_warn!("[SyncDMs] {} timed out ({:?})", url, neg_outer),
6118 }
6119 }
6120
6121 let mut total_events = 0u32;
6122 let mut new_messages = 0u32;
6123
6124 if !skipped_no_neg.is_empty() {
6129 let req_filter = filter.clone().limit(500);
6130 match client
6131 .stream_events(nostr_sdk::prelude::ReqTarget::manual(
6132 skipped_no_neg.iter().cloned().map(|u| (u, vec![req_filter.clone()])),
6133 ))
6134 .timeout(relay_request_timeout(std::time::Duration::from_secs(20)))
6135 .await
6136 {
6137 Ok(stream) => {
6138 let mut seen: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
6139 let stream = stream.ready_chunks(event_handler::UNWRAP_BATCH);
6140 tokio::pin!(stream);
6141 while let Some(chunk) = stream.next().await {
6142 let events: Vec<Event> = chunk
6146 .into_iter()
6147 .filter_map(|(_relay, res)| res.ok())
6148 .filter(|event| seen.insert(event.id.to_bytes()))
6149 .collect();
6150 total_events += events.len() as u32;
6151 for prepared in event_handler::prepare_events(&events, my_pk).await {
6152 if event_handler::commit_prepared_event(prepared, false, handler).await {
6153 new_messages += 1;
6154 }
6155 }
6156 }
6157 }
6158 Err(e) => log_warn!("[SyncDMs] REQ pass failed: {}", e),
6159 }
6160 }
6161
6162 if all_missing.is_empty() {
6163 log_info!("[SyncDMs] No missing events");
6164 return Ok((total_events, new_messages));
6165 }
6166
6167 log_info!("[SyncDMs] Fetching {} missing events", all_missing.len());
6169 let ids: Vec<EventId> = all_missing.into_iter().collect();
6170 let relay_strs: Vec<String> = client.relays().await.keys()
6171 .map(|u| u.to_string()).collect();
6172
6173 const BATCH_SIZE: usize = 500;
6174
6175 for batch in ids.chunks(BATCH_SIZE) {
6176 let f = Filter::new().ids(batch.to_vec()).kind(Kind::GiftWrap).pubkey(my_pk);
6179 match client
6180 .stream_events(nostr_sdk::prelude::ReqTarget::manual(
6181 relay_strs.iter().cloned().map(|u| (u, vec![f.clone()])),
6182 ))
6183 .timeout(std::time::Duration::from_secs(30))
6184 .await
6185 {
6186 Ok(stream) => {
6187 let prepared_stream = stream
6188 .filter_map(|(_relay, res)| async move { res.ok() })
6189 .ready_chunks(event_handler::UNWRAP_BATCH)
6190 .map(move |events| {
6191 db::spawn_bound(async move {
6192 event_handler::prepare_events(&events, my_pk).await
6193 })
6194 })
6195 .buffer_unordered(8);
6196 tokio::pin!(prepared_stream);
6197
6198 while let Some(result) = prepared_stream.next().await {
6199 let Ok(batch) = result else { continue };
6200 total_events += batch.len() as u32;
6201 for prepared in batch {
6202 if event_handler::commit_prepared_event(prepared, false, handler).await {
6203 new_messages += 1;
6204 }
6205 }
6206 }
6207 }
6208 Err(e) => log_warn!("[SyncDMs] Batch fetch error: {}", e),
6209 }
6210 }
6211
6212 log_info!("[SyncDMs] Complete: {} events processed, {} new messages", total_events, new_messages);
6213 Ok((total_events, new_messages))
6214 })
6215 .await
6216 }
6217
6218 pub async fn subscribe_dms(&self) -> Result<nostr_sdk::prelude::SubscriptionId> {
6227 use nostr_sdk::prelude::*;
6228 let client = state::nostr_client()
6229 .ok_or(VectorError::Other("Not connected".into()))?;
6230 let my_pk = state::my_public_key()
6231 .ok_or(VectorError::Other("Not logged in".into()))?;
6232
6233 let filter = Filter::new()
6234 .pubkey(my_pk)
6235 .kind(Kind::GiftWrap)
6236 .limit(0);
6237
6238 let output = client.subscribe(filter.clone()).await
6239 .map_err(|e| VectorError::Nostr(e.to_string()))?;
6240 live_subs::keep_output(&output, vec![filter]);
6241 Ok(output.value)
6242 }
6243
6244 pub async fn sync_communities(&self) -> Result<Vec<String>> {
6258 let mut all_warnings: Vec<String> = Vec::new();
6259 {
6263 use crate::community::{transport::LiveTransport, v2::service as v2};
6264 let bootstrap: Vec<String> = match crate::state::nostr_client() {
6265 Some(client) => client.relays().await.keys().map(|r| r.to_string()).collect(),
6266 None => Vec::new(),
6267 };
6268 let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
6269 if let Ok(outcome) = v2::sync_community_list(&transport, &bootstrap).await {
6270 let joined = outcome.joined;
6273 for c in &joined {
6274 if community::v2::realtime::follow_worker_running() {
6275 community::v2::realtime::enqueue_follow(c.id());
6276 } else {
6277 let cid_hex = crate::simd::hex::bytes_to_hex_32(&c.id().0);
6278 all_warnings.extend(
6279 Self::v2_inline_follow(c.id()).await.into_iter().map(|w| format!("{}: {w}", &cid_hex[..8])),
6280 );
6281 }
6282 }
6283 if !joined.is_empty() {
6284 if let Some(client) = crate::state::nostr_client() {
6285 community::v2::realtime::refresh_subscription(&client).await;
6286 }
6287 }
6288 }
6289 }
6290
6291 let ids = db::community::list_community_ids().map_err(VectorError::from)?;
6292 for id in ids {
6293 if community::v2::realtime::follow_worker_running() {
6296 community::v2::realtime::enqueue_follow(&id);
6297 } else {
6298 let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
6299 all_warnings.extend(
6300 Self::v2_inline_follow(&id).await.into_iter().map(|w| format!("{}: {w}", &cid_hex[..8])),
6301 );
6302 }
6303 if let Ok(Some(c)) = db::community::load_community_v2(&id) {
6309 for ch in &c.channels {
6310 let hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
6311 let _ = Self::v2_backfill_channel(
6312 &id, &hex, 50, 2, None, None,
6313 crate::community::transport::Evidence::Fast, 12,
6314 ).await;
6315 }
6316 }
6317 }
6318 Ok(all_warnings)
6319 }
6320
6321
6322 pub async fn listen(&self, handler: Arc<dyn InboundEventHandler>) -> Result<()> {
6354 self.listen_with(handler, CatchUp::Inline).await
6355 }
6356
6357 pub async fn listen_with(&self, handler: Arc<dyn InboundEventHandler>, catch_up: CatchUp) -> Result<()> {
6359 use nostr_sdk::prelude::*;
6360
6361 let client = state::nostr_client()
6362 .ok_or(VectorError::Other("Not connected".into()))?;
6363 let my_pk = state::my_public_key()
6364 .ok_or(VectorError::Other("Not logged in".into()))?;
6365
6366 community::v2::streamauth::ensure_responder(&client);
6373
6374 let listening_since = crate::clock::now_ms();
6377 let inline = catch_up == CatchUp::Inline;
6378 if inline {
6379 news::begin(handler.clone(), listening_since);
6380 } else {
6381 news::end();
6382 }
6383 let live_from = news::cutoff().unwrap_or(listening_since);
6384
6385 if handler.wants_community_changes() {
6389 community::v2::changes::prime_all(&*handler);
6390 }
6391
6392 community::v2::realtime::spawn_follow_worker(handler.clone());
6395 early::start(handler.clone());
6396
6397 let notifications = client.notifications();
6404 let dm_sub_id = self.subscribe_dms().await?;
6405 live_subs::watch(&client);
6406 let (live_tx, mut live_rx) = tokio::sync::mpsc::channel::<(LiveRoute, Box<nostr_sdk::prelude::Event>)>(4096);
6407 let dm_sid = dm_sub_id.clone();
6408 db::spawn_bound(async move {
6409 let mut notifications = notifications;
6410 while let Some(notification) = notifications.next().await {
6411 if let nostr_sdk::prelude::ClientNotification::Message { message, .. } = ¬ification {
6415 if let nostr_sdk::prelude::RelayMessage::Ok { event_id, status, .. } = &**message {
6416 sending::note_relay_ok(event_id, *status);
6417 }
6418 }
6419 let nostr_sdk::prelude::ClientNotification::Event { event, subscription_id, .. } = notification else { continue };
6420 let route = if subscription_id == dm_sid {
6421 LiveRoute::Dm
6422 } else if community::v2::realtime::routes_live(&subscription_id) {
6423 LiveRoute::CommunityV2
6424 } else {
6425 continue;
6426 };
6427 if live_tx.send((route, event)).await.is_err() {
6428 break;
6429 }
6430 }
6431 });
6432
6433 if inline {
6441 let _ = self.sync_communities().await;
6442 let _ = self.sync_dms(None, &event_handler::LiveOnly::from(&*handler, live_from)).await;
6443 }
6444
6445 community::v2::realtime::refresh_subscription(&client).await;
6448
6449 if inline {
6452 Self::owe_catch_up(false, false, [(EVERY_RELAY.to_string(), live_from)]);
6453 live_subs::set_catch_up(|what| {
6456 let now = crate::clock::now_ms();
6457 match what {
6458 live_subs::CatchUp::All { away_ms } => Self::owe_catch_up(true, true, [(EVERY_RELAY.to_string(), now.saturating_sub(away_ms))]),
6459 live_subs::CatchUp::Relay(url) => Self::owe_catch_up(false, false, [(url, now.saturating_sub(live_subs::MAX_BACKOFF.as_millis() as u64))]),
6460 }
6461 });
6462 #[cfg(not(target_arch = "wasm32"))]
6463 live_subs::start_wake_watch();
6464 }
6465
6466 handler.on_subscription_ready(db::community::list_community_ids().map(|v| v.len()).unwrap_or(0));
6472
6473 if let Some(monitor) = client.monitor().filter(|_| catch_up == CatchUp::Inline) {
6480 let mut rx = monitor.subscribe();
6481 let pool = client.clone();
6482 db::spawn_bound(async move {
6483 let mut down: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
6486 for (url, relay) in pool.relays().await {
6487 if relay.status() != RelayStatus::Connected {
6488 down.insert(url.to_string(), live_from);
6489 }
6490 }
6491 loop {
6492 match rx.recv().await {
6493 Ok(MonitorNotification::StatusChanged { relay_url, status }) => {
6494 let url = relay_url.to_string();
6495 match status {
6496 RelayStatus::Disconnected | RelayStatus::Terminated => {
6497 down.entry(url).or_insert_with(crate::clock::now_ms);
6498 }
6499 RelayStatus::Connected => {
6501 if let Some(since) = down.remove(&url) {
6502 VectorCore::owe_catch_up(true, true, [(url, since)]);
6503 }
6504 }
6505 _ => {}
6506 }
6507 }
6508 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
6510 VectorCore::owe_catch_up(true, true, [(EVERY_RELAY.to_string(), crate::clock::now_ms().saturating_sub(30 * 60_000))]);
6511 }
6512 Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
6513 }
6514 }
6515 });
6516 }
6517
6518 {
6522 let client_health = client.clone();
6523 db::spawn_bound(async move {
6524 crate::rt::time::sleep(std::time::Duration::from_secs(30)).await; let heard = std::sync::Mutex::new(std::collections::HashMap::<RelayUrl, usize>::new());
6528 loop {
6529 let budget = relay_request_timeout(std::time::Duration::from_secs(8));
6532 let client_health = &client_health;
6533 let heard = &heard;
6534 futures_util::future::join_all(client_health.relays().await.into_iter().map(|(url, relay)| async move {
6535 match relay.status() {
6536 RelayStatus::Connected => {
6537 let received = relay.stats().bytes_received();
6538 let before = heard.lock().unwrap().insert(url.clone(), received);
6539 if before.is_some_and(|b| received > b) {
6540 return;
6541 }
6542 let probe = crate::rt::time::timeout(
6544 budget + std::time::Duration::from_secs(2),
6545 client_health
6546 .fetch_events(nostr_sdk::prelude::ReqTarget::single(
6547 url.to_string(),
6548 [Filter::new().id(EventId::from_byte_array([0; 32]))],
6549 ))
6550 .timeout(budget),
6551 )
6552 .await;
6553 heard.lock().unwrap().insert(url.clone(), relay.stats().bytes_received());
6554 if !matches!(probe, Ok(Ok(_))) {
6555 relay.disconnect();
6556 crate::rt::time::sleep(std::time::Duration::from_millis(500)).await;
6557 let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
6558 }
6559 }
6560 RelayStatus::Terminated | RelayStatus::Disconnected => {
6561 let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
6562 }
6563 _ => {}
6564 }
6565 })).await;
6566 crate::rt::time::sleep(std::time::Duration::from_secs(60)).await;
6567 }
6568 });
6569 }
6570
6571 let client_for_closure = client.clone();
6572
6573 while let Some((route, event)) = live_rx.recv().await {
6576 match route {
6577 LiveRoute::Dm => {
6579 let prepared = event_handler::prepare_event(*event, &client_for_closure, my_pk).await;
6580 event_handler::commit_prepared_event(prepared, true, &*handler).await;
6581 }
6582 LiveRoute::CommunityV2 => community::v2::realtime::dispatch_event(*event, handler.clone()).await,
6584 }
6585 }
6586
6587 news::end();
6588 Ok(())
6589 }
6590
6591 pub(crate) fn owe_live_replay(since_ms: u64) {
6593 Self::owe_catch_up(false, false, [(EVERY_RELAY.to_string(), since_ms)]);
6594 }
6595
6596 pub(crate) fn owe_catch_up(communities: bool, dms: bool, relays: impl IntoIterator<Item = (String, u64)>) {
6600 if news::listening_since().is_none() {
6601 return;
6602 }
6603 let session = db::current_session_id();
6604 let start = {
6605 let mut owed = CATCH_UPS.lock().unwrap_or_else(|e| e.into_inner());
6606 if owed.session != session {
6607 *owed = Owed { session, ..Owed::default() };
6608 }
6609 owed.communities |= communities;
6610 owed.dms |= dms;
6611 for (relay, since) in relays {
6612 let at = owed.relays.entry(relay).or_insert(since);
6613 *at = (*at).min(since);
6614 }
6615 !std::mem::replace(&mut owed.running, true)
6616 };
6617 if start {
6618 db::spawn_bound(Self::run_catch_ups(session));
6619 }
6620 }
6621
6622 async fn run_catch_ups(session: u64) {
6623 loop {
6624 crate::rt::time::sleep(std::time::Duration::from_secs(1)).await;
6626 let listener = news::listener().zip(news::cutoff());
6627 let owed = {
6628 let mut owed = CATCH_UPS.lock().unwrap_or_else(|e| e.into_inner());
6629 let nothing = !owed.communities && !owed.dms && owed.relays.is_empty();
6630 if owed.session != session || nothing || listener.is_none() {
6631 owed.running = false;
6632 return;
6633 }
6634 std::mem::replace(&mut *owed, Owed { session, running: true, ..Owed::default() })
6635 };
6636 let Some((handler, from)) = listener else { return };
6637 if owed.communities {
6638 let _ = VectorCore.sync_communities().await;
6639 }
6640 if owed.dms {
6641 let _ = VectorCore.sync_dms(None, &event_handler::LiveOnly::from(&*handler, from)).await;
6642 }
6643 if let Some(client) = state::nostr_client() {
6644 if owed.communities {
6645 community::v2::realtime::refresh_subscription(&client).await;
6646 }
6647 for (relay, since) in owed.relays {
6648 let since = since.saturating_sub(news::ALLOWANCE_MS).max(from);
6649 let only = (relay != EVERY_RELAY).then_some(relay.as_str());
6650 community::v2::realtime::replay(&client, nostr_sdk::prelude::Timestamp::from_secs(since / 1000), only, handler.clone()).await;
6651 }
6652 }
6653 }
6654 }
6655
6656 pub async fn logout(&self) {
6658 news::end();
6659 if let Some(client) = state::nostr_client() {
6660 let _ = client.disconnect().await;
6661 }
6662 db::close_database();
6663 }
6664
6665 pub async fn swap_session(&self) {
6673 state::clear_message_tombstones();
6675 news::end();
6676
6677 #[cfg(feature = "xdc")]
6680 crate::xdc::session::leave_all(std::time::Duration::from_secs(4)).await;
6681 #[cfg(feature = "calls")]
6683 crate::calls::voice::leave().await;
6684
6685 if let Some(client) = state::take_nostr_client() {
6688 let _ = client.shutdown().await;
6689 }
6690 db::close_database();
6691
6692 state::ENCRYPTION_KEY.clear(&[&state::MY_SECRET_KEY]);
6694 state::MY_SECRET_KEY.clear(&[&state::ENCRYPTION_KEY]);
6695 {
6696 use zeroize::Zeroize;
6697 if let Ok(mut g) = state::MNEMONIC_SEED.lock() {
6698 if let Some(s) = g.as_mut() { s.zeroize(); }
6699 *g = None;
6700 }
6701 if let Ok(mut g) = state::PENDING_NSEC.lock() {
6702 if let Some(s) = g.as_mut() { s.zeroize(); }
6703 *g = None;
6704 }
6705 }
6706
6707 crate::community::v2::realtime::clear().await;
6715 crate::community::transport::clear_plane_pool();
6718 }
6719}
6720
6721#[cfg(test)]
6722mod catch_up_tests {
6723 use super::*;
6724
6725 #[tokio::test]
6726 async fn what_a_listener_is_owed_merges_and_runs_once() {
6727 let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
6728 *CATCH_UPS.lock().unwrap() = Owed::default();
6729 VectorCore::owe_catch_up(true, false, [("wss://a".to_string(), 100)]);
6730 assert!(!CATCH_UPS.lock().unwrap().running, "nobody listening: nothing owed");
6731
6732 let _listening = news::listen_for_test(Arc::new(event_handler::NoOpEventHandler), crate::clock::now_ms());
6733 VectorCore::owe_catch_up(false, false, [("wss://a".to_string(), 100)]);
6734 VectorCore::owe_catch_up(false, true, [("wss://a".to_string(), 50), ("wss://b".to_string(), 70)]);
6735 let owed = CATCH_UPS.lock().unwrap();
6736 assert!(owed.running && owed.dms && !owed.communities);
6737 assert_eq!((owed.relays.get("wss://a"), owed.relays.get("wss://b")), (Some(&50), Some(&70)), "each relay from its earliest gap");
6738 }
6739}
6740
6741fn page_before(
6746 held: &[compact::CompactMessage],
6747 interner: &compact::NpubInterner,
6748 before: Option<(u64, &str)>,
6749 limit: usize,
6750) -> Vec<Message> {
6751 let (lo, mut msgs) = match before {
6752 None => (held.len(), Vec::new()),
6753 Some((at, id)) => {
6754 let lo = held.partition_point(|m| m.at < at);
6755 let hi = held.partition_point(|m| m.at <= at);
6756 let tie = held[lo..hi].iter().map(|m| m.to_message(interner)).filter(|m| m.id.as_str() < id).collect();
6757 (lo, tie)
6758 }
6759 };
6760 let mut start = lo.saturating_sub(limit.saturating_sub(msgs.len()));
6761 while start > 0 && start < lo && held[start - 1].at == held[start].at {
6762 start -= 1;
6763 }
6764 msgs.extend(held[start..lo].iter().map(|m| m.to_message(interner)));
6765 msgs.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
6766 if msgs.len() > limit {
6767 msgs.drain(..msgs.len() - limit);
6768 }
6769 msgs
6770}
6771
6772#[cfg(test)]
6773mod page_before_tests {
6774 use super::*;
6775
6776 #[test]
6777 fn it_matches_converting_the_whole_chat() {
6778 let mut interner = compact::NpubInterner::new();
6779 let mut held = compact::CompactMessageVec::new();
6780 let mut seed: u64 = 7;
6781 for n in 0..400u64 {
6782 seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17;
6783 let msg = Message { id: format!("{:064x}", seed), at: (n / 9) * 1000 + (seed % 3), ..Default::default() };
6785 held.insert(compact::CompactMessage::from_message(&msg, &mut interner));
6786 }
6787 let mut all: Vec<Message> = held.iter().map(|m| m.to_message(&interner)).collect();
6788 all.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
6789 let reference = |before: Option<(u64, &str)>, limit: usize| {
6790 let mut v: Vec<String> = all.iter()
6791 .filter(|m| before.is_none_or(|(at, id)| (m.at, m.id.as_str()) < (at, id)))
6792 .map(|m| m.id.clone())
6793 .collect();
6794 if v.len() > limit { v.drain(..v.len() - limit); }
6795 v
6796 };
6797 let ids = |v: Vec<Message>| v.into_iter().map(|m| m.id).collect::<Vec<_>>();
6798 for limit in [1, 3, 10, 50, 1000] {
6799 assert_eq!(ids(page_before(held.messages(), &interner, None, limit)), reference(None, limit));
6800 for c in all.iter().step_by(13) {
6801 for cursor in [(c.at, c.id.as_str()), (c.at, "0"), (c.at, "g"), (c.at + 1, "0")] {
6802 assert_eq!(ids(page_before(held.messages(), &interner, Some(cursor), limit)), reference(Some(cursor), limit), "cursor {cursor:?} limit {limit}");
6803 }
6804 }
6805 }
6806 }
6807}
6808
6809#[cfg(all(test, feature = "tor", not(target_arch = "wasm32")))]
6810mod transport_policy_tests {
6811 use std::time::Duration;
6812
6813 use crate::transport::{egress, Egress, Kind, Lane};
6814
6815 fn live() -> u64 {
6816 crate::db::live_session_id()
6817 }
6818
6819 #[test]
6822 fn tor_transport_policy() {
6823 let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
6824 let short = Duration::from_secs(5);
6825 let long = Duration::from_secs(300);
6826
6827 crate::transport::set_preference(Some(Kind::Clearnet));
6830 crate::tor::set_tor_enabled_pref(false);
6831 assert_eq!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Direct);
6832 assert_eq!(super::relay_connect_timeout(short), short);
6833 assert_eq!(super::relay_request_timeout(short), short);
6834
6835 crate::tor::set_tor_enabled_pref(true);
6838 assert!(matches!(
6839 crate::tor::transport_state(),
6840 crate::tor::TorTransportState::RequiredButInactive
6841 ));
6842 assert!(
6845 matches!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Refuse(_)),
6846 "Tor enabled but inactive must never connect direct"
6847 );
6848 assert_eq!(super::relay_connect_timeout(short), Duration::from_secs(60));
6849 assert_eq!(super::relay_request_timeout(short), Duration::from_secs(30));
6850
6851 crate::tor::set_tor_enabled_pref(false);
6854 crate::tor::arm_prelogin_carry(true);
6855 assert!(crate::tor::effective_tor_pref(false), "an armed carry raises an off preference");
6856 crate::tor::set_tor_enabled_pref(crate::tor::effective_tor_pref(false));
6857 assert!(
6858 matches!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Refuse(_)),
6859 "an armed carry must refuse until Tor is up, never connect direct"
6860 );
6861 crate::tor::arm_prelogin_carry(false);
6862 assert!(!crate::tor::effective_tor_pref(false), "a disarmed carry leaves the preference alone");
6863 assert!(crate::tor::effective_tor_pref(true));
6864
6865 let opts = super::transport_relay_options();
6867 assert!(format!("{opts:?}").contains("proxy: Some"), "remote-signer relays must carry the transport");
6868
6869 for tor in [true, false] {
6872 crate::tor::set_tor_enabled_pref(tor);
6873 assert_eq!(super::relay_connect_timeout(long), long, "connect, tor={tor}");
6874 assert_eq!(super::relay_request_timeout(long), long, "request, tor={tor}");
6875 }
6876 crate::transport::set_preference(Some(Kind::Clearnet));
6877 }
6878}
6879
6880#[cfg(test)]
6881mod facade_tests {
6882 use super::*;
6883
6884 #[tokio::test]
6887 async fn download_attachment_rejects_private_url() {
6888 let att = crate::types::Attachment {
6889 url: "http://169.254.169.254/latest/meta-data/".to_string(),
6890 ..Default::default()
6891 };
6892 match VectorCore.download_attachment(&att).await {
6893 Err(VectorError::Other(msg)) => {
6894 assert!(msg.contains("Private/internal"), "expected SSRF rejection, got: {msg}")
6895 }
6896 other => panic!("expected SSRF rejection, got {other:?}"),
6897 }
6898 }
6899
6900 #[tokio::test]
6901 async fn download_attachment_rejects_empty_url() {
6902 let att = crate::types::Attachment::default();
6903 assert!(VectorCore.download_attachment(&att).await.is_err());
6904 }
6905
6906 #[tokio::test]
6909 async fn list_communities_and_channel_routing_are_protocol_aware() {
6910 use crate::community::transport::memory::MemoryRelay;
6911 use nostr_sdk::prelude::Keys;
6912
6913 let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
6914 crate::db::close_database();
6915 crate::db::clear_id_caches();
6916 let tmp = tempfile::tempdir().unwrap();
6917 let acct = {
6919 const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
6920 let mut s = String::from("npub1");
6921 for i in 0..58 {
6922 s.push(B[(i * 7 + 3) % 32] as char);
6923 }
6924 s
6925 };
6926 std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
6927 crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
6928 crate::db::set_current_account(acct.clone()).unwrap();
6929 crate::db::init_database(&acct).unwrap();
6930 let _ = crate::state::take_nostr_client();
6931 let me = Keys::generate();
6932 crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
6933 crate::state::set_my_public_key(me.public_key());
6934
6935 let relay = MemoryRelay::new();
6937 let community = crate::community::v2::service::create_community(&relay, "V2 Guild", vec!["wss://r".into()], None)
6938 .await
6939 .unwrap();
6940 let channel_hex = crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0);
6941
6942 let listed = VectorCore.list_communities().await;
6944 let v2 = listed.iter().find(|c| c["version"] == 2).expect("the v2 community is listed");
6945 assert_eq!(v2["name"], "V2 Guild");
6946 assert_eq!(v2["is_owner"], true);
6947 assert_eq!(v2["channels"][0]["channel_id"], channel_hex);
6948
6949 assert_eq!(
6951 VectorCore.v2_community_for_channel(&channel_hex).unwrap(),
6952 Some(community.identity.community_id),
6953 "a v2 channel is routed to v2"
6954 );
6955 assert_eq!(VectorCore.v2_community_for_channel(&"00".repeat(32)).unwrap(), None);
6957 }
6958
6959 #[test]
6964 fn v2_invite_url_base_derivation_round_trips() {
6965 use crate::community::v2::derive::TOKEN_LEN;
6966 use crate::community::v2::invite::{build_invite_url, parse_invite_link};
6967 use nostr_sdk::prelude::Keys;
6968 let base = crate::community::v2::invite::INVITE_URL_BASE.trim_end_matches("/invite");
6969 assert!(!base.ends_with("/invite"), "the bare domain must not carry /invite");
6970 let signer = Keys::generate();
6971 let token = [0x07u8; TOKEN_LEN];
6972 let url = build_invite_url(base, &signer.public_key(), &token, &[]).unwrap();
6973 assert!(url.contains("/invite/"), "a v2 URL carries the naddr path");
6974 assert!(!url.contains("/invite/invite/"), "no doubled /invite from the base");
6975 let parsed = parse_invite_link(&url).unwrap();
6976 assert_eq!(parsed.link_signer, signer.public_key());
6977 assert_eq!(parsed.token, token);
6978 }
6979}
6980
6981#[cfg(test)]
6982mod history_paging_tests {
6983 use super::*;
6984
6985 fn msg(at: u64, id_byte: u8, content: &str) -> Message {
6986 Message {
6987 id: format!("{:02x}", id_byte).repeat(32),
6988 content: content.to_string(),
6989 at,
6990 ..Default::default()
6991 }
6992 }
6993
6994 #[tokio::test]
6998 async fn history_pages_through_a_same_ms_wall_and_a_deleted_cursor() {
6999 let chat_id = "test-history-paging-wall";
7000 {
7001 let mut st = state::STATE.lock().await;
7002 st.ensure_community_chat(chat_id);
7003 for m in [msg(500, 0x01, "old"), msg(900, 0xaa, "wall-a"), msg(900, 0xbb, "wall-b"), msg(900, 0xcc, "wall-c")] {
7005 st.add_message_to_chat(chat_id, &m);
7006 }
7007 }
7008 let core = VectorCore;
7009
7010 let newest = core.get_messages_before(chat_id, None, 2).await;
7012 assert_eq!(newest.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(), ["wall-b", "wall-c"]);
7013
7014 let cursor = (newest[0].at, newest[0].id.as_str().to_string());
7016 let page = core.get_messages_before(chat_id, Some((cursor.0, &cursor.1)), 10).await;
7017 assert_eq!(page.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(), ["old", "wall-a"]);
7018
7019 {
7022 let mut st = state::STATE.lock().await;
7023 let chat = st.get_chat_mut(chat_id).unwrap();
7024 chat.messages.remove_by_hex_id(&cursor.1);
7025 }
7026 let page = core.get_messages_before(chat_id, Some((cursor.0, &cursor.1)), 10).await;
7027 assert_eq!(
7028 page.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(),
7029 ["old", "wall-a"],
7030 "a deleted cursor pages identically"
7031 );
7032
7033 assert!(core.get_messages_before("test-history-paging-nochat", None, 5).await.is_empty());
7035 }
7036}
7037
7038#[cfg(test)]
7039mod moderation_cache_audit {
7040 #[test]
7046 fn every_moderation_action_drops_the_memoised_verdict() {
7047 let src = include_str!("lib.rs");
7048 for name in [
7049 "pub async fn refound_community",
7050 "pub async fn kick_community_members",
7051 "pub async fn set_members_banned",
7052 "pub async fn contain_raid",
7053 ] {
7054 let start = src.find(name).unwrap_or_else(|| panic!("{name} not found — rename?"));
7055 let rest = &src[start + name.len()..];
7057 let end = rest.find("\n pub ").unwrap_or(rest.len());
7058 assert!(
7059 rest[..end].contains("invalidate_raid_report"),
7060 "{name} mutates membership but never drops the memoised console verdict"
7061 );
7062 }
7063 }
7064
7065 #[test]
7070 fn an_adopted_change_drops_the_verdict_too() {
7071 let src = include_str!("db/community.rs");
7072 for name in ["pub fn set_community_banlist", "pub fn set_community_roles", "pub fn set_guestbook"] {
7073 let start = src.find(name).unwrap_or_else(|| panic!("{name} not found — rename?"));
7074 let rest = &src[start + name.len()..];
7075 let end = rest.find("\npub fn ").unwrap_or(rest.len());
7076 assert!(
7077 rest[..end].contains("forget_console_verdict"),
7078 "{name} changes who the console reports on but leaves the memo standing"
7079 );
7080 }
7081 }
7082}