Skip to main content

cosmic_applet_avestruz/handlers/
media.rs

1// SPDX-License-Identifier: MIT
2
3//! The account's media servers, and attaching files to what is being
4//! written.
5//!
6//! The servers are the account's server list (see
7//! [`crate::nostr::blossom`]). They show as the event store has them at
8//! once, and as the relays have them when they have answered; until then
9//! nothing can be changed, since what is saved replaces what the list
10//! names. Servers are added, taken out and moved on the page, and
11//! nothing is written until Save, as on the relays page; a first list is
12//! only written after saying so. There is no server until the account
13//! names one: none is built in.
14//!
15//! A file is attached from the composer: picked in the desktop's file
16//! chooser, or pasted. The chooser is a window of its own, and the popup
17//! is above every window and has the keyboard, so the popup closes while
18//! the chooser is open, and opens again on the composer when it is done.
19//!
20//! ```mermaid
21//! flowchart TD
22//!     attach["Attach, in the composer"] --> any{"Any media server?"}
23//!     any -->|"none"| page["The media servers page, to add one"]
24//!     any -->|"yes"| chooser["The popup closes; the file chooser opens"]
25//!     chooser --> picked["Files picked: the popup opens again"]
26//!     paste["Ctrl+V, in the composer"] --> what{"What is on the clipboard?"}
27//!     what -->|"text"| typed["Pasted into the text"]
28//!     what -->|"files, a picture"| each
29//!     picked --> each["For each file"]
30//!     each --> ready["Read; a picture made bare; hashed"]
31//!     ready --> signed["The account signs an authorization for that hash"]
32//!     signed --> sent["Sent to the first server that takes it; the others fetch it"]
33//!     sent --> link["Its address goes at the end of the text, and what the note says of it is kept"]
34//! ```
35//!
36//! Each file is on its way by itself, shown under the text with how far
37//! it has got, and can be called off. They belong to what they were
38//! attached to: one that arrives after the composer was left goes at the
39//! end of that target's draft. Nothing is published while a file for it
40//! is on its way.
41//!
42//! What a note says of a file ([`crate::nostr::blossom::imeta`]) is kept by
43//! the file's address, and said when a note that links to that address
44//! goes out: taking the address out of the text takes the file out of the
45//! note. It is kept with the draft, too, on the relay of this machine.
46
47use std::borrow::Cow;
48use std::path::PathBuf;
49use std::sync::Arc;
50use std::sync::atomic::Ordering;
51
52use cosmic::dialog::file_chooser::{self, FileFilter};
53use cosmic::iced::clipboard;
54use cosmic::iced::clipboard::mime::AllowedMimeTypes;
55use cosmic::iced::widget::operation::focus;
56use cosmic::prelude::*;
57use cosmic::widget::text_editor::{Action, Edit, Motion};
58use nostr_sdk::prelude::{Event, PublicKey, Timestamp, Url};
59
60use crate::fl;
61use crate::handlers::auth::sign_error_text;
62use crate::handlers::compose::publish_error_text;
63use crate::handlers::feed::fetch_error_text;
64use crate::helpers::readable_size;
65use crate::media::{self, MAX_BYTES, MediaError};
66use crate::messages::{AttachFailure, Message};
67use crate::nostr::account::Signer;
68use crate::nostr::blossom::{self, Attachment, Sent, UploadError, server_name, typed_server};
69use crate::nostr::client::{FetchError, ListError, Source};
70use crate::nostr::compose::Target;
71use crate::state::{AppModel, MediaState, Upload, ViewState};
72use crate::views::compose::COMPOSE_EDITOR_ID;
73
74/// What a picture pasted from the clipboard is called.
75const PASTED_NAME: &str = "pasted";
76
77/// The kinds of thing taken from the clipboard, the most wanted first: a
78/// list of files, then text, and a picture only where there is neither.
79/// Something copied in a spreadsheet is offered as text and as a picture
80/// of it, and it is the text that is meant.
81const FILE_LIST: &str = "text/uri-list";
82const TEXTS: [&str; 3] = ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"];
83const PICTURES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"];
84
85/// What was on the clipboard when Ctrl+V was pressed in the composer.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum Pasted {
88    /// Text: it goes into what is written.
89    Text(String),
90    /// Files copied in a file manager: each is attached.
91    Files(Vec<PathBuf>),
92    /// A picture, copied as one: it is attached. What it is made of, and
93    /// what it is called.
94    Picture(Vec<u8>, String),
95}
96
97impl AllowedMimeTypes for Pasted {
98    fn allowed() -> Cow<'static, [String]> {
99        std::iter::once(FILE_LIST).chain(TEXTS).chain(PICTURES).map(str::to_string).collect()
100    }
101}
102
103impl TryFrom<(Vec<u8>, String)> for Pasted {
104    type Error = ();
105
106    fn try_from((bytes, kind): (Vec<u8>, String)) -> Result<Self, Self::Error> {
107        pasted(bytes, &kind).ok_or(())
108    }
109}
110
111/// What `bytes` from the clipboard are, which it said are a `kind`. A
112/// list of addresses none of which is a file is the text it is.
113fn pasted(bytes: Vec<u8>, kind: &str) -> Option<Pasted> {
114    if let Some(picture) = PICTURES.iter().find(|picture| **picture == kind) {
115        let extension = picture.rsplit('/').next().unwrap_or_default();
116        return (!bytes.is_empty()).then(|| Pasted::Picture(bytes, format!("{PASTED_NAME}.{extension}")));
117    }
118    let text = String::from_utf8_lossy(&bytes).replace("\r\n", "\n");
119    if kind == FILE_LIST {
120        let listed = text.lines().map(str::trim).filter(|line| !line.is_empty() && !line.starts_with('#'));
121        let files: Vec<PathBuf> =
122            listed.filter_map(|line| Url::parse(line).ok().filter(|url| url.scheme() == "file")?.to_file_path().ok()).collect();
123        if !files.is_empty() {
124            return Some(Pasted::Files(files));
125        }
126    }
127    (!text.is_empty()).then_some(Pasted::Text(text))
128}
129
130/// A file to attach: where it is, or what it is called and made of.
131#[derive(Debug, Clone)]
132enum Picked {
133    File(PathBuf),
134    Bytes(String, Vec<u8>),
135}
136
137impl Picked {
138    /// What the file is called.
139    fn name(&self) -> String {
140        match self {
141            Self::File(path) => path.file_name().map(|name| name.to_string_lossy().to_string()).unwrap_or_default(),
142            Self::Bytes(name, _) => name.clone(),
143        }
144    }
145}
146
147/// Send `picked` to the first of `servers` that takes it, as `account`,
148/// which `signer` signs for: read, a picture made bare (see
149/// [`crate::media`]), hashed, authorized, and sent (see
150/// [`blossom::send`]), with `size` set to how large it is as it goes and
151/// `sent` kept at how much of it has gone.
152async fn attach(
153    http: reqwest::Client,
154    signer: Signer,
155    account: PublicKey,
156    servers: Vec<Url>,
157    picked: Picked,
158    size: Sent,
159    sent: Sent,
160) -> Result<Attachment, AttachFailure> {
161    let name = picked.name();
162    let bytes = match picked {
163        Picked::File(path) => {
164            // Not read at all, if it is too large to be sent.
165            let length = tokio::fs::metadata(&path).await.map_err(|e| AttachFailure::Read(e.to_string()))?.len();
166            let length = usize::try_from(length).unwrap_or(usize::MAX);
167            if length > MAX_BYTES {
168                return Err(AttachFailure::Media(MediaError::TooLarge(length)));
169            }
170            tokio::fs::read(&path).await.map_err(|e| AttachFailure::Read(e.to_string()))?
171        }
172        Picked::Bytes(_, bytes) => bytes,
173    };
174    let ready = tokio::task::spawn_blocking(move || {
175        let media = media::prepare(name, bytes)?;
176        let hash = blossom::hash_of(&media.bytes);
177        Ok((media, hash))
178    });
179    let (media, hash) = ready.await.map_err(|e| AttachFailure::Read(e.to_string()))?.map_err(AttachFailure::Media)?;
180    size.store(media.bytes.len(), Ordering::Relaxed);
181
182    let unsigned = blossom::upload_auth(&media.name, &hash, Timestamp::now());
183    let auth = signer.sign(account, unsigned).await.map_err(AttachFailure::Sign)?;
184    blossom::send(&http, &servers, &auth, media, &hash, &sent).await.map_err(AttachFailure::Refused)
185}
186
187/// Why a server did not take a file, in the user's language.
188fn upload_error_text(error: &UploadError) -> String {
189    match error {
190        UploadError::Unreachable(error) => fl!("attach-unreachable", error = error.as_str()),
191        UploadError::Refused { status, reason } => fl!("attach-refused", status = status.to_string(), reason = reason.as_str()),
192        UploadError::Unreadable(error) => fl!("attach-unreadable-answer", error = error.as_str()),
193    }
194}
195
196/// Why the file called `name` was not attached, in the user's language.
197fn attach_failure_text(name: &str, failure: AttachFailure) -> String {
198    match failure {
199        AttachFailure::Read(error) => fl!("attach-error-read", name = name, error = error),
200        AttachFailure::Media(MediaError::Empty) => fl!("attach-error-empty", name = name),
201        AttachFailure::Media(MediaError::TooLarge(size)) => {
202            fl!("attach-error-too-large", name = name, size = readable_size(size), most = readable_size(MAX_BYTES))
203        }
204        AttachFailure::Media(MediaError::Unreadable) => fl!("attach-error-unreadable", name = name),
205        AttachFailure::Media(MediaError::Damaged) => fl!("attach-error-damaged", name = name),
206        AttachFailure::Sign(error) => fl!("attach-error-sign", name = name, error = sign_error_text(error)),
207        AttachFailure::Refused(refused) => {
208            let each: Vec<String> =
209                refused.iter().map(|(server, error)| format!("{}: {}", server_name(server), upload_error_text(error))).collect();
210            fl!("attach-error-refused", name = name, servers = each.join(" "))
211        }
212    }
213}
214
215impl AppModel {
216    /// Forget the account's media servers, and call off what is on its
217    /// way to them: the account changed, and they were its own.
218    pub(crate) fn reset_media(&mut self) {
219        for upload in &self.media.uploads {
220            upload.handle.abort();
221        }
222        self.media = MediaState::default();
223    }
224
225    /// Find out what the account's media servers are, while the popup is
226    /// open, unless the relays said already.
227    pub(crate) fn load_media_servers(&mut self) -> Task<cosmic::Action<Message>> {
228        if self.popup.is_none() || self.media.from_relays || self.media.loading {
229            return Task::none();
230        }
231        self.ask_media_servers(Source::Store)
232    }
233
234    /// Ask `source` for the account's server list, unless it is being
235    /// changed: what the change leaves is what it is.
236    fn ask_media_servers(&mut self, source: Source) -> Task<cosmic::Action<Message>> {
237        let (Some(service), Some(account)) = (self.nostr.clone(), self.account.as_ref().map(|account| account.public_key)) else {
238            return Task::none();
239        };
240        if self.media.saving {
241            return Task::none();
242        }
243        if source == Source::Relays {
244            self.media.loading = true;
245        }
246        Task::perform(async move { service.media_server_list(source, account).await }, move |result| {
247            cosmic::Action::App(Message::MediaServersLoaded { account, source, result })
248        })
249    }
250
251    /// The servers are what `list` says from now on. Those on the page
252    /// that were not changed there show what it says; changed, they stay
253    /// as they are.
254    fn take_media_servers(&mut self, list: Option<Event>) {
255        let (before, now) = (self.media.servers(), blossom::servers(list.as_ref()));
256        if !self.media.read || self.media.edited == before {
257            self.media.edited = now;
258        }
259        self.media.list = list;
260        self.media.read = true;
261    }
262
263    /// The account's server list came from the store or from the relays,
264    /// or didn't. After the store, the relays are asked.
265    pub fn handle_media_servers_loaded(
266        &mut self,
267        account: PublicKey,
268        source: Source,
269        result: Result<Option<Event>, FetchError>,
270    ) -> Task<cosmic::Action<Message>> {
271        // Whoever signed out meanwhile took their servers with them.
272        if self.account.as_ref().map(|account| account.public_key) != Some(account) {
273            return Task::none();
274        }
275        let from_relays = source == Source::Relays;
276        if from_relays {
277            self.media.loading = false;
278        }
279        match result {
280            // A change on its way says what the list is when it is done;
281            // and the store's word is not taken over the relays'.
282            Ok(_) if self.media.saving || (!from_relays && self.media.from_relays) => {}
283            Ok(list) => {
284                self.take_media_servers(list);
285                self.media.from_relays = from_relays;
286            }
287            Err(e) => {
288                tracing::warn!("the account's media server list could not be asked of {source:?}: {e:?}");
289                if from_relays && self.view_state == ViewState::Media {
290                    self.error_message = Some(fl!("media-not-read", error = fetch_error_text(e)));
291                }
292            }
293        }
294        match source {
295            Source::Store => self.ask_media_servers(Source::Relays),
296            Source::Relays => Task::none(),
297        }
298    }
299
300    /// Show the account's media servers, in place of what is on show, and
301    /// ask for its list again.
302    pub fn handle_open_media(&mut self) -> Task<cosmic::Action<Message>> {
303        self.menu_open = false;
304        self.view_state = ViewState::Media;
305        self.ask_media_servers(Source::Store)
306    }
307
308    /// Leave the media servers: for the composer, if something is being
309    /// written, and for the list that was on show otherwise.
310    pub fn handle_close_media(&mut self) -> Task<cosmic::Action<Message>> {
311        if self.composer.is_some() {
312            self.view_state = ViewState::Compose;
313            focus(COMPOSE_EDITOR_ID.clone())
314        } else {
315            self.show_list_view()
316        }
317    }
318
319    /// Whether the servers can be changed now: by an account with its
320    /// key, once the relays have said what its list is, while no change
321    /// is on its way.
322    pub(crate) fn media_can_change(&self) -> bool {
323        self.can_publish() && self.media.from_relays && !self.media.saving
324    }
325
326    /// Add the server typed, on the page: nothing is written until the
327    /// servers are saved.
328    pub fn handle_add_media_server(&mut self) {
329        if !self.media_can_change() {
330            return;
331        }
332        let typed = self.media.typed.trim().to_string();
333        if typed.is_empty() {
334            return;
335        }
336        match typed_server(&typed) {
337            Some(server) => {
338                if !self.media.edited.contains(&server) {
339                    self.media.edited.push(server);
340                }
341                self.media.typed.clear();
342                self.error_message = None;
343            }
344            None => self.error_message = Some(fl!("media-not-a-server", typed = typed)),
345        }
346    }
347
348    /// Take `server` out, on the page.
349    pub fn handle_remove_media_server(&mut self, server: &Url) {
350        if self.media_can_change() {
351            self.media.edited.retain(|other| other != server);
352        }
353    }
354
355    /// Move `server` a place up, or down, on the page.
356    pub fn handle_shift_media_server(&mut self, server: &Url, up: bool) {
357        if !self.media_can_change() {
358            return;
359        }
360        let Some(at) = self.media.edited.iter().position(|other| other == server) else {
361            return;
362        };
363        let to = if up { at.checked_sub(1) } else { Some(at + 1).filter(|to| *to < self.media.edited.len()) };
364        if let Some(to) = to {
365            self.media.edited.swap(at, to);
366        }
367    }
368
369    /// Whether there is anything to save, and it can be saved now.
370    pub(crate) fn media_can_save(&self) -> bool {
371        self.media_can_change() && self.media.changed()
372    }
373
374    /// Write the servers as the page has them to the account's list.
375    pub fn handle_save_media_servers(&mut self) -> Task<cosmic::Action<Message>> {
376        if !self.media_can_save() {
377            return Task::none();
378        }
379        let (Some(service), Some(account)) = (self.nostr.clone(), self.account.as_ref().map(|account| account.public_key)) else {
380            return Task::none();
381        };
382        let (signer, servers, first_list) = (self.signer.clone(), self.media.edited.clone(), self.media.first_list);
383        self.media.saving = true;
384        self.error_message = None;
385        Task::perform(async move { service.set_media_servers(&signer, account, &servers, first_list).await }, move |result| {
386            cosmic::Action::App(Message::MediaServersSaved { account, result })
387        })
388    }
389
390    /// The account's server list was changed, or wasn't. What was not
391    /// saved stays on the page, changed, to be saved again.
392    pub fn handle_media_servers_saved(&mut self, account: PublicKey, result: Result<Option<Event>, ListError>) {
393        self.media.saving = false;
394        if self.account.as_ref().map(|account| account.public_key) != Some(account) {
395            return;
396        }
397        self.error_message = match result {
398            Ok(list) => {
399                self.media.edited = blossom::servers(list.as_ref());
400                self.media.list = list;
401                self.media.first_list = false;
402                None
403            }
404            Err(ListError::NoList) => {
405                self.media.first_list = true;
406                Some(fl!("media-no-list"))
407            }
408            Err(ListError::Fetch(e)) => {
409                tracing::error!("the media server list could not be asked for: {e:?}");
410                Some(fl!("media-error", error = fetch_error_text(e)))
411            }
412            Err(ListError::Unreadable(e)) => Some(fl!("media-error", error = sign_error_text(e))),
413            Err(ListError::Publish(e)) => {
414                tracing::error!("the media server list did not go out: {e:?}");
415                Some(fl!("media-error", error = publish_error_text(e)))
416            }
417        };
418    }
419
420    /// Whether something can be attached to what is being written now:
421    /// it is being written, by an account with its key, and is not on its
422    /// way out.
423    fn can_attach(&self) -> bool {
424        self.can_publish() && self.nostr.is_some() && self.composer.as_ref().is_some_and(|composer| !composer.publishing)
425    }
426
427    /// The files on their way that are attached to `target`.
428    pub(crate) fn uploads_for(&self, target: Target) -> impl Iterator<Item = &Upload> {
429        self.media.uploads.iter().filter(move |upload| upload.target == target)
430    }
431
432    /// Whether there is a media server to send a file to. Where there is
433    /// none, the page they are added on is shown, and says why.
434    fn has_media_server(&mut self) -> Result<(), Task<cosmic::Action<Message>>> {
435        if !self.media.servers().is_empty() {
436            return Ok(());
437        }
438        let opened = self.handle_open_media();
439        self.error_message = Some(fl!("media-needed"));
440        Err(opened)
441    }
442
443    /// Pick what is to be attached to what is being written, in the
444    /// desktop's file chooser. The popup closes meanwhile: it is above
445    /// every window, the chooser among them, and has the keyboard.
446    pub fn handle_attach_media(&mut self) -> Task<cosmic::Action<Message>> {
447        if !self.can_attach() || self.media.picking {
448            return Task::none();
449        }
450        if let Err(opened) = self.has_media_server() {
451            return opened;
452        }
453        self.media.picking = true;
454        let closed = if self.popup.is_some() { self.handle_toggle_popup() } else { Task::none() };
455        let (title, kinds) = (fl!("compose-attach-title"), fl!("compose-attach-kinds"));
456        let picking = async move {
457            let kinds = FileFilter::new(&kinds).mimetype("image/*").mimetype("video/*").mimetype("audio/*");
458            let dialog = file_chooser::open::Dialog::new().title(title).filter(kinds);
459            match dialog.open_files().await {
460                Ok(picked) => Ok(picked.urls().iter().filter_map(|url| url.to_file_path().ok()).collect()),
461                Err(file_chooser::Error::Cancelled) => Ok(Vec::new()),
462                Err(e) => Err(format!("{e}: {}", std::error::Error::source(&e).map(ToString::to_string).unwrap_or_default())),
463            }
464        };
465        Task::batch([closed, Task::perform(picking, |picked| cosmic::Action::App(Message::MediaPicked(picked)))])
466    }
467
468    /// The file chooser is done: with these files, with none, or it could
469    /// not be opened. The popup opens again, on the composer.
470    pub fn handle_media_picked(&mut self, picked: Result<Vec<PathBuf>, String>) -> Task<cosmic::Action<Message>> {
471        self.media.picking = false;
472        let opened = if self.popup.is_none() {
473            // No click closed it, that the press of a button could be.
474            self.popup_unfocused_at = None;
475            self.handle_toggle_popup()
476        } else {
477            Task::none()
478        };
479        let attached = match picked {
480            Ok(files) => self.attach_all(files.into_iter().map(Picked::File).collect()),
481            Err(e) => {
482                tracing::error!("the file chooser could not be opened: {e}");
483                self.say_of_attaching(None, fl!("attach-error-chooser", error = e));
484                Task::none()
485            }
486        };
487        Task::batch([opened, attached, focus(COMPOSE_EDITOR_ID.clone())])
488    }
489
490    /// Ctrl+V was pressed in the composer: see what is on the clipboard.
491    pub fn handle_compose_paste(&self) -> Task<cosmic::Action<Message>> {
492        if !self.can_attach() {
493            return Task::none();
494        }
495        clipboard::read_data::<Pasted>().map(|pasted| cosmic::Action::App(Message::ComposePasted(pasted)))
496    }
497
498    /// What was on the clipboard: text goes into what is written, and
499    /// files or a picture are attached to it.
500    pub fn handle_compose_pasted(&mut self, pasted: Option<Pasted>) -> Task<cosmic::Action<Message>> {
501        match pasted {
502            Some(Pasted::Text(text)) => {
503                self.handle_compose_edited(Action::Edit(Edit::Paste(Arc::new(text))));
504                Task::none()
505            }
506            Some(Pasted::Files(files)) => self.attach_pasted(files.into_iter().map(Picked::File).collect()),
507            Some(Pasted::Picture(bytes, name)) => self.attach_pasted(vec![Picked::Bytes(name, bytes)]),
508            None => Task::none(),
509        }
510    }
511
512    /// Attach `picked`, which were pasted, if there is a server to send
513    /// them to.
514    fn attach_pasted(&mut self, picked: Vec<Picked>) -> Task<cosmic::Action<Message>> {
515        if !self.can_attach() {
516            return Task::none();
517        }
518        match self.has_media_server() {
519            Ok(()) => self.attach_all(picked),
520            Err(opened) => opened,
521        }
522    }
523
524    /// Send each of `picked` on its way, attached to what is being
525    /// written.
526    fn attach_all(&mut self, picked: Vec<Picked>) -> Task<cosmic::Action<Message>> {
527        let (Some(account), Some(target)) = (
528            self.account.as_ref().filter(|account| account.can_sign).map(|account| account.public_key),
529            self.composer.as_ref().map(|composer| composer.target),
530        ) else {
531            return Task::none();
532        };
533        let servers = self.media.servers();
534        if servers.is_empty() {
535            return Task::none();
536        }
537        if let Some(composer) = self.composer.as_mut().filter(|_| !picked.is_empty()) {
538            composer.error = None;
539        }
540        let sending = picked.into_iter().map(|picked| {
541            self.media.attached += 1;
542            let id = self.media.attached;
543            let (name, size, sent) = (picked.name(), Sent::default(), Sent::default());
544            let attaching =
545                attach(self.http.clone(), self.signer.clone(), account, servers.clone(), picked, size.clone(), sent.clone());
546            let (task, handle) =
547                Task::perform(attaching, move |result| cosmic::Action::App(Message::MediaUploaded { id, result })).abortable();
548            self.media.uploads.push(Upload { id, target, name, size, sent, handle });
549            task
550        });
551        Task::batch(sending.collect::<Vec<_>>())
552    }
553
554    /// Say `said` of attaching something to `target`: in the composer, if
555    /// it is open on that, or on what is open if no target is named; and
556    /// over whatever is on show otherwise.
557    fn say_of_attaching(&mut self, target: Option<Target>, said: String) {
558        match self.composer.as_mut().filter(|composer| target.is_none_or(|target| composer.target == target)) {
559            Some(composer) => composer.error = Some(said),
560            None => self.error_message = Some(said),
561        }
562    }
563
564    /// The file numbered `id` is on a media server, or isn't. Its address
565    /// goes at the end of what it was attached to: in the composer, if
566    /// that is open on it, and in its draft otherwise.
567    pub fn handle_media_uploaded(&mut self, id: u64, result: Result<Attachment, AttachFailure>) -> Task<cosmic::Action<Message>> {
568        let Some(at) = self.media.uploads.iter().position(|upload| upload.id == id) else {
569            // Called off.
570            return Task::none();
571        };
572        let upload = self.media.uploads.remove(at);
573        let attachment = match result {
574            Ok(attachment) => attachment,
575            Err(failure) => {
576                tracing::error!("{} was not attached: {failure:?}", upload.name);
577                self.say_of_attaching(Some(upload.target), attach_failure_text(&upload.name, failure));
578                return Task::none();
579            }
580        };
581        tracing::info!(
582            "{} is at {}, and was fetched from there by {} other server(s)",
583            upload.name,
584            attachment.url,
585            attachment.mirrored.len()
586        );
587        self.media.said.insert(attachment.url.clone(), attachment.imeta);
588        match self.composer.as_mut().filter(|composer| composer.target == upload.target) {
589            Some(composer) => {
590                composer.content.perform(Action::Move(Motion::DocumentEnd));
591                let text = composer.content.text();
592                let lead = if text.trim().is_empty() || text.ends_with('\n') { "" } else { "\n" };
593                composer.content.perform(Action::Edit(Edit::Paste(Arc::new(format!("{lead}{}\n", attachment.url)))));
594                self.preview_composed_anew()
595            }
596            None => {
597                let mut text = self.drafts.get(upload.target).to_string();
598                if !text.is_empty() && !text.ends_with('\n') {
599                    text.push('\n');
600                }
601                text.push_str(&attachment.url);
602                text.push('\n');
603                self.drafts.set(upload.target, text);
604                self.send_draft(upload.target)
605            }
606        }
607    }
608
609    /// Call off the file numbered `id`, which is on its way.
610    pub fn handle_cancel_upload(&mut self, id: u64) {
611        if let Some(at) = self.media.uploads.iter().position(|upload| upload.id == id) {
612            self.media.uploads.remove(at).handle.abort();
613        }
614    }
615}
616
617#[cfg(test)]
618mod tests {
619    use super::{FILE_LIST, Pasted, attach_failure_text, pasted};
620    use crate::media::MediaError;
621    use crate::messages::AttachFailure;
622    use crate::nostr::blossom::UploadError;
623    use cosmic::iced::clipboard::mime::AllowedMimeTypes;
624    use nostr_sdk::prelude::Url;
625    use std::path::PathBuf;
626
627    #[test]
628    fn what_is_pasted_is_files_before_text_and_text_before_a_picture() {
629        let wanted = Pasted::allowed();
630        let place = |kind: &str| wanted.iter().position(|allowed| allowed == kind).unwrap();
631        assert!(place(FILE_LIST) < place("text/plain;charset=utf-8"));
632        assert!(place("text/plain") < place("image/png"));
633    }
634
635    #[test]
636    fn what_was_on_the_clipboard_is_text_files_or_a_picture() {
637        let text = |said: &str| Some(Pasted::Text(said.to_string()));
638        assert_eq!(pasted(b"gm\r\nnostr".to_vec(), "text/plain;charset=utf-8"), text("gm\nnostr"));
639        assert_eq!(pasted(b"gm".to_vec(), "UTF8_STRING"), text("gm"));
640        assert_eq!(pasted(Vec::new(), "text/plain"), None);
641
642        let listed = b"# copied\r\nfile:///home/me/a%20picture.jpg\r\nfile:///home/me/clip.mp4\r\n".to_vec();
643        let files = vec![PathBuf::from("/home/me/a picture.jpg"), PathBuf::from("/home/me/clip.mp4")];
644        assert_eq!(pasted(listed, FILE_LIST), Some(Pasted::Files(files)));
645        // Addresses that are no files are what they say.
646        assert_eq!(pasted(b"https://example.com/a\r\n".to_vec(), FILE_LIST), text("https://example.com/a\n"));
647
648        assert_eq!(pasted(vec![1, 2, 3], "image/png"), Some(Pasted::Picture(vec![1, 2, 3], "pasted.png".into())));
649        assert_eq!(pasted(vec![1], "image/jpeg"), Some(Pasted::Picture(vec![1], "pasted.jpeg".into())));
650        assert_eq!(pasted(Vec::new(), "image/png"), None);
651    }
652
653    #[test]
654    fn why_a_file_was_not_attached_names_the_file_and_each_server() {
655        let server = |name: &str| Url::parse(name).unwrap();
656        let refused = AttachFailure::Refused(vec![
657            (server("https://one.example.com"), UploadError::Refused { status: 413, reason: "too large".into() }),
658            (server("https://two.example.com"), UploadError::Unreachable("no route".into())),
659        ]);
660        let said = attach_failure_text("holiday.jpg", refused);
661        for part in ["holiday.jpg", "one.example.com", "413", "too large", "two.example.com", "no route"] {
662            assert!(said.contains(part), "{part} is in: {said}");
663        }
664        let said = attach_failure_text("film.mp4", AttachFailure::Media(MediaError::TooLarge(300_000_000)));
665        assert!(said.contains("film.mp4") && said.contains("300") && said.contains("100"), "{said}");
666    }
667}