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
use crate::{
my_plex::{MyPlexAccount, MyPlexApiErrorResponse},
InternalHttpApi, PlexApiError,
};
use reqwest::StatusCode;
use serde_json;
const WEBHOOKS_URL: &str = "api/v2/user/webhooks";
#[derive(Debug, Deserialize)]
#[cfg_attr(all(test, feature = "test_new_attributes"), serde(deny_unknown_fields))]
struct Webhook {
url: String,
}
impl MyPlexAccount {
pub async fn get_webhooks(&self) -> crate::Result<Vec<String>> {
let response = self.get(WEBHOOKS_URL).await?;
if response.status() == StatusCode::OK {
let hooks: Vec<Webhook> = serde_json::from_str(response.text().await?.as_str())?;
let mut ret: Vec<String> = Vec::new();
for hook in hooks {
ret.push(hook.url)
}
Ok(ret)
} else {
let err: MyPlexApiErrorResponse = response.json().await?;
Err(core::convert::From::from(err))
}
}
pub async fn set_webhooks(&self, webhooks: &[&str]) -> crate::Result<()> {
let params = if webhooks.is_empty() {
vec![("urls", "")]
} else {
webhooks.iter().map(|&url| ("urls[]", url)).collect()
};
let response = self.post_form(WEBHOOKS_URL, ¶ms).await?;
if response.status() == StatusCode::CREATED {
Ok(())
} else {
let err: MyPlexApiErrorResponse = response.json().await?;
Err(core::convert::From::from(err))
}
}
pub async fn add_webhook(&self, webhook: &str) -> crate::Result<()> {
let webhooks = self.get_webhooks().await?;
let mut webhooks: Vec<&str> = webhooks.iter().map(|s| &**s).collect();
webhooks.push(webhook);
self.set_webhooks(&webhooks).await
}
pub async fn del_webhook(&self, webhook: &str) -> crate::Result<()> {
let webhooks: Vec<String> = self.get_webhooks().await?;
let original_len = webhooks.len();
let new_webhooks: Vec<&str> = webhooks
.iter()
.filter(|&value| *value != *webhook)
.map(|s| &**s)
.collect();
if original_len == new_webhooks.len() {
Err(PlexApiError::WebhookNotFound {
url: String::from(webhook),
})
} else {
self.set_webhooks(&new_webhooks).await
}
}
}