1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use crate::{
    http_client::HttpClient,
    media_container::devices::{DevicesMediaContainer, Feature},
    url::{MYPLEX_DEVICES, MYPLEX_RESOURCES},
    Error, Player, Result, Server,
};
use futures::{future::select_ok, FutureExt};
use secrecy::ExposeSecret;
use tracing::{debug, error, trace};

pub struct DeviceManager {
    pub client: HttpClient,
}

impl DeviceManager {
    pub fn new(client: HttpClient) -> Self {
        Self { client }
    }

    async fn devices_internal<'a, 'b>(&'a self, url: &'b str) -> Result<Vec<Device<'a>>> {
        let container: DevicesMediaContainer = self
            .client
            .get(url)
            .header("Accept", "application/xml")
            .xml()
            .await?;

        Ok(container
            .devices
            .into_iter()
            .map(|device| Device {
                inner: device,
                client: &self.client,
            })
            .collect())
    }

    #[tracing::instrument(level = "debug", skip(self))]
    pub async fn devices(&self) -> Result<Vec<Device<'_>>> {
        self.devices_internal(MYPLEX_DEVICES).await
    }

    #[tracing::instrument(level = "debug", skip(self))]
    pub async fn resources(&self) -> Result<Vec<Device<'_>>> {
        self.devices_internal(MYPLEX_RESOURCES).await
    }
}

#[derive(Debug, Clone)]
pub struct Device<'a> {
    inner: crate::media_container::devices::Device,
    client: &'a HttpClient,
}

impl Device<'_> {
    /// Returns the list of features supported by the device.
    pub fn provides(&self, feature: Feature) -> bool {
        self.inner.provides.contains(&feature)
    }

    pub fn identifier(&self) -> &str {
        &self.inner.client_identifier
    }

    /// Returns the authentication token that should be used when connecting to the device.
    /// If it's a shared device, the main authentication token will no be accepted.
    pub fn access_token(&self) -> Option<&str> {
        self.inner
            .access_token
            .as_ref()
            .map(|v| v.expose_secret().as_str())
    }

    /// Connect to the device.
    #[tracing::instrument(level = "debug", skip(self), fields(device_name = self.inner.name))]
    pub async fn connect(&self) -> Result<DeviceConnection> {
        if !self.inner.provides.contains(&Feature::Server)
            && !self.inner.provides.contains(&Feature::Controller)
        {
            error!("Device must provide Server or Controller");
            return Err(Error::DeviceConnectionNotSupported);
        }

        if !self.inner.connections.is_empty() {
            let mut client = self.client.clone();
            if let Some(access_token) = self.inner.access_token.as_ref() {
                let access_token = access_token.expose_secret();
                if access_token != client.x_plex_token() {
                    debug!("Connecting using access token for the device");
                    client = client.set_x_plex_token(access_token.to_owned());
                }
            }

            if self.inner.provides.contains(&Feature::Server) {
                trace!(
                    "Connecting to server {id}",
                    id = self.inner.client_identifier,
                );
                let futures = self
                    .inner
                    .connections
                    .iter()
                    .map(|connection| {
                        trace!("Trying {address}", address = connection.uri);
                        crate::Server::new(&connection.uri, client.clone()).boxed()
                    })
                    .collect::<Vec<_>>();

                let (server, _) = select_ok(futures).await?;
                trace!("Connected via {address}", address = server.client().api_url);
                Ok(DeviceConnection::Server(Box::new(server)))
            } else {
                trace!(
                    "Connecting to player {id}",
                    id = self.inner.client_identifier,
                );
                client.x_plex_target_client_identifier = self.inner.client_identifier.clone();

                let futures = self
                    .inner
                    .connections
                    .iter()
                    .map(|connection| {
                        trace!("Trying {address}", address = connection.uri);
                        crate::Player::new(&connection.uri, client.clone()).boxed()
                    })
                    .collect::<Vec<_>>();

                let (player, _) = select_ok(futures).await?;
                trace!("Connected via {address}", address = player.client().api_url);
                Ok(DeviceConnection::Player(Box::new(player)))
            }
        } else {
            Err(Error::DeviceConnectionsIsEmpty)
        }
    }

    /// Establish a connection to the device using server as a proxy.
    #[tracing::instrument(level = "debug", skip(self, server), fields(device_name = self.inner.name))]
    pub async fn connect_via(&self, server: &Server) -> Result<DeviceConnection> {
        if !self.inner.provides.contains(&Feature::Controller) {
            error!("Only devices providing Controller can be connected via proxy");
            return Err(Error::DeviceConnectionNotSupported);
        }

        let futures = self
            .inner
            .connections
            .iter()
            .map(|connection| {
                trace!("Trying {address}", address = connection.uri);
                crate::Player::via_proxy(&connection.uri, server).boxed()
            })
            .collect::<Vec<_>>();

        let (player, _) = select_ok(futures).await?;
        Ok(DeviceConnection::Player(Box::new(player)))
    }
}

#[derive(Debug, Clone)]
pub enum DeviceConnection {
    Server(Box<Server>),
    Player(Box<Player>),
}