Skip to main content

vector_core/
wallpaper.rs

1//! Per-DM wallpaper feature.
2//!
3//! Wallpapers are static images attached to a 1:1 DM conversation. Either
4//! party may set one; latest-write-wins by rumor `created_at`.
5//!
6//! On the wire: a NIP-17 gift-wrapped rumor with kind 30078 and the d tag
7//! `vector-wallpaper`. The wallpaper bytes themselves are AES-256-GCM
8//! encrypted onto Blossom — same crypto path Vector uses for normal file
9//! attachments. The decryption key + nonce live in the rumor's tags; that's
10//! safe because the rumor is already sealed inside the NIP-17 envelope
11//! addressed only to the two participants.
12//!
13//! Rumor shape:
14//! ```text
15//!   kind:       30078 (APPLICATION_SPECIFIC)
16//!   created_at: now (latest-write-wins tiebreaker)
17//!   tags:
18//!     ["d",                "vector-wallpaper"]
19//!     ["url",              <blossom URL>]
20//!     ["decryption-key",   <hex>]
21//!     ["decryption-nonce", <hex>]
22//!     ["x",                <plaintext sha256>]
23//!     ["m",                "image/png"]   (optional)
24//!     ["size",             <encrypted size in bytes>]
25//!   content: "" (unused; metadata lives in tags)
26//! ```
27
28use crate::event_ext::FinalizeUnsignedWithId;
29use std::path::{Path, PathBuf};
30use std::sync::Arc;
31use std::time::Duration;
32
33use nostr_sdk::prelude::*;
34use serde::{Deserialize, Serialize};
35
36use crate::crypto;
37use crate::stored_event::event_kind;
38
39const WALLPAPER_DTAG_VALUE: &str = "vector-wallpaper";
40
41/// Hard ceiling on a received (encrypted) wallpaper download. The send side
42/// caps plaintext at 5 MB; 10 MB leaves headroom for encryption overhead
43/// while still bounding memory against a malicious/oversized blob.
44const MAX_WALLPAPER_DOWNLOAD_BYTES: u64 = 10 * 1024 * 1024;
45/// Longest side a received SVG wallpaper is rendered at.
46const WALLPAPER_SVG_DIM: u32 = 2560;
47
48/// A received wallpaper, judged by its bytes: a raster image keeps its own format, an SVG becomes
49/// the pixels it draws (its markup never reaches the webview), anything else is refused.
50fn normalize_received(bytes: Vec<u8>) -> Result<(Vec<u8>, &'static str), String> {
51    let ext = match crypto::mime_from_magic_bytes(&bytes) {
52        "image/png" => "png",
53        "image/jpeg" => "jpg",
54        "image/gif" => "gif",
55        "image/webp" => "webp",
56        _ if crate::svg::looks_like_svg(&bytes) => {
57            return Ok((crate::svg::rasterize_png(&bytes, WALLPAPER_SVG_DIM)?, "png"));
58        }
59        _ => return Err("Wallpaper is not an image".into()),
60    };
61    Ok((bytes, ext))
62}
63
64/// Maximum allowed source-image size (pre-encryption). Matches the user-
65/// facing cap; enforced both at preview prep and at the picker UI.
66pub const MAX_WALLPAPER_BYTES: usize = 5 * 1024 * 1024;
67
68/// Longest-side cap for the re-encoded wallpaper — ample for any display, and
69/// keeps a huge source from bloating every gift-wrapped send.
70const MAX_WALLPAPER_DIMENSION: u32 = 2560;
71
72/// Per-account directory for cached wallpaper files. One active file per
73/// chat + at most one preview-staging file per chat.
74fn wallpapers_dir() -> Result<PathBuf, String> {
75    let npub = crate::db::get_current_account()?;
76    Ok(crate::db::account_dir(&npub)?.join("wallpapers"))
77}
78
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct WallpaperPreview {
81    /// Local cached path the frontend should render.
82    pub path: String,
83    /// True iff the picker had to extract a frame from an animated source.
84    /// The UI uses this to surface a one-line "static-only" notice.
85    pub was_animated: bool,
86    /// Suggested initial brightness (0..=100) derived from the image's
87    /// average luma — bright images get more dimming so text stays
88    /// readable, dark images keep more of the original. User can still
89    /// override with the slider before confirming.
90    pub recommended_dim: u8,
91}
92
93/// Validate + prepare a picked image: enforce the 5 MB cap, image-only
94/// mime, extract first frame for animated formats, write to the per-chat
95/// preview slot. The returned path is what the chat background should
96/// switch to while the Confirm/Cancel bar is showing.
97pub async fn prepare_wallpaper_preview(
98    chat_npub: &str,
99    file_path: &str,
100) -> Result<WallpaperPreview, String> {
101    let bytes = crate::files::read(Path::new(file_path))
102        .await
103        .map_err(|e| format!("Failed to read image: {}", e))?;
104
105    if bytes.len() > MAX_WALLPAPER_BYTES {
106        return Err(format!(
107            "Image is too large ({} MB). Wallpapers max out at {} MB.",
108            bytes.len() / (1024 * 1024),
109            MAX_WALLPAPER_BYTES / (1024 * 1024),
110        ));
111    }
112
113    let mime = crypto::mime_from_magic_bytes(&bytes).to_string();
114    let is_svg = crate::svg::looks_like_svg(&bytes);
115    if !mime.starts_with("image/") && !is_svg {
116        return Err("Wallpapers must be image files.".to_string());
117    }
118
119    // Single decode: normalize (strip + resize + re-encode) and the brightness
120    // estimate share the same decoded pixels — no second decode. Off the runtime:
121    // a full-size decode would stall every task queued behind it.
122    let (final_bytes, final_extension, was_animated, recommended_dim) =
123        crate::rt::spawn_blocking(move || normalize_picked(&bytes, &mime, is_svg))
124            .await
125            .map_err(|e| format!("Image processing task failed: {e}"))??;
126
127    // Clear any prior preview for this chat (different format or stale).
128    clean_chat_files(chat_npub, FileKind::Preview, None).await?;
129
130    let preview = wallpapers_dir()?.join(format!("{}.preview.{}", chat_npub, final_extension));
131    crate::files::write_cache(&preview, &final_bytes)
132        .await
133        .map_err(|e| format!("Failed to stage preview file: {}", e))?;
134
135    Ok(WallpaperPreview {
136        path: preview.to_string_lossy().to_string(),
137        was_animated,
138        recommended_dim,
139    })
140}
141
142/// Pick a starting brightness percent such that white chat text stays
143/// readable against the image. Down-samples to 64×64 for speed, averages
144/// the Rec. 709 luma, then maps `(avg_luma 0..=255)` to a brightness
145/// percent — bright images get dimmer defaults, dark images stay bright.
146/// Operates on the already-decoded wallpaper (no re-decode); falls back to
147/// the 50% default for a degenerate (zero-size) image.
148fn estimate_brightness_for_white_text(img: &::image::DynamicImage) -> u8 {
149    use ::image::GenericImageView;
150
151    let thumb = img.thumbnail(64, 64);
152    let rgb = thumb.to_rgb8();
153    let (w, h) = thumb.dimensions();
154    if w == 0 || h == 0 {
155        return 50;
156    }
157    let mut sum: u64 = 0;
158    let mut count: u64 = 0;
159    for pixel in rgb.pixels() {
160        let r = pixel[0] as f32;
161        let g = pixel[1] as f32;
162        let b = pixel[2] as f32;
163        let y = 0.2126 * r + 0.7152 * g + 0.0722 * b;
164        sum += y as u64;
165        count += 1;
166    }
167    if count == 0 {
168        return 50;
169    }
170    let avg = (sum / count) as f32; // 0..=255
171    // Map luma → brightness with an aggressive curve, then halve to land
172    // most photographs in the 15..30% range where white chat text is
173    // clearly legible against the underlying image:
174    //   white  (255) → ~12
175    //   bright (200) → ~17
176    //   mid    (128) → ~22
177    //   dark   ( 60) → ~38
178    //   black  (  0) → ~47
179    let brightness = (95.0 - (avg / 255.0) * 70.0) / 2.0;
180    brightness.clamp(10.0, 50.0) as u8
181}
182
183/// Delete the preview file (user cancelled before publishing).
184pub async fn cancel_wallpaper_preview(chat_npub: &str) -> Result<(), String> {
185    clean_chat_files(chat_npub, FileKind::Preview, None).await
186}
187
188/// Returns `(bytes, extension, was_animated, recommended_dim)`. Every wallpaper
189/// is decoded ONCE (baking EXIF orientation into pixels) and re-encoded to a
190/// still: this both flattens any animation (wallpapers never animate) AND drops
191/// all metadata. The wallpaper is gift-wrapped to the other participant, so
192/// their copy must not carry our EXIF/GPS. Opaque images become JPEG (small);
193/// images with real transparency stay PNG. The brightness estimate reuses the
194/// same decoded pixels rather than decoding again.
195///
196/// Downscaling uses Triangle (bilinear): a wallpaper is shown behind blur + dim,
197/// so the extra sharpness of a wide-kernel filter is invisible and not worth the
198/// cost on slow devices.
199/// A picked SVG is published as its render, so no peer ever receives the markup.
200fn normalize_picked(bytes: &[u8], mime: &str, is_svg: bool) -> Result<(Vec<u8>, String, bool, u8), String> {
201    if !is_svg {
202        return normalize_wallpaper_image(bytes, mime);
203    }
204    let png = crate::svg::rasterize_png(bytes, WALLPAPER_SVG_DIM)
205        .map_err(|_| "That SVG is too complex to use as a wallpaper.".to_string())?;
206    normalize_wallpaper_image(&png, "image/png")
207}
208
209fn normalize_wallpaper_image(
210    src: &[u8],
211    mime: &str,
212) -> Result<(Vec<u8>, String, bool, u8), String> {
213    let was_animated = mime == "image/gif" || mime == "image/webp";
214
215    let mut img = crate::crypto::decode_image_bounded(src)?;
216    if img.width() > MAX_WALLPAPER_DIMENSION || img.height() > MAX_WALLPAPER_DIMENSION {
217        img = img.resize(
218            MAX_WALLPAPER_DIMENSION,
219            MAX_WALLPAPER_DIMENSION,
220            ::image::imageops::FilterType::Triangle,
221        );
222    }
223
224    let recommended_dim = estimate_brightness_for_white_text(&img);
225    let (bytes, ext) = encode_wallpaper_still(&img)?;
226    Ok((bytes, ext, was_animated, recommended_dim))
227}
228
229/// Re-encode a decoded wallpaper as a metadata-free still: PNG when real
230/// transparency is present, otherwise JPEG (much smaller for photos).
231fn encode_wallpaper_still(img: &::image::DynamicImage) -> Result<(Vec<u8>, String), String> {
232    use ::image::{ExtendedColorType, ImageEncoder};
233    use std::io::Cursor;
234
235    let mut out = Vec::new();
236    if img.color().has_alpha() {
237        let rgba = img.to_rgba8();
238        if rgba.pixels().any(|p| p.0[3] != 255) {
239            ::image::codecs::png::PngEncoder::new(Cursor::new(&mut out))
240                .write_image(rgba.as_raw(), rgba.width(), rgba.height(), ExtendedColorType::Rgba8)
241                .map_err(|e| format!("Failed to encode wallpaper: {}", e))?;
242            return Ok((out, "png".to_string()));
243        }
244    }
245    let rgb = img.to_rgb8();
246    ::image::codecs::jpeg::JpegEncoder::new_with_quality(Cursor::new(&mut out), 88)
247        .write_image(rgb.as_raw(), rgb.width(), rgb.height(), ExtendedColorType::Rgb8)
248        .map_err(|e| format!("Failed to encode wallpaper: {}", e))?;
249    Ok((out, "jpg".to_string()))
250}
251
252#[derive(Copy, Clone)]
253enum FileKind {
254    Preview,
255    Active,
256}
257
258/// Remove every wallpaper artifact for `chat_npub` of the given kind. When
259/// `extension_to_skip` is `Some`, files matching that extension are kept
260/// (used to overwrite-in-place during same-format rewrites).
261async fn clean_chat_files(
262    chat_npub: &str,
263    kind: FileKind,
264    extension_to_skip: Option<&str>,
265) -> Result<(), String> {
266    let dir = wallpapers_dir()?;
267
268    let preview_prefix = format!("{}.preview.", chat_npub);
269    let active_prefix = format!("{}.", chat_npub);
270
271    for path in crate::files::list(&dir).await {
272        let name = match path.file_name().and_then(|n| n.to_str()) {
273            Some(n) => n.to_string(),
274            None => continue,
275        };
276        let matches = match kind {
277            FileKind::Preview => name.starts_with(&preview_prefix),
278            // Active = chat-prefixed but NOT preview-prefixed.
279            FileKind::Active => name.starts_with(&active_prefix) && !name.starts_with(&preview_prefix),
280        };
281        if !matches {
282            continue;
283        }
284        if let Some(ext) = extension_to_skip {
285            let suffix = format!(".{}", ext);
286            if name.ends_with(&suffix) {
287                continue;
288            }
289        }
290        crate::files::remove(&path).await;
291    }
292    Ok(())
293}
294
295/// Publish the current preview file as the chat's wallpaper. Encrypts +
296/// uploads to Blossom, builds the kind-30078 rumor, sends to the
297/// counterparty (the gift-wrap helper fans out to self for cross-device
298/// sync), promotes the preview file to the active slot, updates STATE +
299/// DB, drops a `WallpaperChanged` system event, and emits
300/// `wallpaper_updated` to the frontend.
301///
302/// `blur` and `dim` are the customisation knobs the user set on the
303/// preview slider — clamped here to safe ranges and carried as optional
304/// tags on the rumor so older clients without slider support still get a
305/// usable wallpaper (falling back to their own defaults).
306pub async fn publish_wallpaper(chat_npub: &str, blur: u8, dim: u8) -> Result<(), String> {
307    // Capture session at entry — the upload + gift-wrap send below take
308    // seconds, and a mid-publish account swap must not write this
309    // wallpaper into the new account (re-checked before the STATE/DB write).
310
311    let blur = blur.min(30);
312    let dim = dim.min(100);
313    // Find the preview file (we don't know its extension ahead of time).
314    let dir = wallpapers_dir()?;
315    let prefix = format!("{}.preview.", chat_npub);
316    let mut preview_path: Option<PathBuf> = None;
317    for p in crate::files::list(&dir).await {
318        let n = p
319            .file_name()
320            .and_then(|n| n.to_str())
321            .unwrap_or("")
322            .to_string();
323        if n.starts_with(&prefix) {
324            preview_path = Some(p);
325            break;
326        }
327    }
328    let preview = preview_path
329        .ok_or_else(|| "No wallpaper preview to publish. Pick an image first.".to_string())?;
330    let bytes = crate::files::read_cache(&preview)
331        .await
332        .map_err(|e| format!("Failed to read preview file: {}", e))?;
333
334    let extension = preview
335        .extension()
336        .and_then(|e| e.to_str())
337        .unwrap_or("png")
338        .to_string();
339    let mime = crypto::mime_from_extension(&extension).to_string();
340    let plaintext_hash = crypto::sha256_hex(&bytes);
341
342    let params = crypto::generate_encryption_params();
343    let encrypted = crypto::encrypt_data(&bytes, &params)?;
344
345    let _client = crate::state::nostr_client().ok_or("Not logged in")?;
346    let signer = crate::signer::active_signer()
347        .map_err(|e| format!("Signer: {}", e))?;
348    let my_pk = crate::state::my_public_key().ok_or("Public key not set")?;
349    // The chat the wallpaper belongs to, tagged on the rumor below. Without it,
350    // the self-send copy (for multi-device sync) has no recipient, so the
351    // inbound handler attributes it to our self-chat (Notes) instead of this
352    // chat — a wallpaper set in any chat would also reskin Notes.
353    let recipient_pk = PublicKey::from_bech32(chat_npub)
354        .map_err(|e| format!("Invalid chat npub: {}", e))?;
355
356    let servers = crate::state::get_blossom_servers();
357
358    // Bridge Blossom upload progress to the frontend so the Set Wallpaper
359    // button can render a real ring instead of an opaque disabled state.
360    let chat_npub_for_progress = chat_npub.to_string();
361    let progress_cb: crate::blossom::ProgressCallback = Arc::new(move |percentage, bytes| {
362        crate::traits::emit_event(
363            "wallpaper_upload_progress",
364            &serde_json::json!({
365                "chat_id": chat_npub_for_progress,
366                "progress": percentage.unwrap_or(0),
367                "bytes": bytes.unwrap_or(0),
368            }),
369        );
370        Ok(())
371    });
372
373    let upload_url = crate::blossom::upload_blob_with_progress_and_failover(
374        signer.clone(),
375        servers,
376        Arc::new(encrypted.clone()),
377        Some(&mime),
378        /* is_encrypted */ true,
379        progress_cb,
380        None, // default retry count
381        None, // default retry spacing
382        None, // no cancel flag (the picker flow doesn't expose cancel mid-upload)
383    )
384    .await
385    .map_err(|e| format!("Wallpaper upload failed: {}", e))?
386    // This flow never mirrors, so only the descriptor matters.
387    .url;
388
389    let created_at = crate::clock::now_secs();
390    let rumor = EventBuilder::new(Kind::Custom(event_kind::APPLICATION_SPECIFIC), "")
391        .tag(Tag::identifier(WALLPAPER_DTAG_VALUE))
392        // Recipient tag — identifies which chat this wallpaper is for. The
393        // inbound handler reads it to attribute self-sent (multi-device) copies
394        // to the correct chat rather than defaulting to our self-chat.
395        .tag(Tag::public_key(recipient_pk))
396        .tag(Tag::custom(
397            "url",
398            vec![upload_url.clone()],
399        ))
400        .tag(Tag::custom(
401            "decryption-key",
402            vec![params.key.clone()],
403        ))
404        .tag(Tag::custom(
405            "decryption-nonce",
406            vec![params.nonce.clone()],
407        ))
408        .tag(Tag::custom(
409            "x",
410            vec![plaintext_hash.clone()],
411        ))
412        .tag(Tag::custom(
413            "m",
414            vec![mime.clone()],
415        ))
416        .tag(Tag::custom(
417            "size",
418            vec![encrypted.len().to_string()],
419        ))
420        .tag(Tag::custom(
421            "blur",
422            vec![blur.to_string()],
423        ))
424        .tag(Tag::custom(
425            "dim",
426            vec![dim.to_string()],
427        ))
428        .custom_created_at(Timestamp::from(created_at))
429        .finalize_unsigned_with_id(my_pk);
430
431    // SEND FIRST, commit on success. Wallpaper is a sync feature — if the
432    // recipient (and our other devices) can't see it, there's no value in
433    // locally applying it.
434    //
435    // 3 attempts with 2s spacing (~6s max wait) keeps the dialog
436    // responsive. self_send=true so other devices of ours pick it up via
437    // their own NIP-17 inbox subscription.
438    let pending_id = format!("pending-wallpaper-{}", created_at);
439    let send_config = crate::sending::SendConfig {
440        max_send_attempts: 3,
441        retry_delay: std::time::Duration::from_secs(2),
442        self_send: true,
443        ..Default::default()
444    };
445    let send_callback: Arc<dyn crate::sending::SendCallback> =
446        Arc::new(crate::sending::NoOpSendCallback);
447    if let Err(e) = crate::sending::send_rumor_dm(
448        chat_npub, &pending_id, rumor.clone(), &send_config, send_callback,
449    ).await {
450        log_warn!("[Wallpaper] send_rumor_dm to {} failed: {}", chat_npub, e);
451        return Err(format!(
452            "Couldn't send the wallpaper. Check that the relays you and your contact share are reachable, then try again. ({})",
453            e
454        ));
455    }
456    log_info!("[Wallpaper] rumor delivered to {}", chat_npub);
457
458    // Account swapped during upload/send: the rumor already went to the
459    // original recipient, but the local commit below (preview promotion,
460    // STATE, DB) would land in the new account's storage. Skip it.
461
462    // Send succeeded — promote the preview file to the active slot.
463    let active = wallpapers_dir()?.join(format!("{}.{}", chat_npub, extension));
464    clean_chat_files(chat_npub, FileKind::Active, None).await?;
465    crate::files::rename(&preview, &active)
466        .await
467        .map_err(|e| format!("Failed to promote preview: {}", e))?;
468    let active_str = active.to_string_lossy().to_string();
469
470    let me_npub = my_pk.to_bech32().unwrap_or_default();
471
472    // Persist to STATE + DB. Capture the previous Blossom URL + uploader
473    // under the same lock so we can clean it up only if we owned it.
474    let (slim, prev_url, prev_uploader) = {
475        let mut state = crate::state::STATE.lock().await;
476        let prev = state.get_chat(chat_npub).map(|c| {
477            (c.wallpaper_url.clone(), c.wallpaper_uploader.clone())
478        });
479        if let Some(chat) = state.get_chat_mut(chat_npub) {
480            chat.wallpaper_path = active_str.clone();
481            chat.wallpaper_ts = created_at;
482            chat.wallpaper_blur = blur;
483            chat.wallpaper_dim = dim;
484            chat.wallpaper_url = upload_url.clone();
485            chat.wallpaper_uploader = me_npub.clone();
486        }
487        let slim = state
488            .get_chat(chat_npub)
489            .map(|c| crate::db::chats::SlimChatDB::from_chat(c, &state.interner));
490        let (pu, puploader) = prev.unwrap_or_default();
491        (slim, pu, puploader)
492    };
493    if let Some(slim) = slim {
494        if let Err(e) = crate::db::chats::save_slim_chat(&slim) {
495            log_warn!("[Wallpaper] save_slim_chat failed for {}: {}", chat_npub, e);
496        }
497    }
498
499    // Fire-and-forget DELETE of the previous blob, only if we uploaded
500    // it (server's auth challenge would reject otherwise). Multi-device
501    // case: this runs on the device that does the replace, which may not
502    // be the device that uploaded the previous one — the uploader check
503    // is on the npub, not the device, so it still fires correctly.
504    if !prev_url.is_empty() && prev_uploader == me_npub {
505        let signer_clone = signer.clone();
506        let prev_url_clone = prev_url.clone();
507        crate::db::spawn_bound(async move {
508            if let Err(e) =
509                crate::blossom::delete_blob_by_url(signer_clone, &prev_url_clone).await
510            {
511                log_warn!(
512                    "[Wallpaper] DELETE prev blob {} failed: {}",
513                    prev_url_clone, e
514                );
515            }
516        });
517    }
518
519    let event_id = rumor.id.ok_or("Rumor missing id")?.to_hex();
520    let inserted = match crate::db::events::save_system_event_by_id(
521        &event_id,
522        chat_npub,
523        crate::stored_event::SystemEventType::WallpaperChanged,
524        &me_npub,
525        Some("You"),
526    )
527    .await
528    {
529        Ok(b) => b,
530        Err(e) => {
531            log_warn!("[Wallpaper] save_system_event_by_id failed for {}: {}", event_id, e);
532            false
533        }
534    };
535    if inserted {
536        crate::traits::emit_event("system_event", &serde_json::json!({
537            "conversation_id": chat_npub,
538            "event_id": event_id,
539            "event_type": crate::stored_event::SystemEventType::WallpaperChanged.as_u8(),
540            "member_pubkey": me_npub,
541            "member_name": "You",
542        }));
543    } else {
544        log_warn!("[Wallpaper] system event {} was not inserted (already exists or save failed)", event_id);
545    }
546
547    crate::traits::emit_event(
548        "wallpaper_updated",
549        &serde_json::json!({
550            "chat_id": chat_npub,
551            "path": active_str,
552            "ts": created_at,
553            "blur": blur,
554            "dim": dim,
555            "by_npub": me_npub,
556            "event_id": event_id,
557        }),
558    );
559
560    Ok(())
561}
562
563/// A wallpaper rumor from someone whose DM request waits, kept unfetched until it's
564/// answered or accepted.
565#[derive(Serialize, Deserialize)]
566struct HeldWallpaper {
567    sender: String,
568    created_at: u64,
569    url: String,
570    key: String,
571    nonce: String,
572    hash: Option<String>,
573    mime: Option<String>,
574    blur: Option<u8>,
575    dim: Option<u8>,
576    event_id: String,
577}
578
579/// Whether a wallpaper from `sender` in this chat must wait: they wrote to us first and
580/// we've neither answered nor accepted. Ours, from any device, never waits.
581async fn held_back(chat_npub: &str, sender_npub: &str) -> bool {
582    if !crate::requests::shielded() {
583        return false;
584    }
585    let me = crate::state::my_public_key().and_then(|pk| pk.to_bech32().ok()).unwrap_or_default();
586    sender_npub != me && crate::state::STATE.lock().await.dm_unanswered(chat_npub)
587}
588
589/// The wallpaper a request held, applied now that it's answered or accepted.
590pub async fn release_held(chat_npub: &str) {
591    let Ok(Some(json)) = crate::db::chats::take_held_wallpaper(chat_npub) else { return };
592    let Ok(h) = serde_json::from_str::<HeldWallpaper>(&json) else { return };
593    if let Err(e) = apply_received_wallpaper(
594        chat_npub, &h.sender, h.created_at, &h.url, &h.key, &h.nonce,
595        h.hash.as_deref(), h.mime.as_deref(), h.blur, h.dim, &h.event_id,
596    ).await {
597        log_warn!("[Wallpaper] held wallpaper for {chat_npub} failed to apply: {e}");
598    }
599}
600
601/// Apply a received wallpaper rumor. Drops the rumor if its timestamp is
602/// not newer than the chat's current `wallpaper_ts` (latest-write-wins).
603/// On a fresh rumor: downloads + decrypts the Blossom blob, caches it
604/// locally, updates STATE + DB, saves a `WallpaperChanged` system event,
605/// and emits `wallpaper_updated` to the frontend.
606#[allow(clippy::too_many_arguments)]
607pub async fn apply_received_wallpaper(
608    chat_npub: &str,
609    sender_npub: &str,
610    created_at: u64,
611    url: &str,
612    decryption_key: &str,
613    decryption_nonce: &str,
614    plaintext_hash: Option<&str>,
615    mime: Option<&str>,
616    blur: Option<u8>,
617    dim: Option<u8>,
618    rumor_event_id: &str,
619) -> Result<(), String> {
620    // Capture session NOW — the download below can take seconds, and a
621    // mid-fetch account swap must not let us write account A's wallpaper
622    // into account B's STATE/DB (re-checked before every write below).
623
624    let blur = blur.unwrap_or(0).min(30);
625    let dim = dim.unwrap_or(50).min(100);
626    // Latest-write-wins. Drop the rumor if we've already applied a newer
627    // (or equal) one — typical during negentropy backfill.
628    {
629        let state = crate::state::STATE.lock().await;
630        if let Some(chat) = state.get_chat(chat_npub) {
631            if chat.wallpaper_ts >= created_at {
632                return Ok(());
633            }
634        }
635    }
636
637    // Removal tombstone — sender cleared their wallpaper. No blob to fetch;
638    // wipe the local active file + STATE/DB so the default theme returns.
639    if url.is_empty() {
640        // One held from before the removal is withdrawn with it.
641        let _ = crate::db::chats::drop_held_wallpaper_before(chat_npub, created_at);
642        clean_chat_files(chat_npub, FileKind::Active, None).await?;
643        let (slim, prev_url, prev_uploader) = {
644            let mut state = crate::state::STATE.lock().await;
645            let prev = state.get_chat(chat_npub).map(|c| {
646                (c.wallpaper_url.clone(), c.wallpaper_uploader.clone())
647            });
648            if let Some(chat) = state.get_chat_mut(chat_npub) {
649                chat.wallpaper_path = String::new();
650                chat.wallpaper_url = String::new();
651                chat.wallpaper_uploader = String::new();
652                chat.wallpaper_ts = created_at;
653                chat.wallpaper_blur = blur;
654                chat.wallpaper_dim = dim;
655            }
656            let slim = state
657                .get_chat(chat_npub)
658                .map(|c| crate::db::chats::SlimChatDB::from_chat(c, &state.interner));
659            let (pu, puploader) = prev.unwrap_or_default();
660            (slim, pu, puploader)
661        };
662        if let Some(slim) = slim {
663            let _ = crate::db::chats::save_slim_chat(&slim);
664        }
665        delete_prior_blob_if_ours(&prev_url, &prev_uploader).await;
666        emit_wallpaper_removed(chat_npub, sender_npub, created_at, rumor_event_id).await;
667        return Ok(());
668    }
669
670    // Nothing a stranger points at is fetched before their request is accepted.
671    if held_back(chat_npub, sender_npub).await {
672        let held = HeldWallpaper {
673            sender: sender_npub.to_string(), created_at, url: url.to_string(),
674            key: decryption_key.to_string(), nonce: decryption_nonce.to_string(),
675            hash: plaintext_hash.map(str::to_string), mime: mime.map(str::to_string),
676            blur: Some(blur), dim: Some(dim), event_id: rumor_event_id.to_string(),
677        };
678        let json = serde_json::to_string(&held).map_err(|e| format!("hold wallpaper: {e}"))?;
679        crate::db::chats::hold_wallpaper(chat_npub, created_at, &json)?;
680        return Ok(());
681    }
682
683    let _ = mime; // The sender's word on the type is never used: the bytes decide.
684
685    // SSRF guard: the URL is attacker-controlled (it arrives in a rumor),
686    // and this fetch is zero-interaction. Block private/internal targets.
687    crate::net::validate_url_not_private(url)?;
688
689    let http = crate::net::build_http_client(Duration::from_secs(30))?;
690    let resp = crate::net::proxied_request(&http, reqwest::Method::GET, url)
691        .await
692        .send()
693        .await
694        .map_err(|e| format!("Wallpaper download failed: {}", e))?;
695    if !resp.status().is_success() {
696        return Err(format!("Wallpaper HTTP {}", resp.status()));
697    }
698    // Reject by advertised length first (cheap), then enforce a hard cap
699    // while streaming so a server that omits Content-Length can't OOM us.
700    if let Some(len) = resp.content_length() {
701        if len > MAX_WALLPAPER_DOWNLOAD_BYTES {
702            return Err("Wallpaper too large".to_string());
703        }
704    }
705    let mut bytes: Vec<u8> = Vec::new();
706    let mut body = resp.bytes_stream();
707    while let Some(chunk) = futures_util::StreamExt::next(&mut body)
708        .await
709        .transpose()
710        .map_err(|e| format!("Read body: {}", e))?
711    {
712        bytes.extend_from_slice(&chunk);
713        if bytes.len() as u64 > MAX_WALLPAPER_DOWNLOAD_BYTES {
714            return Err("Wallpaper too large".to_string());
715        }
716    }
717
718    let plaintext = crypto::decrypt_data_owned(bytes, decryption_key, decryption_nonce)?;
719
720    if let Some(want_hash) = plaintext_hash {
721        let got_hash = crypto::sha256_hex(&plaintext);
722        if !got_hash.eq_ignore_ascii_case(want_hash) {
723            return Err("Wallpaper integrity check failed".to_string());
724        }
725    }
726
727    let (plaintext, extension) = normalize_received(plaintext)?;
728
729    // Account swap during the download invalidates everything below — the
730    // chat npub, the DB pool, and the per-account wallpapers dir all belong
731
732    let active = wallpapers_dir()?.join(format!("{}.{}", chat_npub, extension));
733    clean_chat_files(chat_npub, FileKind::Active, None).await?;
734    crate::files::write_cache(&active, &plaintext).await.map_err(|e| format!("Write wallpaper: {}", e))?;
735    let active_str = active.to_string_lossy().to_string();
736
737    // Capture previous URL + uploader under the same lock — only DELETE
738    // the prior blob if WE were the uploader (covers multi-device sync
739    // where a different device of ours uploaded the previous wallpaper).
740    let (slim, prev_url, prev_uploader) = {
741        let mut state = crate::state::STATE.lock().await;
742        let prev = state.get_chat(chat_npub).map(|c| {
743            (c.wallpaper_url.clone(), c.wallpaper_uploader.clone())
744        });
745        if let Some(chat) = state.get_chat_mut(chat_npub) {
746            chat.wallpaper_path = active_str.clone();
747            chat.wallpaper_ts = created_at;
748            chat.wallpaper_blur = blur;
749            chat.wallpaper_dim = dim;
750            chat.wallpaper_url = url.to_string();
751            chat.wallpaper_uploader = sender_npub.to_string();
752        }
753        let slim = state
754            .get_chat(chat_npub)
755            .map(|c| crate::db::chats::SlimChatDB::from_chat(c, &state.interner));
756        let (pu, puploader) = prev.unwrap_or_default();
757        (slim, pu, puploader)
758    };
759    if let Some(slim) = slim {
760        let _ = crate::db::chats::save_slim_chat(&slim);
761    }
762
763    if !prev_url.is_empty() {
764        let me_npub = crate::state::my_public_key()
765            .and_then(|pk| pk.to_bech32().ok())
766            .unwrap_or_default();
767        if !me_npub.is_empty() && prev_uploader == me_npub {
768            if let Some(_client) = crate::state::nostr_client() {
769                if let Ok(signer) = crate::signer::active_signer() {
770                    let prev_url_clone = prev_url.clone();
771                    crate::db::spawn_bound(async move {
772                        if let Err(e) =
773                            crate::blossom::delete_blob_by_url(signer, &prev_url_clone).await
774                        {
775                            log_warn!(
776                                "[Wallpaper] DELETE prev blob {} failed: {}",
777                                prev_url_clone, e
778                            );
779                        }
780                    });
781                }
782            }
783        }
784    }
785
786    // Resolve a display name for the system event. Fall back to the npub
787    // (truncated by the frontend's formatter) when we don't know the peer
788    // yet — the row still tells the user what happened.
789    let sender_display = {
790        let state = crate::state::STATE.lock().await;
791        state
792            .get_profile(sender_npub)
793            .and_then(|p| {
794                if !p.nickname().is_empty() {
795                    Some(p.nickname().to_string())
796                } else if !p.name().is_empty() {
797                    Some(p.name().to_string())
798                } else {
799                    None
800                }
801            })
802            .unwrap_or_else(|| sender_npub.to_string())
803    };
804    let inserted = crate::db::events::save_system_event_by_id(
805        rumor_event_id,
806        chat_npub,
807        crate::stored_event::SystemEventType::WallpaperChanged,
808        sender_npub,
809        Some(&sender_display),
810    )
811    .await
812    .unwrap_or(false);
813    if inserted {
814        crate::traits::emit_event("system_event", &serde_json::json!({
815            "conversation_id": chat_npub,
816            "event_id": rumor_event_id,
817            "event_type": crate::stored_event::SystemEventType::WallpaperChanged.as_u8(),
818            "member_pubkey": sender_npub,
819            "member_name": sender_display,
820        }));
821    }
822
823    crate::traits::emit_event(
824        "wallpaper_updated",
825        &serde_json::json!({
826            "chat_id": chat_npub,
827            "path": active_str,
828            "ts": created_at,
829            "blur": blur,
830            "dim": dim,
831            "by_npub": sender_npub,
832            "event_id": rumor_event_id,
833        }),
834    );
835
836    Ok(())
837}
838
839/// Fire-and-forget DELETE of a prior Blossom blob, but only if WE uploaded
840/// it (the server's auth challenge rejects deletes from anyone else). The
841/// uploader check is on the npub, so multi-device replaces still fire.
842async fn delete_prior_blob_if_ours(prev_url: &str, prev_uploader: &str) {
843    if prev_url.is_empty() {
844        return;
845    }
846    let me_npub = crate::state::my_public_key()
847        .and_then(|pk| pk.to_bech32().ok())
848        .unwrap_or_default();
849    if me_npub.is_empty() || prev_uploader != me_npub {
850        return;
851    }
852    if let Some(_client) = crate::state::nostr_client() {
853        if let Ok(signer) = crate::signer::active_signer() {
854            let prev_url = prev_url.to_string();
855            crate::db::spawn_bound(async move {
856                if let Err(e) = crate::blossom::delete_blob_by_url(signer, &prev_url).await {
857                    log_warn!("[Wallpaper] DELETE prev blob {} failed: {}", prev_url, e);
858                }
859            });
860        }
861    }
862}
863
864/// Save the WallpaperChanged system event for a removal + emit the frontend
865/// events that revert the chat to the default theme.
866async fn emit_wallpaper_removed(
867    chat_npub: &str,
868    by_npub: &str,
869    created_at: u64,
870    event_id: &str,
871) {
872    let me_npub = crate::state::my_public_key()
873        .and_then(|pk| pk.to_bech32().ok())
874        .unwrap_or_default();
875    let display = if by_npub == me_npub {
876        "You".to_string()
877    } else {
878        let state = crate::state::STATE.lock().await;
879        state
880            .get_profile(by_npub)
881            .and_then(|p| {
882                if !p.nickname().is_empty() {
883                    Some(p.nickname().to_string())
884                } else if !p.name().is_empty() {
885                    Some(p.name().to_string())
886                } else {
887                    None
888                }
889            })
890            .unwrap_or_else(|| by_npub.to_string())
891    };
892    let inserted = crate::db::events::save_system_event_by_id(
893        event_id,
894        chat_npub,
895        crate::stored_event::SystemEventType::WallpaperRemoved,
896        by_npub,
897        Some(&display),
898    )
899    .await
900    .unwrap_or(false);
901    if inserted {
902        crate::traits::emit_event("system_event", &serde_json::json!({
903            "conversation_id": chat_npub,
904            "event_id": event_id,
905            "event_type": crate::stored_event::SystemEventType::WallpaperRemoved.as_u8(),
906            "member_pubkey": by_npub,
907            "member_name": display,
908        }));
909    }
910    crate::traits::emit_event(
911        "wallpaper_updated",
912        &serde_json::json!({
913            "chat_id": chat_npub,
914            "path": "",
915            "ts": created_at,
916            "blur": 0,
917            "dim": 50,
918            "by_npub": by_npub,
919            "event_id": event_id,
920        }),
921    );
922}
923
924/// Remove the chat's wallpaper, reverting both sides to the default theme.
925/// Publishes a kind-30078 `vector-wallpaper` tombstone (no `url` tag) so the
926/// recipient and our other devices clear it too (latest-write-wins by
927/// `created_at`), then DELETEs our blob and wipes local STATE/DB.
928pub async fn remove_wallpaper(chat_npub: &str) -> Result<(), String> {
929
930    let my_pk = crate::state::my_public_key().ok_or("Public key not set")?;
931    let recipient_pk = PublicKey::from_bech32(chat_npub)
932        .map_err(|e| format!("Invalid chat npub: {}", e))?;
933
934    let created_at = crate::clock::now_secs();
935    // Tombstone: same d-tag + recipient p-tag as a set, but no url/key/nonce.
936    let rumor = EventBuilder::new(Kind::Custom(event_kind::APPLICATION_SPECIFIC), "")
937        .tag(Tag::identifier(WALLPAPER_DTAG_VALUE))
938        .tag(Tag::public_key(recipient_pk))
939        .custom_created_at(Timestamp::from(created_at))
940        .finalize_unsigned_with_id(my_pk);
941
942    let pending_id = format!("pending-wallpaper-rm-{}", created_at);
943    let send_config = crate::sending::SendConfig {
944        max_send_attempts: 3,
945        retry_delay: std::time::Duration::from_secs(2),
946        self_send: true,
947        ..Default::default()
948    };
949    let send_callback: Arc<dyn crate::sending::SendCallback> =
950        Arc::new(crate::sending::NoOpSendCallback);
951    if let Err(e) = crate::sending::send_rumor_dm(
952        chat_npub, &pending_id, rumor.clone(), &send_config, send_callback,
953    ).await {
954        log_warn!("[Wallpaper] removal send to {} failed: {}", chat_npub, e);
955        return Err(format!(
956            "Couldn't remove the wallpaper. Check that the relays you and your contact share are reachable, then try again. ({})",
957            e
958        ));
959    }
960
961    // Account swapped mid-send — the tombstone already went out, but the
962    // local commit below would land in the new account's storage. Skip it.
963
964    clean_chat_files(chat_npub, FileKind::Active, None).await?;
965    let me_npub = my_pk.to_bech32().unwrap_or_default();
966    let (slim, prev_url, prev_uploader) = {
967        let mut state = crate::state::STATE.lock().await;
968        let prev = state.get_chat(chat_npub).map(|c| {
969            (c.wallpaper_url.clone(), c.wallpaper_uploader.clone())
970        });
971        if let Some(chat) = state.get_chat_mut(chat_npub) {
972            chat.wallpaper_path = String::new();
973            chat.wallpaper_url = String::new();
974            chat.wallpaper_uploader = String::new();
975            chat.wallpaper_ts = created_at;
976        }
977        let slim = state
978            .get_chat(chat_npub)
979            .map(|c| crate::db::chats::SlimChatDB::from_chat(c, &state.interner));
980        let (pu, puploader) = prev.unwrap_or_default();
981        (slim, pu, puploader)
982    };
983    if let Some(slim) = slim {
984        if let Err(e) = crate::db::chats::save_slim_chat(&slim) {
985            log_warn!("[Wallpaper] save_slim_chat (removal) failed for {}: {}", chat_npub, e);
986        }
987    }
988
989    delete_prior_blob_if_ours(&prev_url, &prev_uploader).await;
990
991    let event_id = rumor.id.ok_or("Rumor missing id")?.to_hex();
992    emit_wallpaper_removed(chat_npub, &me_npub, created_at, &event_id).await;
993
994    Ok(())
995}
996
997#[cfg(test)]
998mod wallpaper_strip_tests {
999    #[test]
1000    fn a_received_wallpaper_is_judged_by_its_bytes() {
1001        let mut png = Vec::new();
1002        image::RgbaImage::from_pixel(2, 2, image::Rgba([1, 2, 3, 255]))
1003            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
1004            .unwrap();
1005        assert_eq!(super::normalize_received(png.clone()).unwrap(), (png, "png"));
1006
1007        let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect width="4" height="4"/></svg>"##.to_vec();
1008        let (out, ext) = super::normalize_received(svg).unwrap();
1009        assert_eq!(ext, "png");
1010        assert!(out.starts_with(b"\x89PNG"), "an SVG arrives as the pixels it draws");
1011
1012        assert!(super::normalize_received(b"<html><script>x</script></html>".to_vec()).is_err());
1013    }
1014
1015    #[test]
1016    fn a_picked_svg_is_published_as_pixels() {
1017        let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><rect width="40" height="20" fill="#59fcb3"/></svg>"##;
1018        let (out, ext, was_animated, _) = super::normalize_picked(svg, "image/svg+xml", true).unwrap();
1019        assert_eq!((ext.as_str(), was_animated), ("jpg", false));
1020        let img = ::image::load_from_memory(&out).unwrap();
1021        assert_eq!(img.width(), super::WALLPAPER_SVG_DIM);
1022
1023        let mut bomb = String::from(r##"<svg xmlns="http://www.w3.org/2000/svg" width="9" height="9"><defs><rect id="l0" width="1" height="1"/>"##);
1024        for i in 1..8 {
1025            bomb += &format!(r##"<g id="l{i}">{}</g>"##, format!(r##"<use href="#l{}"/>"##, i - 1).repeat(10));
1026        }
1027        bomb += r##"</defs><use href="#l7"/></svg>"##;
1028        assert!(super::normalize_picked(bomb.as_bytes(), "image/svg+xml", true).is_err());
1029    }
1030
1031    use super::*;
1032    use ::image::{DynamicImage, ImageFormat, Rgb, RgbImage, Rgba, RgbaImage};
1033    use std::io::Cursor;
1034
1035    fn png_bytes(img: &DynamicImage) -> Vec<u8> {
1036        let mut out = Vec::new();
1037        img.write_to(&mut Cursor::new(&mut out), ImageFormat::Png).unwrap();
1038        out
1039    }
1040
1041    #[test]
1042    fn opaque_wallpaper_becomes_jpeg_and_is_capped() {
1043        let img = DynamicImage::ImageRgb8(RgbImage::from_fn(3000, 1000, |x, y| {
1044            Rgb([(x % 256) as u8, (y % 256) as u8, 128])
1045        }));
1046        let (bytes, ext, was_animated, dim) =
1047            normalize_wallpaper_image(&png_bytes(&img), "image/png").unwrap();
1048        assert_eq!(ext, "jpg");
1049        assert!(!was_animated);
1050        assert!((10..=50).contains(&dim), "brightness out of range: {dim}");
1051        let dec = ::image::load_from_memory(&bytes).unwrap();
1052        assert!(dec.width() <= MAX_WALLPAPER_DIMENSION && dec.height() <= MAX_WALLPAPER_DIMENSION);
1053    }
1054
1055    #[test]
1056    fn transparent_wallpaper_stays_png() {
1057        let img = DynamicImage::ImageRgba8(RgbaImage::from_fn(64, 64, |x, _| {
1058            Rgba([10, 20, 30, if x < 32 { 0 } else { 255 }])
1059        }));
1060        let (bytes, ext, _, _) =
1061            normalize_wallpaper_image(&png_bytes(&img), "image/png").unwrap();
1062        assert_eq!(ext, "png");
1063        assert!(::image::load_from_memory(&bytes).unwrap().color().has_alpha());
1064    }
1065
1066    #[test]
1067    fn animated_mime_flags_was_animated_but_flattens_to_a_still() {
1068        let img = DynamicImage::ImageRgb8(RgbImage::from_fn(10, 10, |_, _| Rgb([1, 2, 3])));
1069        let (_bytes, ext, was_animated, _dim) =
1070            normalize_wallpaper_image(&png_bytes(&img), "image/gif").unwrap();
1071        assert!(was_animated);
1072        assert_eq!(ext, "jpg");
1073    }
1074}