Skip to content

An open-source cross-platform alternative to AirDrop

8.6 KB
Raw Blame
//! The device list overlay: paired and discovered devices, with the send
//! and unpair actions.

use super::{App, Overlay};
use crate::device_list::{DeviceHost, DeviceList, DeviceListOutcome, DeviceRow, Row};
use crate::picker::PickerTarget;
use crate::sanitize;
use crate::storage::PairedChannel;
use crate::ui::Category;
use crossterm::event::KeyEvent;
use localsend::discovery::StatefulDevice;

impl App {
    pub(super) fn open_device_list(&mut self) {
        match DeviceList::open(self.device_rows()) {
            Ok(list) => {
                self.ui.suspend();
                self.overlay = Overlay::DeviceList(list);
            }
            Err(err) => {
                self.ui
                    .log_plain(&format!("Could not open the device list: {err}"));
            }
        }
    }

    /// Builds the rows of the device list: the paired devices (with the
    /// live address of those that are also discovered), then the discovered
    /// devices that are not paired.
    pub(super) fn device_rows(&self) -> Vec<Row> {
        let mut rows = vec![Row::Header("Paired")];
        let mut empty = true;
        for (fingerprint, paired) in self.storage.paired.iter() {
            empty = false;
            let discovered = self.discovery.device_by_fingerprint(fingerprint);
            rows.push(Row::Device(DeviceRow {
                fingerprint: fingerprint.clone(),
                alias: discovered
                    .as_ref()
                    .map(|stored| sanitize::single_line(&stored.device.alias))
                    .unwrap_or_else(|| sanitize::single_line(&paired.alias)),
                slot: self.slots.get(fingerprint),
                hosts: discovered.as_ref().map(channel_hosts).unwrap_or_default(),
                paired: true,
            }));
        }
        if empty {
            rows.push(Row::Empty);
        }

        rows.push(Row::Spacer);
        rows.push(Row::Header("Discovered"));
        let mut empty = true;
        for stored in self.discovery.devices() {
            if self.storage.paired.contains(&stored.device.fingerprint) {
                continue;
            }
            empty = false;
            rows.push(Row::Device(DeviceRow {
                fingerprint: stored.device.fingerprint.clone(),
                alias: sanitize::single_line(&stored.device.alias),
                slot: self.slots.get(&stored.device.fingerprint),
                hosts: channel_hosts(&stored),
                paired: false,
            }));
        }
        if empty {
            rows.push(Row::Empty);
        }
        rows
    }

    /// Handles a key while the list is open; returns `true` when the
    /// application should quit (the list was cancelled in `send` mode).
    pub(super) fn handle_device_list_key(&mut self, key: KeyEvent) -> bool {
        let Overlay::DeviceList(list) = &mut self.overlay else {
            return false;
        };
        match list.handle_key(key) {
            DeviceListOutcome::Open => {}
            DeviceListOutcome::Closed => {
                self.close_overlay();
                // In `send` mode the device list is the whole program.
                return !self.preselected.is_empty();
            }
            DeviceListOutcome::Send { fingerprint } => {
                if self.preselected.is_empty()
                    && let Some(device) = self.discovery.device_by_fingerprint(&fingerprint)
                {
                    // The list stays open until the picker takes over its
                    // alternate screen, so the main screen never shows.
                    self.open_picker(PickerTarget::Device {
                        fingerprint: device.device.fingerprint.clone(),
                        alias: sanitize::single_line(&device.device.alias),
                    });
                } else {
                    self.close_overlay();
                    if !self.preselected.is_empty() {
                        self.start_send(&fingerprint, self.preselected.clone());
                    }
                }
            }
            DeviceListOutcome::Pair { fingerprint } => self.pair(&fingerprint),
            DeviceListOutcome::Unpair { fingerprint } => self.unpair(&fingerprint),
        }
        false
    }

    /// Pairs a discovered device; the list stays open and refreshes (the
    /// device moves up into "Paired"). The log line shows up once the list
    /// is closed.
    fn pair(&mut self, fingerprint: &str) {
        let Some(stored) = self.discovery.device_by_fingerprint(fingerprint) else {
            return;
        };
        let alias = sanitize::single_line(&stored.device.alias);
        match self.storage.paired.insert(
            fingerprint.to_string(),
            alias.clone(),
            PairedChannel::channels_of(&stored),
        ) {
            Ok(()) => self.ui.log(
                Category::Discovery,
                &format!("{alias}: Paired. Future requests are auto-accepted."),
            ),
            Err(err) => self.ui.log(
                Category::Discovery,
                &format!("{alias}: Paired for this run, but saving failed: {err:#}"),
            ),
        }
        let rows = self.device_rows();
        if let Overlay::DeviceList(list) = &mut self.overlay {
            list.set_rows(rows);
            list.draw();
        }
    }

    /// Removes a paired device; the list stays open and refreshes (the
    /// device reappears under "Discovered" when it is still around). The
    /// log line shows up once the list is closed.
    fn unpair(&mut self, fingerprint: &str) {
        match self.storage.paired.remove(fingerprint) {
            Ok(Some(device)) => {
                self.ui.log(
                    Category::Discovery,
                    &format!("{}: Unpaired", sanitize::single_line(&device.alias)),
                );
            }
            Ok(None) => {}
            Err(err) => {
                self.ui.log(
                    Category::Discovery,
                    &format!("Unpaired for this run, but saving failed: {err:#}"),
                );
            }
        }
        let rows = self.device_rows();
        if let Overlay::DeviceList(list) = &mut self.overlay {
            list.set_rows(rows);
            list.draw();
        }
    }
}

/// The addresses a stored device can be dialed at, best first, each with
/// the state of its channel.
fn channel_hosts(stored: &StatefulDevice) -> Vec<DeviceHost> {
    stored
        .get_ranked_channels()
        .into_iter()
        .filter_map(|channel| {
            Some(DeviceHost {
                host: channel.http()?.host.clone(),
                state: *stored.channels.get(channel)?,
            })
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::channel_hosts;
    use localsend::discovery::{
        ChannelState, DeviceChannel, DiscoveredDevice, HttpChannel, Outbound, StatefulDevice,
    };
    use localsend::model::discovery::ProtocolType;
    use std::time::SystemTime;

    fn channel(host: &str) -> DeviceChannel {
        DeviceChannel::Http(HttpChannel {
            host: host.to_string(),
            port: 53317,
            protocol: ProtocolType::Https,
        })
    }

    #[test]
    fn lists_each_host_with_the_state_of_its_channel_best_first() {
        let now = SystemTime::now();
        let failed = ChannelState {
            outbound: Outbound::Failed(now),
            inbound: None,
        };
        let untested = ChannelState {
            outbound: Outbound::Untested,
            inbound: Some(now),
        };
        let reachable = ChannelState {
            outbound: Outbound::Reachable(now),
            inbound: None,
        };
        let stored = StatefulDevice {
            device: DiscoveredDevice {
                alias: "Cute Tomato".to_string(),
                version: "2.2".to_string(),
                device_model: None,
                device_type: None,
                fingerprint: "tomato".to_string(),
                channel: channel("192.168.0.10"),
                download: false,
            },
            confirmed: true,
            verified: true,
            channels: [
                (channel("10.0.0.10"), failed),
                (channel("fe80::1%3"), untested),
                (channel("192.168.0.10"), reachable),
            ]
            .into(),
            logs: Vec::new(),
        };

        let hosts: Vec<(String, ChannelState)> = channel_hosts(&stored)
            .into_iter()
            .map(|host| (host.host, host.state))
            .collect();

        assert_eq!(
            hosts,
            [
                ("192.168.0.10".to_string(), reachable),
                ("fe80::1%3".to_string(), untested),
                ("10.0.0.10".to_string(), failed),
            ]
        );
    }
}