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
use crate::serde_helpers::option_bool_from_int;
use crate::server::Server;
use crate::{HasDeleteUrl, HasMyPlexToken};
use chrono::{DateTime, Utc};
use serde_with::CommaSeparator;
use std::sync::mpsc;
use std::thread;

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(test, serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct Device {
    name: String,
    public_address: String,
    product: String,
    product_version: String,
    platform: String,
    platform_version: String,
    device: String,
    model: Option<String>,
    vendor: Option<String>,
    #[serde(
        deserialize_with = "serde_with::rust::StringWithSeparator::<CommaSeparator>::deserialize"
    )]
    provides: Vec<String>,
    client_identifier: String,
    version: Option<String>,
    id: Option<u32>,
    token: Option<String>,
    access_token: Option<String>,
    #[serde(with = "chrono::serde::ts_seconds")]
    created_at: DateTime<Utc>,
    #[serde(with = "chrono::serde::ts_seconds")]
    last_seen_at: DateTime<Utc>,
    #[serde(
        deserialize_with = "serde_with::rust::StringWithSeparator::<CommaSeparator>::deserialize",
        default
    )]
    screen_resolution: Vec<String>,
    #[serde(
        deserialize_with = "serde_with::rust::string_empty_as_none::deserialize",
        default
    )]
    screen_density: Option<u8>,
    #[serde(rename = "Connection")]
    connections: Option<Vec<Connection>>,
    #[serde(deserialize_with = "option_bool_from_int", default)]
    https_required: Option<bool>,
    #[serde(deserialize_with = "option_bool_from_int", default)]
    synced: Option<bool>,
    #[serde(deserialize_with = "option_bool_from_int", default)]
    relay: Option<bool>,
    #[serde(deserialize_with = "option_bool_from_int", default)]
    public_address_matches: Option<bool>,
    #[serde(deserialize_with = "option_bool_from_int", default)]
    presence: Option<bool>,
    #[serde(deserialize_with = "option_bool_from_int", default)]
    owned: Option<bool>,
    #[serde(rename = "SyncList")]
    sync_list: Option<SyncList>,
    #[serde(default)]
    auth_token: String,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(test, serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
struct SyncList {
    items_complete_count: u32,
    total_size: u64,
    version: u32,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(test, serde(deny_unknown_fields))]
struct Connection {
    uri: String,
    protocol: Option<String>,
    address: Option<String>,
    port: Option<u32>,
    #[serde(deserialize_with = "option_bool_from_int", default)]
    local: Option<bool>,
    #[serde(deserialize_with = "option_bool_from_int", default)]
    relay: Option<bool>,
}

impl Device {
    pub fn connect_to_server(&self) -> crate::Result<Server> {
        if !self.provides.contains(&String::from("server")) {
            // TODO: Return descriptive error
            return Err(crate::error::PlexApiError {});
        }

        if self.connections.is_none() {
            // TODO: Return descriptive error
            return Err(crate::error::PlexApiError {});
        }

        let (tx, rx) = mpsc::channel();
        let mut handlers = vec![];
        let connections = self.connections.clone().unwrap();
        for c in connections {
            let tx_clone = mpsc::Sender::clone(&tx);
            let auth_token_clone = self.auth_token.clone();
            let handler = thread::spawn(move || {
                let srv = if auth_token_clone.is_empty() {
                    Server::connect(&c.uri)
                } else {
                    Server::login(&c.uri, &auth_token_clone)
                };
                tx_clone.send(srv)
            });
            handlers.push(handler);
        }

        let mut left = handlers.len();

        loop {
            let thread_result = rx.recv();
            if thread_result.is_ok() {
                let srv = thread_result.unwrap();
                if srv.is_ok() {
                    return srv;
                }
            }
            left -= 1;
            if left == 0 {
                // TODO: Return descriptive error
                return Err(crate::error::PlexApiError {});
            }
        }
    }

    pub fn get_name(&self) -> &str {
        &self.name
    }
}

impl HasMyPlexToken for Device {
    /// Returns authentication token for current account.
    fn get_auth_token(&self) -> String {
        self.auth_token.clone()
    }

    /// Sets authentication token for current account.
    fn set_auth_token(&mut self, auth_token: &str) {
        self.auth_token = String::from(auth_token);
    }
}

impl HasDeleteUrl for Device {
    fn get_delete_url(&self) -> Option<String> {
        self.id
            .map(|id| format!("https://plex.tv/devices/{}.xml", id))
    }
}