1use crate::event_ext::FinalizeUnsignedWithId;
8use std::ops::Range;
9use std::sync::Arc;
10use std::sync::atomic::{AtomicBool, Ordering};
11use nostr_sdk::prelude::*;
12
13pub const NIP59_RANDOM_TIMESTAMP_TWEAK: Range<u64> = 0..172_800;
19
20pub fn tweaked_timestamp() -> Timestamp {
24 use ::rand::Rng;
25 let secs: u64 = ::rand::thread_rng().gen_range(NIP59_RANDOM_TIMESTAMP_TWEAK);
26 Timestamp::from_secs(crate::clock::timestamp().as_secs().saturating_sub(secs))
27}
28
29use crate::state::{nostr_client, my_public_key, STATE};
30use crate::types::{Message, Attachment};
31use crate::crypto;
32
33pub trait SendCallback: Send + Sync {
45 fn on_pending(&self, _chat_id: &str, _msg: &Message) {}
47
48 fn cancel_token(&self, _pending_id: &str) -> Option<Arc<AtomicBool>> {
52 None
53 }
54
55 fn on_upload_progress(
57 &self,
58 _pending_id: &str,
59 _percentage: u8,
60 _bytes_sent: u64,
61 ) -> Result<(), String> {
62 Ok(())
63 }
64
65 fn on_upload_complete(&self, _chat_id: &str, _pending_id: &str, _attachment_id: &str, _url: &str) {}
67 fn on_upload_stage(&self, _pending_id: &str, _stage: &str, _pct: Option<u8>) {}
70
71 fn on_sent(&self, _chat_id: &str, _old_id: &str, _msg: &Message) {}
74
75 fn on_failed(&self, _chat_id: &str, _old_id: &str, _msg: &Message) {}
77
78 fn on_refused(&self, _chat_id: &str, _old_id: &str, _reason: &str) {}
81
82 fn on_failed_reason(&self, _chat_id: &str, _old_id: &str, _reason: &str) {}
84
85 fn on_persist(&self, _chat_id: &str, _msg: &Message) {}
88}
89
90pub struct NoOpSendCallback;
92impl SendCallback for NoOpSendCallback {}
93
94pub struct SendConfig {
100 pub max_send_attempts: u32,
102 pub retry_delay: std::time::Duration,
104 pub self_send: bool,
106 pub cancel_token: Option<Arc<AtomicBool>>,
108 pub upload_retries: u32,
110 pub upload_retry_delay: std::time::Duration,
112 pub expiration: Option<u64>,
116 pub self_destruct_secs: Option<u64>,
120}
121
122impl Default for SendConfig {
123 fn default() -> Self {
124 Self {
125 max_send_attempts: 1,
126 retry_delay: std::time::Duration::from_secs(5),
127 self_send: false,
128 cancel_token: None,
129 upload_retries: 3,
130 upload_retry_delay: std::time::Duration::from_secs(2),
131 expiration: None,
132 self_destruct_secs: None,
133 }
134 }
135}
136
137impl SendConfig {
138 pub fn gui() -> Self {
140 Self {
141 max_send_attempts: 12,
142 self_send: true,
143 ..Default::default()
144 }
145 }
146
147 pub fn headless() -> Self {
149 Self {
150 max_send_attempts: 3,
151 self_send: true,
152 ..Default::default()
153 }
154 }
155}
156
157#[derive(serde::Serialize, Clone, Debug)]
163pub struct SendResult {
164 pub pending_id: String,
166 pub event_id: Option<String>,
168 pub chat_id: String,
170}
171
172struct WrapConfirm {
189 wrap_id: EventId,
190 chat_id: String,
191 pending_id: String,
192 rumor_event_id: String,
194 rumor: UnsignedEvent,
195 callback: Arc<dyn SendCallback>,
196 self_send: bool,
197 confirmed: AtomicBool,
198 rescued: AtomicBool,
201 loop_exited: AtomicBool,
204 notify: tokio::sync::Notify,
205 session: std::sync::Weak<crate::db::Session>,
208 registered_at: web_time::Instant,
209}
210
211struct WrapConfirms;
214
215fn wrap_confirms() -> Arc<std::sync::Mutex<std::collections::HashMap<EventId, Arc<WrapConfirm>>>> {
216 crate::db::current_session().scoped::<WrapConfirms, _>()
217}
218
219const WRAP_CONFIRM_TTL: std::time::Duration = std::time::Duration::from_secs(15 * 60);
222
223fn register_wrap_confirm(entry: Arc<WrapConfirm>) {
224 let owner = wrap_confirms();
225 let mut map = owner.lock().unwrap();
226 map.retain(|_, e| e.registered_at.elapsed() < WRAP_CONFIRM_TTL);
227 map.insert(entry.wrap_id, entry);
228}
229
230fn remove_wrap_confirm(wrap_id: &EventId) {
231 wrap_confirms().lock().unwrap().remove(wrap_id);
232}
233
234pub fn note_relay_ok(event_id: &EventId, accepted: bool) {
240 if !accepted {
241 return;
242 }
243 let entry = {
244 let owner = wrap_confirms();
245 let map = owner.lock().unwrap();
246 map.get(event_id).cloned()
247 };
248 let Some(entry) = entry else { return };
249 entry.confirmed.store(true, Ordering::SeqCst);
250 entry.notify.notify_one();
251 if !entry.loop_exited.load(Ordering::SeqCst)
252 || entry.rescued.swap(true, Ordering::SeqCst)
253 {
254 return;
255 }
256 if !entry.session.upgrade().is_some_and(|s| s.is_live()) {
257 remove_wrap_confirm(&entry.wrap_id);
258 return;
259 }
260 crate::db::spawn_bound(async move {
261 rescue_failed_as_sent(&entry).await;
262 remove_wrap_confirm(&entry.wrap_id);
263 });
264}
265
266async fn rescue_failed_as_sent(entry: &WrapConfirm) {
269 let finalized = {
270 let mut state = STATE.lock().await;
271 state.update_message(&entry.pending_id, |msg| {
272 msg.set_failed(false);
273 });
274 state.finalize_pending_message(&entry.chat_id, &entry.pending_id, &entry.rumor_event_id)
275 };
276 let Some((_old_id, ref msg)) = finalized else { return };
277 crate::log_info!(
278 "[Send] late relay OK confirmed wrap {} — message {} rescued to sent",
279 entry.wrap_id,
280 entry.rumor_event_id,
281 );
282 entry.callback.on_sent(&entry.chat_id, &entry.pending_id, msg);
283 entry.callback.on_persist(&entry.chat_id, msg);
284 if let Some(rid) = entry.rumor.id {
286 let _ = crate::db::nip17_keys::clear_resend_payload(&rid);
287 }
288 if entry.self_send {
289 if let (Some(client), Some(my_pk)) = (nostr_client(), my_public_key()) {
290 spawn_self_send(client, my_pk, entry.rumor.clone());
291 }
292 }
293 crate::push::after_delivery(&entry.chat_id, &entry.rumor);
294}
295
296fn spawn_self_send(client: Client, my_pk: PublicKey, rumor: UnsignedEvent) {
298 let rid_for_self = rumor.id;
299 crate::db::spawn_bound(async move {
300 match crate::inbox_relays::send_gift_wrap_retained(
301 &client, &my_pk, rumor, [],
302 ).await {
303 Ok(self_outcome) if !self_outcome.output.success.is_empty() => {
304 if let Some(rid) = rid_for_self {
305 if let Err(e) = crate::db::nip17_keys::store_wrap_key(
306 &self_outcome.wrap_event_id,
307 &rid,
308 &my_pk,
309 crate::db::nip17_keys::WrapRole::SelfSend,
310 &self_outcome.wrap_secret,
311 &self_outcome.targeted_relays,
312 ) {
313 eprintln!("[NIP-17] failed to persist self-wrap key: {}", e);
314 }
315 }
316 }
317 _ => {}
318 }
319 });
320}
321
322#[allow(clippy::too_many_arguments)]
337async fn retry_send_gift_wrap(
338 client: &Client,
339 receiver: &PublicKey,
340 receiver_npub: &str,
341 pending_id: &str,
342 rumor: UnsignedEvent,
343 event_id: &str,
344 config: &SendConfig,
345 callback: Arc<dyn SendCallback>,
346 prebuilt: Option<crate::inbox_relays::BuiltGiftWrap>,
350) -> Result<SendResult, String> {
351 let my_pk = my_public_key().ok_or("Public key not set")?;
352 let inner_rumor_id = rumor.id;
353
354 let is_resend = prebuilt.is_some();
357 let mut built: Option<crate::inbox_relays::BuiltGiftWrap> = prebuilt;
360 let mut targets: Option<crate::inbox_relays::GiftWrapTargets> = None;
363 let mut confirm: Option<Arc<WrapConfirm>> = None;
364 let mut last_error: Option<String> = None;
365 let mut unknown: Option<String> = None;
367 let mut keys_stored = is_resend;
368 let mut rechecked = false;
370
371 let max_attempts = config.max_send_attempts.max(1);
372
373 if let Err(why) = crate::event_size::check_rumor(&rumor) {
375 fail_pending(&callback, receiver_npub, pending_id, &why).await;
376 return Err(why);
377 }
378
379 if crate::transport::blocked_reason().is_some() {
383 let retries = config.retry_delay.saturating_mul(max_attempts.saturating_sub(1));
384 let budget = crate::transport::budget(crate::transport::Op::ReadyWait, std::time::Duration::ZERO).max(retries);
385 if let Err(why) = crate::transport::wait_ready(budget).await {
386 fail_pending(&callback, receiver_npub, pending_id, &why).await;
387 return Err(why);
388 }
389 }
390
391 for attempt in 0..max_attempts {
392 if built.is_none() {
393 let wrap_extra: Vec<Tag> = rumor.tags.iter()
396 .find(|t| t.as_slice().first().map(|k| k.as_str() == "expiration").unwrap_or(false))
397 .cloned()
398 .into_iter()
399 .collect();
400 match crate::inbox_relays::build_gift_wrap_retained(
401 client, receiver, rumor.clone(), wrap_extra,
402 ).await {
403 Ok(b) => built = Some(b),
404 Err(e) => {
405 crate::log_warn!(
406 "[Send] attempt {}/{} — building gift-wrap failed: {}",
407 attempt + 1, max_attempts, e,
408 );
409 last_error = Some(e);
410 if attempt + 1 < max_attempts {
411 crate::rt::time::sleep(config.retry_delay).await;
412 }
413 continue;
414 }
415 }
416 }
417 let wrap = built.as_ref().unwrap();
418
419 if confirm.is_none() {
420 let entry = Arc::new(WrapConfirm {
421 wrap_id: wrap.event.id,
422 chat_id: receiver_npub.to_string(),
423 pending_id: pending_id.to_string(),
424 rumor_event_id: event_id.to_string(),
425 rumor: rumor.clone(),
426 callback: callback.clone(),
427 self_send: config.self_send,
428 confirmed: AtomicBool::new(false),
429 rescued: AtomicBool::new(false),
430 loop_exited: AtomicBool::new(false),
431 notify: tokio::sync::Notify::new(),
432 session: std::sync::Arc::downgrade(&crate::db::current_session()),
433 registered_at: web_time::Instant::now(),
434 });
435 register_wrap_confirm(entry.clone());
436 confirm = Some(entry);
437 }
438 let confirm_ref = confirm.as_ref().unwrap();
439
440 if let Some(t) = targets.as_ref().filter(|t| t.unknown.is_none()) {
441 crate::inbox_relays::reconnect_gift_wrap_targets(t).await;
442 } else {
443 let t = crate::inbox_relays::resolve_gift_wrap_targets(client, receiver).await;
444 if t.refused.is_some() && t.from_cache && !rechecked {
446 rechecked = true;
447 if crate::inbox_relays::recheck_after_failure(client, receiver, &t.inbox_tried).await {
448 continue;
449 }
450 }
451 if let Some(why) = t.refused.clone() {
453 remove_wrap_confirm(&confirm_ref.wrap_id);
454 callback.on_refused(receiver_npub, pending_id, &why);
455 fail_pending(&callback, receiver_npub, pending_id, &why).await;
456 return Err(why);
457 }
458 if let Some(why) = t.unknown.clone() {
461 crate::log_warn!("[Send] attempt {}/{} — inbox lookup out of reach: {}", attempt + 1, max_attempts, why);
462 unknown = Some(why);
463 targets = None;
464 if attempt + 1 < max_attempts {
465 crate::rt::time::sleep(config.retry_delay).await;
466 }
467 continue;
468 }
469 unknown = None;
470 if !keys_stored {
474 keys_stored = true;
475 if let Some(rid) = inner_rumor_id {
476 if let Err(e) = crate::db::nip17_keys::store_wrap_key(
477 &wrap.event.id,
478 &rid,
479 receiver,
480 crate::db::nip17_keys::WrapRole::Recipient,
481 &wrap.secret,
482 &t.targeted_relays,
483 ) {
484 eprintln!("[NIP-17] failed to persist wrap key: {}", e);
485 }
486 if let Err(e) = crate::db::nip17_keys::stash_resend_payload(
487 &wrap.event.id, pending_id, &wrap.event, &rumor,
488 ) {
489 eprintln!("[NIP-17] failed to retain resend payload: {}", e);
490 }
491 }
492 }
493 if keys_stored && (is_resend || rechecked) {
495 if let Err(e) = crate::db::nip17_keys::add_wrap_relays(&wrap.event.id, &t.targeted_relays) {
496 eprintln!("[NIP-17] failed to note the new wrap relays: {}", e);
497 }
498 }
499 targets = Some(t);
500 }
501 let targets_ref = targets.as_ref().unwrap();
502 let from_cache = targets_ref.from_cache;
503 let inbox_tried = targets_ref.inbox_tried.clone();
504
505 match crate::inbox_relays::publish_gift_wrap_to_targets(
506 client, targets_ref, &wrap.event,
507 ).await {
508 Ok(output) if !output.success.is_empty() => {
509 return Ok(finalize_gift_wrap_sent(
510 client, my_pk, receiver_npub, pending_id, event_id,
511 &rumor, config, &callback, confirm_ref, targets_ref,
512 ).await);
513 }
514 Ok(output) => {
515 let failures: Vec<String> = output.failed.iter()
520 .map(|(url, err)| format!("{}: {}", url, err))
521 .collect();
522 crate::log_warn!(
523 "[Send] attempt {}/{} — 0 of {} relays accepted (targeted: {}). Per-relay errors: {}",
524 attempt + 1,
525 max_attempts,
526 targets_ref.targeted_relays.len(),
527 targets_ref.targeted_relays.join(", "),
528 if failures.is_empty() {
529 "(none reported — likely all timed out before responding)".to_string()
530 } else {
531 failures.join(" | ")
532 },
533 );
534 last_error = None;
535 }
536 Err(e) => {
537 crate::log_warn!(
538 "[Send] attempt {}/{} — publish errored: {}",
539 attempt + 1, max_attempts, e,
540 );
541 last_error = Some(e);
542 }
543 }
544
545 if confirm_ref.confirmed.load(Ordering::SeqCst) {
548 return Ok(finalize_gift_wrap_sent(
549 client, my_pk, receiver_npub, pending_id, event_id,
550 &rumor, config, &callback, confirm_ref, targets_ref,
551 ).await);
552 }
553
554 if from_cache && !rechecked && attempt + 1 < max_attempts {
557 rechecked = true;
558 if crate::inbox_relays::recheck_after_failure(client, receiver, &inbox_tried).await {
559 crate::log_info!("[Send] {}'s inbox relays changed; sending to the new ones", receiver_npub);
560 if let Some(old) = targets.take() {
561 crate::inbox_relays::teardown_gift_wrap_targets(client, &old).await;
562 }
563 continue;
564 }
565 }
566
567 if attempt + 1 < max_attempts {
568 let _ = crate::rt::time::timeout(
572 config.retry_delay,
573 confirm_ref.notify.notified(),
574 ).await;
575 if confirm_ref.confirmed.load(Ordering::SeqCst) {
576 return Ok(finalize_gift_wrap_sent(
577 client, my_pk, receiver_npub, pending_id, event_id,
578 &rumor, config, &callback, confirm_ref, targets_ref,
579 ).await);
580 }
581 }
582 }
583
584 if let (Some(wrap), Some(t), Some(entry)) = (built.as_ref(), targets.as_ref(), confirm.as_ref()) {
586 if wrap_on_relays(client, &wrap.event, receiver, t).await {
587 return Ok(finalize_gift_wrap_sent(
588 client, my_pk, receiver_npub, pending_id, event_id,
589 &rumor, config, &callback, entry, t,
590 ).await);
591 }
592 }
593
594 if let Some(t) = targets.as_ref() {
598 crate::inbox_relays::teardown_gift_wrap_targets(client, t).await;
599 }
600 let why = crate::transport::blocked_reason()
601 .or_else(|| unknown.clone())
602 .or_else(|| built.is_none().then(|| last_error.clone()).flatten())
603 .unwrap_or_else(|| "No relay accepted the message.".to_string());
604 fail_pending(&callback, receiver_npub, pending_id, &why).await;
605 if let Some(entry) = confirm.as_ref() {
606 entry.loop_exited.store(true, Ordering::SeqCst);
607 if entry.confirmed.load(Ordering::SeqCst)
610 && !entry.rescued.swap(true, Ordering::SeqCst)
611 {
612 rescue_failed_as_sent(entry).await;
613 remove_wrap_confirm(&entry.wrap_id);
614 return Ok(SendResult {
615 pending_id: pending_id.to_string(),
616 event_id: Some(event_id.to_string()),
617 chat_id: receiver_npub.to_string(),
618 });
619 }
620 }
621 match last_error {
622 Some(e) => Err(format!("Failed to send DM after {} attempts: {}", max_attempts, e)),
623 None => Err(format!(
624 "Failed to send DM after {} attempts (no relays accepted the gift-wrap)",
625 max_attempts
626 )),
627 }
628}
629
630async fn wrap_on_relays(
633 client: &Client,
634 wrap: &Event,
635 receiver: &PublicKey,
636 targets: &crate::inbox_relays::GiftWrapTargets,
637) -> bool {
638 use futures_util::stream::{FuturesUnordered, StreamExt};
639 let filter = Filter::new().id(wrap.id).kind(Kind::GiftWrap).pubkey(*receiver);
640 let budget = crate::relay_request_timeout(std::time::Duration::from_secs(8));
641 let mut checks: FuturesUnordered<_> = targets
642 .resolved
643 .iter()
644 .map(|(url, _)| crate::community::transport::fetch_relay_eose_filters(client, url.as_str(), vec![filter.clone()], budget))
645 .collect();
646 while let Some(found) = checks.next().await {
647 if found.is_ok_and(|events| events.iter().any(|e| e.id == wrap.id)) {
648 return true;
649 }
650 }
651 false
652}
653
654#[allow(clippy::too_many_arguments)]
657async fn finalize_gift_wrap_sent(
658 client: &Client,
659 my_pk: PublicKey,
660 receiver_npub: &str,
661 pending_id: &str,
662 event_id: &str,
663 rumor: &UnsignedEvent,
664 config: &SendConfig,
665 callback: &Arc<dyn SendCallback>,
666 confirm: &Arc<WrapConfirm>,
667 targets: &crate::inbox_relays::GiftWrapTargets,
668) -> SendResult {
669 remove_wrap_confirm(&confirm.wrap_id);
670 crate::inbox_relays::teardown_gift_wrap_targets(client, targets).await;
671
672 let finalized = {
673 let mut state = STATE.lock().await;
674 state.finalize_pending_message(receiver_npub, pending_id, event_id)
675 };
676 if let Some((_old_id, ref finalized_msg)) = finalized {
677 callback.on_sent(receiver_npub, pending_id, finalized_msg);
678 callback.on_persist(receiver_npub, finalized_msg);
679 }
680
681 if let Some(rid) = rumor.id {
684 let _ = crate::db::nip17_keys::clear_resend_payload(&rid);
685 }
686
687 if config.self_send {
688 spawn_self_send(client.clone(), my_pk, rumor.clone());
689 }
690 crate::push::after_delivery(receiver_npub, rumor);
691
692 SendResult {
693 pending_id: pending_id.to_string(),
694 event_id: Some(event_id.to_string()),
695 chat_id: receiver_npub.to_string(),
696 }
697}
698
699async fn add_pending(receiver_npub: &str, msg: &Message) {
710 let answered = {
711 let mut state = STATE.lock().await;
712 let unanswered = crate::requests::shielded() && state.dm_unanswered(receiver_npub);
713 state.add_message_to_participant(receiver_npub, msg);
714 unanswered
715 };
716 if answered {
717 let npub = receiver_npub.to_string();
718 crate::db::spawn_bound(async move { crate::wallpaper::release_held(&npub).await });
719 crate::profile::sync::queue_profile_sync(receiver_npub.to_string(), crate::profile::sync::SyncPriority::Critical, true);
720 }
721}
722
723pub async fn send_dm(
724 receiver_npub: &str,
725 content: &str,
726 reply_to: Option<&str>,
727 config: &SendConfig,
728 callback: Arc<dyn SendCallback>,
729) -> Result<SendResult, String> {
730 let client = nostr_client().ok_or("Not logged in")?;
731 let my_pk = my_public_key().ok_or("Public key not set")?;
732
733 let pending_id = format!("pending-{}", web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_nanos());
735 let now = std::time::Duration::from_millis(crate::clock::now_ms());
737
738 let receiver = PublicKey::from_bech32(receiver_npub)
739 .map_err(|e| format!("Invalid npub: {}", e))?;
740
741 let (plain, text_spans) = crate::text_spans::extract_own(content);
742 let content = plain.as_str();
743
744 let emoji_tags = crate::emoji_packs::resolve_outbound_emoji_tags(content);
749
750 let mut msg = Message {
752 id: pending_id.clone(),
753 content: content.to_string(),
754 replied_to: reply_to.unwrap_or("").to_string(),
755 at: now.as_millis() as u64,
756 pending: true,
757 mine: true,
758 npub: my_pk.to_bech32().ok(),
759 emoji_tags: emoji_tags.clone(),
760 text_spans: text_spans.clone(),
761 expiration: config.expiration,
762 ..Default::default()
763 };
764 let _ = crate::db::events::populate_reply_context(&mut msg).await;
766
767 add_pending(receiver_npub, &msg).await;
768
769 callback.on_pending(receiver_npub, &msg);
770
771 let milliseconds = now.as_millis() % 1000;
773 let mut rumor = EventBuilder::new(Kind::PrivateDirectMessage, content)
775 .custom_created_at(Timestamp::from_secs(now.as_secs()))
776 .tag(Tag::public_key(receiver));
777
778 if let Some(reply_id) = reply_to {
779 if !reply_id.is_empty() {
780 rumor = rumor.tag(Tag::custom(
781 "e",
782 [reply_id.to_string(), String::new(), "reply".to_string()],
783 ));
784 }
785 }
786
787 let mut rumor = rumor.tag(Tag::custom("ms", [milliseconds.to_string()]));
788 for et in &emoji_tags {
789 rumor = rumor.tag(Tag::custom(
790 "emoji",
791 [et.shortcode.clone(), et.url.clone()],
792 ));
793 }
794 rumor = rumor.tags(crate::text_spans::to_nostr_tags(&text_spans));
795 if let Some(exp) = config.expiration {
798 rumor = rumor.tag(Tag::expiration(Timestamp::from_secs(exp)));
799 }
800 let built_rumor = rumor.finalize_unsigned_with_id(my_pk);
801 let event_id = built_rumor.id.ok_or("Rumor has no id")?.to_hex();
802
803 retry_send_gift_wrap(
805 &client, &receiver, receiver_npub, &pending_id,
806 built_rumor, &event_id, config, callback, None,
807 ).await
808}
809
810pub async fn send_rumor_dm(
818 receiver_npub: &str,
819 pending_id: &str,
820 rumor: UnsignedEvent,
821 config: &SendConfig,
822 callback: Arc<dyn SendCallback>,
823) -> Result<SendResult, String> {
824 let client = nostr_client().ok_or("Not logged in")?;
825
826 let receiver = PublicKey::from_bech32(receiver_npub)
827 .map_err(|e| format!("Invalid npub: {}", e))?;
828
829 let event_id = rumor.id.ok_or("Rumor has no id")?.to_hex();
830
831 retry_send_gift_wrap(
832 &client, &receiver, receiver_npub, pending_id,
833 rumor, &event_id, config, callback, None,
834 ).await
835}
836
837pub async fn resend_failed_dm(
850 receiver_npub: &str,
851 failed_msg_id: &str,
852 config: &SendConfig,
853 callback: Arc<dyn SendCallback>,
854) -> Result<bool, String> {
855 let payload = match crate::db::nip17_keys::get_resend_payload_by_pending(failed_msg_id)? {
860 Some(p) => p,
861 None => return Ok(false),
862 };
863 let client = nostr_client().ok_or("Not logged in")?;
864 let receiver = PublicKey::from_bech32(receiver_npub)
865 .map_err(|e| format!("Invalid npub: {}", e))?;
866
867 let repending = {
870 let mut state = STATE.lock().await;
871 state.update_message(failed_msg_id, |msg| {
872 msg.set_failed(false);
873 msg.set_pending(true);
874 })
875 };
876 if let Some((_chat_id, ref msg)) = repending {
877 callback.on_pending(receiver_npub, msg);
878 }
879
880 let event_id = payload.rumor.id.ok_or("Retained rumor has no id")?.to_hex();
881 let built = crate::inbox_relays::BuiltGiftWrap {
882 event: payload.wrap_event,
883 secret: payload.secret,
884 };
885 if let Err(e) = retry_send_gift_wrap(
887 &client, &receiver, receiver_npub, failed_msg_id,
888 payload.rumor, &event_id, config, callback, Some(built),
889 )
890 .await
891 {
892 crate::log_warn!("[Send] idempotent resend of {} did not land: {}", failed_msg_id, e);
896 }
897 Ok(true)
898}
899
900#[allow(clippy::too_many_arguments)]
908pub async fn send_file_dm(
909 receiver_npub: &str,
910 file_bytes: Arc<Vec<u8>>,
911 filename: &str,
912 extension: &str,
913 content: Option<&str>,
914 reply_to: Option<&str>,
915 config: &SendConfig,
916 callback: Arc<dyn SendCallback>,
917) -> Result<SendResult, String> {
918 send_file_dm_with_meta(receiver_npub, file_bytes, filename, extension, None, content, reply_to, config, callback).await
919}
920
921#[allow(clippy::too_many_arguments)]
924pub async fn send_file_dm_with_meta(
925 receiver_npub: &str,
926 file_bytes: Arc<Vec<u8>>,
927 filename: &str,
928 extension: &str,
929 img_meta: Option<crate::types::ImageMetadata>,
930 content: Option<&str>,
931 reply_to: Option<&str>,
932 config: &SendConfig,
933 callback: Arc<dyn SendCallback>,
934) -> Result<SendResult, String> {
935 send_file_dm_from(receiver_npub, FileSource::Bytes(file_bytes), filename, extension, img_meta, content, reply_to, config, callback).await
936}
937
938pub enum FileSource {
940 Bytes(Arc<Vec<u8>>),
942 Path(std::path::PathBuf),
945 Saved(std::path::PathBuf),
948 Sealed { path: std::path::PathBuf, hash: String, key: String, nonce: String, blob_sha256: String },
951}
952
953pub struct TempFile(std::path::PathBuf);
955
956impl Drop for TempFile {
957 fn drop(&mut self) {
958 let _ = std::fs::remove_file(&self.0);
959 }
960}
961
962impl TempFile {
963 pub fn keep(self) -> std::path::PathBuf {
965 let path = self.0.clone();
966 std::mem::forget(self);
967 path
968 }
969}
970
971#[cfg(not(target_arch = "wasm32"))]
973fn outgoing_dir() -> std::path::PathBuf {
974 crate::db::current_account_dir().map(|d| d.join("outgoing")).unwrap_or_else(|_| std::env::temp_dir())
975}
976
977#[cfg(not(target_arch = "wasm32"))]
979pub fn keep_for_retry(body: &crate::blossom::UploadBody, guard: Option<TempFile>, hash: &str, key: &str, nonce: &str, pending_id: &str, mime: &str) {
980 let path = match (body, guard) {
981 (crate::blossom::UploadBody::File { .. }, Some(guard)) => guard.keep(),
982 (crate::blossom::UploadBody::Memory(data), _) => {
983 let dir = outgoing_dir();
984 let _ = std::fs::create_dir_all(&dir);
985 let path = dir.join(format!("{hash}-{pending_id}.enc"));
986 if std::fs::write(&path, &***data).is_err() {
987 return;
988 }
989 path
990 }
991 _ => return,
992 };
993 crate::media::pending::sealed(crate::simd::hex::hex_to_bytes_32(hash), path, key, nonce, mime);
994}
995
996#[cfg(not(target_arch = "wasm32"))]
999pub fn retry_source(att: &Attachment) -> Option<FileSource> {
1000 let hash = crate::simd::hex::hex_to_bytes_32_checked(&att.id)?;
1001 if let Some(path) = crate::media::pending::plain_path(&hash) {
1002 return Some(FileSource::Path(path));
1003 }
1004 if crate::media::ram::cache().contains(&hash) || crate::media::store::holds(&hash) {
1005 let src = crate::media::open(&hash)?;
1006 return crate::media::read_all(&*src).ok().map(|bytes| FileSource::Bytes(Arc::new(bytes)));
1007 }
1008 let prefix = format!("{}-", att.id);
1009 let kept = std::fs::read_dir(outgoing_dir())
1010 .ok()?
1011 .flatten()
1012 .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix) && e.file_name().to_string_lossy().ends_with(".enc"))
1013 .max_by_key(|e| e.metadata().and_then(|m| m.modified()).ok())?;
1014 let (blob_sha256, _) = crypto::stream::hash_file(&kept.path()).ok()?;
1015 Some(FileSource::Sealed { path: kept.path(), hash: att.id.clone(), key: att.key.clone(), nonce: att.nonce.clone(), blob_sha256 })
1016}
1017
1018pub async fn abandon_failed_send(chat_id: &str, message_id: &str, attachments: &[Attachment]) {
1022 let in_community = matches!(crate::db::community::community_id_for_channel(chat_id), Ok(Some(_)));
1023 let unread = if in_community {
1024 crate::community::v2::service::discard_unconfirmed(chat_id, message_id).await
1025 } else {
1026 match crate::db::nip17_keys::get_resend_payload_by_pending(message_id) {
1027 Ok(None) => true,
1028 Ok(Some(wrapped)) => match (wrapped.rumor.id, PublicKey::from_bech32(chat_id)) {
1029 (Some(rumor_id), Ok(recipient)) => crate::deletion::take_back_failed_dm(&rumor_id, &recipient).await,
1030 _ => false,
1031 },
1032 Err(_) => false,
1033 }
1034 };
1035 if !unread {
1036 return;
1037 }
1038 let urls: Vec<String> = attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect();
1039 let urls = crate::db::attachments::urls_unreferenced_elsewhere(&urls, message_id).unwrap_or_default();
1040 if urls.is_empty() {
1041 return;
1042 }
1043 if let Ok(signer) = crate::signer::active_signer() {
1044 crate::blossom::delete_blobs_best_effort(signer, urls);
1045 }
1046}
1047
1048#[cfg(not(target_arch = "wasm32"))]
1050pub fn discard_retry_copy(att: &Attachment) {
1051 let Some(hash) = crate::simd::hex::hex_to_bytes_32_checked(&att.id) else { return };
1052 crate::media::pending::forget(&hash);
1053 let prefix = format!("{}-", att.id);
1054 if let Ok(entries) = std::fs::read_dir(outgoing_dir()) {
1055 for entry in entries.flatten() {
1056 let name = entry.file_name().to_string_lossy().into_owned();
1057 if name.starts_with(&prefix) && name.ends_with(".enc") {
1058 let _ = std::fs::remove_file(entry.path());
1059 }
1060 }
1061 }
1062}
1063
1064#[cfg(not(target_arch = "wasm32"))]
1067pub fn sweep_outgoing() {
1068 let dir = outgoing_dir();
1069 sweep_older_than(&dir, std::time::Duration::from_secs(14 * 24 * 3600));
1070 sweep_older_than(&dir.join("work"), std::time::Duration::from_secs(24 * 3600));
1071}
1072
1073#[cfg(not(target_arch = "wasm32"))]
1074fn sweep_older_than(dir: &std::path::Path, max_age: std::time::Duration) {
1075 let Ok(entries) = std::fs::read_dir(dir) else { return };
1076 for entry in entries.flatten() {
1077 let old = entry.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age);
1078 if old {
1079 let _ = std::fs::remove_file(entry.path());
1080 }
1081 }
1082}
1083
1084pub enum Sealed {
1086 Reused(crate::db::attachments::ReusableUpload),
1088 Body(crate::blossom::UploadBody, Option<TempFile>),
1090}
1091
1092pub async fn seal_or_reuse(
1095 plain: FileSource,
1096 hash: &str,
1097 key: &str,
1098 nonce: &str,
1099 pending_id: &str,
1100 callback: Arc<dyn SendCallback>,
1101 cancel: Option<Arc<AtomicBool>>,
1102) -> Result<Sealed, String> {
1103 if let Ok(Some(r)) = crate::db::attachments::find_reusable_by_hash(hash) {
1106 if crate::blossom::blob_is_served(&r.url, std::time::Duration::from_secs(5)).await {
1107 crate::log_info!("[SmartForward] {} reused ({}, {} KB) — no upload", &hash[..8.min(hash.len())], if r.mine { "own blob" } else { "foreign blob, mirroring in background" }, r.size / 1024);
1108 return Ok(Sealed::Reused(r));
1109 }
1110 }
1111
1112 let (key, nonce) = (key.to_string(), nonce.to_string());
1113 #[cfg(not(target_arch = "wasm32"))]
1115 let outgoing = outgoing_dir();
1116 #[cfg(target_arch = "wasm32")]
1118 let outgoing = crate::db::current_account_dir().map(|d| d.join("outgoing")).unwrap_or_default();
1119 callback.on_upload_stage(pending_id, "encrypting", matches!(plain, FileSource::Path(_) | FileSource::Saved(_)).then_some(0));
1121 let sealed = match plain {
1122 FileSource::Bytes(bytes) => {
1123 let sealed = crate::rt::spawn_blocking(move || {
1124 crypto::encrypt_data(&bytes, &crypto::EncryptionParams { key, nonce })
1125 })
1126 .await
1127 .map_err(|e| format!("Encryption failed: {}", e))??;
1128 Sealed::Body(crate::blossom::UploadBody::Memory(Arc::new(sealed)), None)
1129 }
1130 FileSource::Sealed { path, blob_sha256, .. } => {
1131 let len = std::fs::metadata(&path).map_err(|e| format!("Couldn't read the file: {e}"))?.len();
1132 Sealed::Body(crate::blossom::UploadBody::file(path.clone(), len, &blob_sha256)?, Some(TempFile(path)))
1133 }
1134 FileSource::Path(path) | FileSource::Saved(path) => {
1135 let _ = std::fs::create_dir_all(&outgoing);
1136 let out = outgoing.join(format!("{}-{}.enc", hash, pending_id));
1137 let guard = TempFile(out.clone());
1138 let target = out.clone();
1139 let (stage_cb, pid, plain_hash) = (callback.clone(), pending_id.to_string(), hash.to_string());
1140 let (sealed_hash, len) = crate::rt::spawn_blocking(move || {
1142 crypto::stream::encrypt_file_matching(&path, &target, &key, &nonce, &plain_hash, &mut |pct| {
1143 stage_cb.on_upload_stage(&pid, "encrypting", Some(pct));
1144 !cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed))
1146 })
1147 })
1148 .await
1149 .map_err(|e| format!("Encryption failed: {}", e))??;
1150 Sealed::Body(crate::blossom::UploadBody::file(out, len, &sealed_hash)?, Some(guard))
1151 }
1152 };
1153 callback.on_upload_stage(pending_id, "starting", None);
1154 Ok(sealed)
1155}
1156
1157async fn fail_pending(callback: &Arc<dyn SendCallback>, receiver_npub: &str, pending_id: &str, why: &str) {
1159 let failed_msg = {
1160 let mut state = STATE.lock().await;
1161 state.update_message(pending_id, |msg| {
1162 msg.set_failed(true);
1163 msg.set_pending(false);
1164 })
1165 };
1166 if let Some((_chat_id, ref msg)) = failed_msg {
1167 callback.on_failed_reason(receiver_npub, pending_id, why);
1168 callback.on_failed(receiver_npub, pending_id, msg);
1169 callback.on_persist(receiver_npub, msg);
1170 }
1171}
1172
1173pub fn failure_line(err: &str) -> String {
1176 let line = err.trim().trim_start_matches("Upload failed:").trim().lines().next().unwrap_or_default().trim();
1177 match line.strip_suffix(':') {
1178 Some(head) => format!("{head}."),
1179 None => line.to_string(),
1180 }
1181}
1182
1183#[cfg(not(target_arch = "wasm32"))]
1186pub fn keep_sent(body: &crate::blossom::UploadBody, hash: &str, key: &str, nonce: &str, pt_len: u64, mime: &str) -> bool {
1187 use crate::media::store::{keep_bytes, keep_file, Keep};
1188 let keep = |blob_sha256: String| Keep {
1189 hash: crate::simd::hex::hex_to_bytes_32(hash), key: key.to_string(), nonce: nonce.to_string(),
1190 blob_sha256, pt_len, mime: mime.to_string(), origin: crate::db::media_store::Origin::Sent,
1191 };
1192 let kept = match body {
1193 crate::blossom::UploadBody::Memory(data) => keep_bytes(data, keep(crypto::sha256_hex(data))),
1194 crate::blossom::UploadBody::File { path, sha256, .. } => keep_file(path, keep(sha256.to_string())),
1195 };
1196 kept.inspect_err(|e| crate::log_warn!("[Send] sent, but couldn't keep it: {e}")).is_ok()
1197}
1198
1199async fn mark_send_failed(callback: &Arc<dyn SendCallback>, receiver_npub: &str, pending_id: &str, err: String) -> String {
1200 fail_pending(callback, receiver_npub, pending_id, &failure_line(&err)).await;
1201 err
1202}
1203
1204#[allow(clippy::too_many_arguments)]
1206pub async fn send_file_dm_from(
1207 receiver_npub: &str,
1208 source: FileSource,
1209 filename: &str,
1210 extension: &str,
1211 img_meta: Option<crate::types::ImageMetadata>,
1212 content: Option<&str>,
1213 reply_to: Option<&str>,
1214 config: &SendConfig,
1215 callback: Arc<dyn SendCallback>,
1216) -> Result<SendResult, String> {
1217 let client = nostr_client().ok_or("Not logged in")?;
1218 let my_pk = my_public_key().ok_or("Public key not set")?;
1219 let reply_to = reply_to.filter(|r| !r.is_empty());
1220 let signer = crate::signer::active_signer()
1224 .map_err(|e| format!("Signer unavailable: {}", e))?;
1225
1226 let pending_id = format!("pending-{}", web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_nanos());
1228 let now = std::time::Duration::from_millis(crate::clock::now_ms());
1229 let milliseconds = now.as_millis() % 1000;
1230
1231 let receiver = PublicKey::from_bech32(receiver_npub)
1232 .map_err(|e| format!("Invalid npub: {}", e))?;
1233
1234 let mime_type = crypto::mime_from_extension(extension);
1235
1236 #[cfg(target_arch = "wasm32")]
1238 let (file_hash, local_path_str, img_meta, plain_len) = {
1239 let FileSource::Bytes(bytes) = &source else {
1240 return Err("Vector Web sends files from memory".into());
1241 };
1242 let file_hash = crypto::sha256_hex(bytes);
1243 let _ = crate::media::ram::insert(crate::simd::hex::hex_to_bytes_32(&file_hash), bytes.to_vec(), mime_type);
1244 let img_meta = img_meta.or_else(|| crypto::generate_image_metadata(bytes));
1245 (file_hash, String::new(), img_meta, bytes.len() as u64)
1246 };
1247 #[cfg(not(target_arch = "wasm32"))]
1251 let (file_hash, local_path_str, img_meta, plain_len) = {
1252 let (file_hash, img_meta, plain_len) = match &source {
1253 FileSource::Bytes(bytes) => {
1254 let bytes = Arc::clone(bytes);
1255 crate::rt::spawn_blocking(move || {
1256 let img_meta = img_meta.or_else(|| crypto::generate_image_metadata(&bytes));
1257 (crypto::sha256_hex(&bytes), img_meta, bytes.len() as u64)
1258 })
1259 .await
1260 .map_err(|e| format!("Attachment prep failed: {}", e))?
1261 }
1262 FileSource::Path(path) | FileSource::Saved(path) => {
1263 let path = path.clone();
1264 let (hash, len) = crate::rt::spawn_blocking(move || crypto::stream::hash_file(&path))
1265 .await
1266 .map_err(|e| format!("Attachment prep failed: {}", e))??;
1267 (hash, img_meta, len)
1268 }
1269 FileSource::Sealed { path, hash, .. } => {
1270 let len = std::fs::metadata(path).map_err(|e| format!("Couldn't read the file: {e}"))?.len();
1271 (hash.clone(), img_meta, len.saturating_sub(16))
1272 }
1273 };
1274 let hash = crate::simd::hex::hex_to_bytes_32(&file_hash);
1275 match &source {
1276 FileSource::Bytes(bytes) => {
1277 let _ = crate::media::ram::insert(hash, bytes.to_vec(), mime_type);
1278 }
1279 FileSource::Path(path) | FileSource::Saved(path) => crate::media::pending::plain(hash, path.clone(), mime_type),
1280 FileSource::Sealed { path, key, nonce, .. } => crate::media::pending::sealed(hash, path.clone(), key, nonce, mime_type),
1281 }
1282 (file_hash, String::new(), img_meta, plain_len)
1283 };
1284
1285 let webxdc_topic = (extension.eq_ignore_ascii_case("xdc"))
1290 .then(|| crate::webxdc::mint_topic_id(&file_hash, &my_pk.to_hex()));
1291
1292 let params = match &source {
1296 FileSource::Sealed { key, nonce, .. } => crypto::EncryptionParams { key: key.clone(), nonce: nonce.clone() },
1297 _ => crypto::generate_encryption_params(),
1298 };
1299 let attachment = Attachment {
1300 id: file_hash.clone(), key: params.key.clone(), nonce: params.nonce.clone(),
1301 extension: extension.to_string(), name: filename.to_string(),
1302 url: String::new(), path: local_path_str.clone(), size: plain_len + 16,
1303 img_meta: img_meta.clone(), downloading: false, downloaded: false, verified: true,
1305 resident: crate::media::resident(&crate::simd::hex::hex_to_bytes_32(&file_hash)),
1306 webxdc_topic: webxdc_topic.clone(),
1307 ..Default::default()
1308 };
1309 let mut msg = Message {
1310 id: pending_id.clone(), content: content.unwrap_or("").to_string(),
1311 replied_to: reply_to.unwrap_or("").to_string(),
1312 at: now.as_millis() as u64, pending: true, mine: true,
1313 npub: my_pk.to_bech32().ok(), attachments: vec![attachment.clone()],
1314 expiration: if config.self_destruct_secs.is_some() { None } else { config.expiration },
1316 ..Default::default()
1317 };
1318 let _ = crate::db::events::populate_reply_context(&mut msg).await;
1319 add_pending(receiver_npub, &msg).await;
1320 callback.on_pending(receiver_npub, &msg);
1321 let cancel = config.cancel_token.clone().or_else(|| callback.cancel_token(&pending_id));
1322
1323 let plain = source;
1325 let sealed = match seal_or_reuse(plain, &file_hash, ¶ms.key, ¶ms.nonce, &pending_id, callback.clone(), cancel.clone()).await {
1326 Ok(sealed) => sealed,
1327 Err(e) => return Err(mark_send_failed(&callback, receiver_npub, &pending_id, e).await),
1329 };
1330 #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
1333 let (reused, encrypted, ciphertext_file) = match sealed {
1334 Sealed::Reused(r) => (Some(r), None, None),
1335 Sealed::Body(body, guard) => (None, Some(body), guard),
1336 };
1337 let (att_key, att_nonce, att_url, encrypted_size) = match (&reused, &encrypted) {
1338 (Some(r), _) => {
1339 let adopted = crate::compact::CompactAttachment::from_attachment(&Attachment {
1340 key: r.key.clone(), nonce: r.nonce.clone(), url: r.url.clone(), size: r.size,
1341 ..attachment.clone()
1342 });
1343 let mut state = STATE.lock().await;
1344 state.update_message(&pending_id, |msg| {
1345 if let Some(att) = msg.attachments.last_mut() {
1346 *att = adopted.clone();
1347 }
1348 });
1349 (r.key.clone(), r.nonce.clone(), r.url.clone(), r.size)
1350 }
1351 (None, body) => (params.key.clone(), params.nonce.clone(), String::new(), body.as_ref().map_or(0, |b| b.len())),
1352 };
1353
1354 let servers = crate::state::get_blossom_servers();
1356 let cb_for_progress = callback.clone();
1357 let pid_for_progress = pending_id.clone();
1358 let progress_cb: crate::blossom::ProgressCallback = Arc::new(move |percentage, bytes| {
1359 cb_for_progress.on_upload_progress(
1360 &pid_for_progress,
1361 percentage.unwrap_or(0),
1362 bytes.unwrap_or(0),
1363 )
1364 });
1365
1366 let (upload_url, mirror_urls) = match encrypted {
1370 None => {
1373 callback.on_upload_complete(receiver_npub, &pending_id, &file_hash, &att_url);
1374 if reused.as_ref().is_some_and(|r| !r.mine) {
1378 let signer_bg = signer.clone();
1379 let url_bg = att_url.clone();
1380 crate::db::spawn_bound(async move {
1381 let _ = crate::blossom::mirror_blob_to_servers(
1382 signer_bg, &url_bg, crate::state::get_blossom_servers(),
1383 1, std::time::Duration::from_secs(8), &[],
1384 ).await;
1385 });
1386 }
1387 (att_url.clone(), Vec::new())
1388 }
1389 Some(encrypted) => {
1390 #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
1391 let body = encrypted.clone();
1392 let accepted = match crate::blossom::upload_body_with_progress_and_failover(
1393 signer.clone(), servers, encrypted, Some(mime_type),
1394 true,
1395 progress_cb, Some(config.upload_retries), Some(config.upload_retry_delay),
1396 cancel.clone(),
1397 ).await {
1398 Ok(accepted) => accepted,
1399 Err(e) => {
1400 #[cfg(not(target_arch = "wasm32"))]
1401 if !cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed)) {
1402 keep_for_retry(&body, ciphertext_file, &file_hash, &att_key, &att_nonce, &pending_id, mime_type);
1403 }
1404 return Err(mark_send_failed(&callback, receiver_npub, &pending_id, format!("Upload failed: {}", e)).await);
1405 }
1406 };
1407 #[cfg(not(target_arch = "wasm32"))]
1409 if crate::media::keep_media() && keep_sent(&body, &file_hash, &att_key, &att_nonce, plain_len, mime_type) {
1410 let mut state = STATE.lock().await;
1411 state.update_message(&pending_id, |msg| {
1412 if let Some(att) = msg.attachments.last_mut() {
1413 att.set_downloaded(true);
1414 }
1415 });
1416 }
1417
1418 let upload_url = accepted.url.clone();
1419 {
1420 let mut state = STATE.lock().await;
1421 state.update_message(&pending_id, |msg| {
1422 if let Some(att) = msg.attachments.last_mut() {
1423 att.url = upload_url.clone().into_boxed_str();
1424 }
1425 });
1426 }
1427 callback.on_upload_complete(receiver_npub, &pending_id, &file_hash, &upload_url);
1428
1429 let mirror_urls = crate::blossom::mirror_blob_to_servers(
1433 signer.clone(),
1434 &upload_url,
1435 crate::state::get_blossom_servers(),
1436 2,
1437 std::time::Duration::from_secs(5),
1438 std::slice::from_ref(&accepted.server),
1439 ).await;
1440 if !mirror_urls.is_empty() {
1441 let mut state = STATE.lock().await;
1442 state.update_message(&pending_id, |msg| {
1443 if let Some(att) = msg.attachments.last_mut() {
1444 att.set_fallback_urls(mirror_urls.iter().map(|s| s.as_str().into()));
1445 }
1446 });
1447 }
1448 (upload_url, mirror_urls)
1449 }
1450 };
1451
1452 if cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed)) {
1455 return Err("Upload cancelled".to_string());
1456 }
1457
1458 let mut file_rumor = EventBuilder::new(Kind::from_u16(15), &upload_url)
1460 .custom_created_at(Timestamp::from_secs(now.as_secs()))
1461 .tag(Tag::public_key(receiver))
1462 .tag(Tag::custom("file-type", [mime_type]))
1463 .tag(Tag::custom("size", [encrypted_size.to_string()]))
1464 .tag(Tag::custom("encryption-algorithm", ["aes-gcm"]))
1465 .tag(Tag::custom("decryption-key", [att_key.as_str()]))
1466 .tag(Tag::custom("decryption-nonce", [att_nonce.as_str()]))
1467 .tag(Tag::custom("ox", [file_hash.clone()]));
1468 if let Some(reply_id) = reply_to {
1469 file_rumor = file_rumor.tag(Tag::custom(
1470 "e",
1471 [reply_id.to_string(), String::new(), "reply".to_string()],
1472 ));
1473 }
1474 for fb in &mirror_urls {
1475 file_rumor = file_rumor.tag(Tag::custom("fallback", [fb.as_str()]));
1476 }
1477 if !filename.is_empty() {
1478 file_rumor = file_rumor.tag(Tag::custom("name", [filename]));
1479 }
1480 if let Some(ref topic) = webxdc_topic {
1481 file_rumor = file_rumor.tag(Tag::custom("webxdc-topic", [topic.as_str()]));
1482 }
1483 if let Some(ref meta) = img_meta {
1485 if !meta.thumbhash.is_empty() {
1486 file_rumor = file_rumor.tag(Tag::custom("thumbhash", [meta.thumbhash.as_str()]));
1489 }
1490 file_rumor = file_rumor.tag(Tag::custom("dim", [format!("{}x{}", meta.width, meta.height)]));
1491 }
1492 file_rumor = file_rumor.tag(Tag::custom("ms", [milliseconds.to_string()]));
1493 let expiration = config
1496 .self_destruct_secs
1497 .and_then(crate::self_destruct::expiry_after)
1498 .or(config.expiration);
1499 if let Some(exp) = expiration {
1500 file_rumor = file_rumor.tag(Tag::expiration(Timestamp::from_secs(exp)));
1501 let mut state = STATE.lock().await;
1502 state.update_message(&pending_id, |msg| { msg.expiration_secs = exp as u32; });
1503 }
1504
1505 let built_rumor = file_rumor.finalize_unsigned_with_id(my_pk);
1506 let event_id = built_rumor.id.ok_or("Rumor has no id")?.to_hex();
1507
1508 retry_send_gift_wrap(
1509 &client, &receiver, receiver_npub, &pending_id,
1510 built_rumor, &event_id, config, callback, None,
1511 ).await
1512}
1513
1514#[cfg(test)]
1519mod tests {
1520 use super::*;
1521 use std::sync::Mutex;
1522
1523 #[derive(Debug, Clone, PartialEq)]
1524 enum CbEvent {
1525 Pending(String),
1526 UploadProgress(String, u8, u64),
1527 UploadComplete(String, String),
1528 Sent(String, String),
1529 Failed(String, String),
1530 Persist(String),
1531 }
1532
1533 struct MockCallback {
1534 events: Mutex<Vec<CbEvent>>,
1535 cancel_at: Option<u8>,
1536 }
1537
1538 impl MockCallback {
1539 fn new() -> Self { Self { events: Mutex::new(vec![]), cancel_at: None } }
1540 fn with_cancel(pct: u8) -> Self { Self { events: Mutex::new(vec![]), cancel_at: Some(pct) } }
1541 fn events(&self) -> Vec<CbEvent> { self.events.lock().unwrap().clone() }
1542 }
1543
1544 impl SendCallback for MockCallback {
1545 fn on_pending(&self, cid: &str, _: &Message) {
1546 self.events.lock().unwrap().push(CbEvent::Pending(cid.into()));
1547 }
1548 fn on_upload_progress(&self, pid: &str, pct: u8, bytes: u64) -> Result<(), String> {
1549 self.events.lock().unwrap().push(CbEvent::UploadProgress(pid.into(), pct, bytes));
1550 if self.cancel_at.map_or(false, |c| pct >= c) { return Err("Cancelled".into()); }
1551 Ok(())
1552 }
1553 fn on_upload_complete(&self, cid: &str, _: &str, _: &str, url: &str) {
1554 self.events.lock().unwrap().push(CbEvent::UploadComplete(cid.into(), url.into()));
1555 }
1556 fn on_sent(&self, cid: &str, old: &str, _: &Message) {
1557 self.events.lock().unwrap().push(CbEvent::Sent(cid.into(), old.into()));
1558 }
1559 fn on_failed(&self, cid: &str, old: &str, _: &Message) {
1560 self.events.lock().unwrap().push(CbEvent::Failed(cid.into(), old.into()));
1561 }
1562 fn on_persist(&self, cid: &str, _: &Message) {
1563 self.events.lock().unwrap().push(CbEvent::Persist(cid.into()));
1564 }
1565 }
1566
1567 #[test]
1568 fn config_default() {
1569 let c = SendConfig::default();
1570 assert_eq!(c.max_send_attempts, 1);
1571 assert!(!c.self_send);
1572 assert!(c.cancel_token.is_none());
1573 assert_eq!(c.upload_retries, 3);
1574 }
1575
1576 #[test]
1577 fn config_gui() {
1578 let c = SendConfig::gui();
1579 assert_eq!(c.max_send_attempts, 12);
1580 assert!(c.self_send);
1581 }
1582
1583 #[test]
1584 fn config_headless() {
1585 let c = SendConfig::headless();
1586 assert_eq!(c.max_send_attempts, 3);
1587 assert!(c.self_send);
1588 }
1589
1590 #[test]
1591 fn config_custom_override() {
1592 let c = SendConfig { max_send_attempts: 5, ..SendConfig::gui() };
1593 assert_eq!(c.max_send_attempts, 5);
1594 assert!(c.self_send);
1595 }
1596
1597 #[test]
1598 fn noop_callback_all_methods() {
1599 let cb = NoOpSendCallback;
1600 let msg = Message::default();
1601 cb.on_pending("c", &msg);
1602
1603 assert!(cb.on_upload_progress("p", 50, 1024).is_ok());
1604 cb.on_upload_complete("c", "p", "a", "url");
1605 cb.on_sent("c", "o", &msg);
1606 cb.on_failed("c", "o", &msg);
1607 cb.on_persist("c", &msg);
1608 }
1609
1610 #[test]
1611 fn text_dm_sequence() {
1612 let cb = MockCallback::new();
1613 let msg = Message::default();
1614 cb.on_pending("r", &msg);
1615 cb.on_sent("r", "p-1", &msg);
1616 cb.on_persist("r", &msg);
1617 assert_eq!(cb.events(), vec![
1618 CbEvent::Pending("r".into()),
1619 CbEvent::Sent("r".into(), "p-1".into()),
1620 CbEvent::Persist("r".into()),
1621 ]);
1622 }
1623
1624 #[test]
1625 fn file_dm_sequence() {
1626 let cb = MockCallback::new();
1627 let msg = Message::default();
1628 cb.on_pending("r", &msg);
1629
1630 cb.on_upload_progress("p", 0, 0).ok();
1631 cb.on_upload_progress("p", 50, 5000).ok();
1632 cb.on_upload_progress("p", 100, 10000).ok();
1633 cb.on_upload_complete("r", "p", "h", "https://blossom/h");
1634 cb.on_sent("r", "p", &msg);
1635 cb.on_persist("r", &msg);
1636 let e = cb.events();
1637 assert_eq!(e.len(), 7);
1638 assert!(matches!(&e[4], CbEvent::UploadComplete(_, url) if url.contains("blossom")));
1639 }
1640
1641 #[test]
1642 fn failed_sequence() {
1643 let cb = MockCallback::new();
1644 let msg = Message::default();
1645 cb.on_pending("r", &msg);
1646 cb.on_failed("r", "p", &msg);
1647 cb.on_persist("r", &msg);
1648 assert_eq!(cb.events(), vec![
1649 CbEvent::Pending("r".into()),
1650 CbEvent::Failed("r".into(), "p".into()),
1651 CbEvent::Persist("r".into()),
1652 ]);
1653 }
1654
1655 #[test]
1656 fn cancel_upload_at_threshold() {
1657 let cb = MockCallback::with_cancel(50);
1658 assert!(cb.on_upload_progress("p", 25, 512).is_ok());
1659 assert!(cb.on_upload_progress("p", 50, 1024).is_err());
1660 assert_eq!(cb.events().len(), 2);
1661 }
1662
1663 #[test]
1664 fn cancel_triggers_failed() {
1665 let cb = MockCallback::with_cancel(30);
1666 let msg = Message::default();
1667 cb.on_pending("r", &msg);
1668
1669 cb.on_upload_progress("p", 10, 1000).ok();
1670 assert!(cb.on_upload_progress("p", 30, 3000).is_err());
1671 cb.on_failed("r", "p", &msg);
1672 assert!(matches!(cb.events().last(), Some(CbEvent::Failed(..))));
1673 }
1674
1675 #[test]
1676 fn send_result_serialize() {
1677 let r = SendResult { pending_id: "p".into(), event_id: Some("e".into()), chat_id: "c".into() };
1678 let j = serde_json::to_string(&r).unwrap();
1679 assert!(j.contains("\"pending_id\":\"p\""));
1680 }
1681
1682 #[test]
1683 fn send_result_none_event() {
1684 let r = SendResult { pending_id: "p".into(), event_id: None, chat_id: "c".into() };
1685 let j = serde_json::to_string(&r).unwrap();
1686 assert!(j.contains("null"));
1687 }
1688
1689 #[test]
1694 fn file_dm_fresh_upload_full_sequence() {
1695 let cb = MockCallback::new();
1696 let msg = Message::default();
1697
1698 cb.on_pending("npub1recv", &msg);
1700 cb.on_upload_progress("pending-42", 0, 0).unwrap();
1704 cb.on_upload_progress("pending-42", 25, 2500).unwrap();
1705 cb.on_upload_progress("pending-42", 50, 5000).unwrap();
1706 cb.on_upload_progress("pending-42", 75, 7500).unwrap();
1707 cb.on_upload_progress("pending-42", 100, 10000).unwrap();
1708 cb.on_upload_complete("npub1recv", "pending-42", "deadbeef", "https://blossom.example/deadbeef");
1710 cb.on_sent("npub1recv", "pending-42", &msg);
1712 cb.on_persist("npub1recv", &msg);
1714
1715 let e = cb.events();
1716 assert_eq!(e.len(), 9);
1717 assert!(matches!(&e[0], CbEvent::Pending(c) if c == "npub1recv"));
1718 assert!(matches!(&e[1], CbEvent::UploadProgress(_, 0, 0)));
1719 assert!(matches!(&e[5], CbEvent::UploadProgress(_, 100, 10000)));
1720 assert!(matches!(&e[6], CbEvent::UploadComplete(_, url) if url.contains("deadbeef")));
1721 assert!(matches!(&e[7], CbEvent::Sent(..)));
1722 assert!(matches!(&e[8], CbEvent::Persist(..)));
1723 }
1724
1725 #[test]
1726 fn file_dm_skip_upload_sequence() {
1727 let cb = MockCallback::new();
1728 let msg = Message::default();
1729
1730 cb.on_pending("npub1recv", &msg);
1733 cb.on_upload_complete("npub1recv", "pending-99", "existinghash", "https://blossom.example/existing");
1737 cb.on_sent("npub1recv", "pending-99", &msg);
1739 cb.on_persist("npub1recv", &msg);
1741
1742 let e = cb.events();
1743 assert_eq!(e.len(), 4);
1744 assert!(!e.iter().any(|ev| matches!(ev, CbEvent::UploadProgress(..))));
1746 assert!(matches!(&e[1], CbEvent::UploadComplete(..)));
1747 }
1748
1749 #[test]
1750 fn file_dm_upload_cancelled_at_30pct() {
1751 let cb = MockCallback::with_cancel(30);
1752 let msg = Message::default();
1753
1754 cb.on_pending("npub1recv", &msg);
1755
1756 assert!(cb.on_upload_progress("p", 10, 1000).is_ok());
1757 assert!(cb.on_upload_progress("p", 20, 2000).is_ok());
1758 let err = cb.on_upload_progress("p", 30, 3000);
1760 assert!(err.is_err());
1761 assert!(err.unwrap_err().contains("Cancelled"));
1762 cb.on_failed("npub1recv", "p", &msg);
1764
1765 let e = cb.events();
1766 assert_eq!(e.len(), 5);
1767 assert!(!e.iter().any(|ev| matches!(ev, CbEvent::Sent(..))));
1769 assert!(matches!(e.last(), Some(CbEvent::Failed(..))));
1770 }
1771
1772 #[test]
1773 fn file_dm_upload_fails_marks_failed() {
1774 let cb = MockCallback::new();
1775 let msg = Message::default();
1776
1777 cb.on_pending("npub1recv", &msg);
1778
1779 cb.on_upload_progress("p", 0, 0).ok();
1780 cb.on_upload_progress("p", 10, 500).ok();
1781 cb.on_failed("npub1recv", "p", &msg);
1783 cb.on_persist("npub1recv", &msg);
1784
1785 let e = cb.events();
1786 assert_eq!(e.len(), 5);
1787 assert!(matches!(&e[3], CbEvent::Failed(..)));
1788 assert!(matches!(&e[4], CbEvent::Persist(..)));
1789 assert!(!e.iter().any(|ev| matches!(ev, CbEvent::UploadComplete(..))));
1791 assert!(!e.iter().any(|ev| matches!(ev, CbEvent::Sent(..))));
1792 }
1793
1794 #[test]
1795 fn file_dm_gift_wrap_fails_after_upload() {
1796 let cb = MockCallback::new();
1797 let msg = Message::default();
1798
1799 cb.on_pending("npub1recv", &msg);
1801
1802 cb.on_upload_progress("p", 100, 10000).ok();
1803 cb.on_upload_complete("npub1recv", "p", "hash", "https://blossom/hash");
1804 cb.on_failed("npub1recv", "p", &msg);
1806 cb.on_persist("npub1recv", &msg);
1807
1808 let e = cb.events();
1809 assert_eq!(e.len(), 5);
1810 assert!(matches!(&e[2], CbEvent::UploadComplete(..)));
1812 assert!(matches!(&e[3], CbEvent::Failed(..)));
1813 }
1814
1815 #[test]
1816 fn file_dm_with_image_metadata_sequence() {
1817 let cb = MockCallback::new();
1818 let msg = Message::default();
1819
1820 cb.on_pending("npub1recv", &msg);
1822
1823 cb.on_upload_progress("p", 0, 0).ok();
1824 cb.on_upload_progress("p", 50, 50000).ok();
1825 cb.on_upload_progress("p", 100, 100000).ok();
1826 cb.on_upload_complete("npub1recv", "p", "imghash", "https://blossom/imghash.jpg");
1827 cb.on_sent("npub1recv", "p", &msg);
1828 cb.on_persist("npub1recv", &msg);
1829
1830 let e = cb.events();
1831 assert_eq!(e.len(), 7);
1832 assert!(matches!(&e[0], CbEvent::Pending(..)));
1834 assert!(matches!(&e[4], CbEvent::UploadComplete(_, url) if url.ends_with(".jpg")));
1835 assert!(matches!(&e[5], CbEvent::Sent(..)));
1836 }
1837
1838 #[test]
1839 fn cancel_token_config_with_upload() {
1840 let token = Arc::new(std::sync::atomic::AtomicBool::new(false));
1841 let c = SendConfig {
1842 cancel_token: Some(token.clone()),
1843 ..SendConfig::gui()
1844 };
1845 assert!(c.cancel_token.is_some());
1846 assert!(!token.load(std::sync::atomic::Ordering::Relaxed));
1847
1848 token.store(true, std::sync::atomic::Ordering::Relaxed);
1850 assert!(c.cancel_token.as_ref().unwrap().load(std::sync::atomic::Ordering::Relaxed));
1851 }
1852}
1853
1854#[cfg(test)]
1855mod seal_tests {
1856 use super::*;
1857 use std::sync::Mutex;
1858
1859 #[derive(Default)]
1860 struct Stages(Mutex<Vec<(String, Option<u8>)>>);
1861 impl SendCallback for Stages {
1862 fn on_upload_stage(&self, _: &str, stage: &str, pct: Option<u8>) {
1863 self.0.lock().unwrap().push((stage.to_string(), pct));
1864 }
1865 }
1866
1867 #[tokio::test]
1868 async fn bytes_and_files_seal_to_what_their_key_opens() {
1869 let plain: Vec<u8> = (0..300_000u32).map(|i| (i * 7 % 251) as u8).collect();
1870 let params = crypto::generate_encryption_params();
1871 let hash = crypto::sha256_hex(&plain);
1872 let src = std::env::temp_dir().join(format!("vector-seal-{}.bin", std::process::id()));
1873 std::fs::write(&src, &plain).unwrap();
1874
1875 for source in [FileSource::Bytes(Arc::new(plain.clone())), FileSource::Path(src.clone())] {
1876 let from_file = matches!(source, FileSource::Path(_));
1877 let stages = Arc::new(Stages::default());
1878 let sealed = seal_or_reuse(source, &hash, ¶ms.key, ¶ms.nonce, "pending-1", stages.clone(), None).await.unwrap();
1879 let Sealed::Body(body, guard) = sealed else { panic!("nothing to reuse without a database") };
1880 let ciphertext = match &body {
1881 crate::blossom::UploadBody::Memory(b) => b.to_vec(),
1882 crate::blossom::UploadBody::File { path, .. } => std::fs::read(path).unwrap(),
1883 };
1884 assert_eq!(body.len(), plain.len() as u64 + 16);
1885 assert_eq!(crypto::decrypt_data(&ciphertext, ¶ms.key, ¶ms.nonce).unwrap(), plain);
1886 let stages = stages.0.lock().unwrap().clone();
1887 assert_eq!(stages.first().unwrap().0, "encrypting");
1888 assert_eq!(stages.last().unwrap(), &("starting".to_string(), None));
1889 assert_eq!(guard.is_some(), from_file);
1890 if let crate::blossom::UploadBody::File { path, .. } = &body {
1891 drop(guard);
1892 assert!(!path.exists(), "the ciphertext goes with its guard");
1893 }
1894 }
1895 let _ = std::fs::remove_file(&src);
1896 }
1897
1898 #[tokio::test]
1899 async fn an_upload_shows_the_bytes_in_hand_while_it_goes() {
1900 struct Shown(Mutex<Option<Message>>);
1901 impl SendCallback for Shown {
1902 fn on_pending(&self, _: &str, msg: &Message) {
1903 *self.0.lock().unwrap() = Some(msg.clone());
1904 }
1905 }
1906 let session = crate::db::Session::empty();
1907 let me = Keys::generate();
1908 let file = std::env::temp_dir().join(format!("vector-shown-{}.bin", std::process::id()));
1909 std::fs::write(&file, vec![7u8; 4096]).unwrap();
1910 let shown = Arc::new(Shown(Mutex::new(None)));
1911 crate::db::with_session(session, async {
1912 crate::state::set_nostr_client(crate::nostr_client_builder().build());
1913 crate::state::set_my_public_key(me.public_key());
1914 crate::signer::set_test_signer(Some(crate::signer::ActiveSigner::Keys(me.clone())));
1915 let config = SendConfig { cancel_token: Some(Arc::new(AtomicBool::new(true))), ..SendConfig::default() };
1917 let to = Keys::generate().public_key().to_bech32().unwrap();
1918 let sent = send_file_dm_from(&to, FileSource::Path(file.clone()), "a.bin", "bin", None, None, None, &config, shown.clone()).await;
1919 crate::signer::set_test_signer(None);
1920 assert!(sent.is_err(), "the cancelled send ends failed");
1921 })
1922 .await;
1923 let _ = std::fs::remove_file(&file);
1924 let msg = shown.0.lock().unwrap().clone().expect("the bubble went up");
1925 let att = &msg.attachments[0];
1926 assert!(!att.downloaded && att.path.is_empty(), "the sender keeps no copy of its own");
1927 assert!(att.resident, "the bubble draws the bytes it's sending, rather than offering to download them");
1928 }
1929
1930 #[tokio::test]
1931 async fn a_pending_wrap_confirm_does_not_keep_its_account_alive() {
1932 let session = crate::db::Session::empty();
1933 struct NoCallback;
1934 impl SendCallback for NoCallback {}
1935 let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "hi").finalize_unsigned_with_id(Keys::generate().public_key());
1936 crate::db::with_session(session.clone(), async {
1937 register_wrap_confirm(Arc::new(WrapConfirm {
1938 wrap_id: EventId::from_byte_array([0; 32]),
1939 chat_id: String::new(),
1940 pending_id: String::new(),
1941 rumor_event_id: String::new(),
1942 rumor,
1943 callback: Arc::new(NoCallback),
1944 self_send: false,
1945 confirmed: AtomicBool::new(false),
1946 rescued: AtomicBool::new(false),
1947 loop_exited: AtomicBool::new(true),
1948 notify: tokio::sync::Notify::new(),
1949 session: Arc::downgrade(&crate::db::current_session()),
1950 registered_at: web_time::Instant::now(),
1951 }));
1952 assert_eq!(wrap_confirms().lock().unwrap().len(), 1, "registered on this session");
1953 })
1954 .await;
1955 assert_eq!(Arc::strong_count(&session), 1, "the registry's entry holds no strong reference");
1956 let weak = Arc::downgrade(&session);
1957 drop(session);
1958 assert!(weak.upgrade().is_none(), "the account is freed once nothing else holds it");
1959 }
1960}