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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use super::{Api, Error, Result};
use http::StatusCode;
use reqwest::RequestBuilder;
use serde_json::Value;
use std::time::Duration;
static DEFAULT_USER_AGENT: &str = "api-podcast-rust";
pub struct Client<'a> {
client: reqwest::Client,
api: Api<'a>,
user_agent: &'a str,
}
#[derive(Debug)]
pub struct Response {
pub response: reqwest::Response,
pub request: reqwest::Request,
}
impl Response {
pub async fn json(self) -> Result<Value> {
Ok(self.response.json().await?)
}
}
impl Client<'_> {
pub fn new(id: Option<&str>) -> Client {
Client {
client: reqwest::ClientBuilder::new()
.timeout(Duration::from_secs(30))
.build()
.expect("Client::new()"),
api: if let Some(id) = id {
Api::Production(id)
} else {
Api::Mock
},
user_agent: DEFAULT_USER_AGENT,
}
}
pub fn new_custom<'a>(client: reqwest::Client, id: Option<&'a str>, user_agent: Option<&'a str>) -> Client<'a> {
Client {
client,
api: if let Some(id) = id {
Api::Production(id)
} else {
Api::Mock
},
user_agent: if let Some(user_agent) = user_agent {
user_agent
} else {
DEFAULT_USER_AGENT
},
}
}
pub async fn search(&self, parameters: &Value) -> Result<Response> {
self.get("search", parameters).await
}
pub async fn typeahead(&self, parameters: &Value) -> Result<Response> {
self.get("typeahead", parameters).await
}
pub async fn fetch_best_podcasts(&self, parameters: &Value) -> Result<Response> {
self.get("best_podcasts", parameters).await
}
pub async fn fetch_podcast_by_id(&self, id: &str, parameters: &Value) -> Result<Response> {
self.get(&format!("podcasts/{}", id), parameters).await
}
pub async fn batch_fetch_podcasts(&self, parameters: &Value) -> Result<Response> {
self.post("podcasts", parameters).await
}
pub async fn fetch_episode_by_id(&self, id: &str, parameters: &Value) -> Result<Response> {
self.get(&format!("episodes/{}", id), parameters).await
}
pub async fn batch_fetch_episodes(&self, parameters: &Value) -> Result<Response> {
self.post("episodes", parameters).await
}
pub async fn fetch_curated_podcasts_list_by_id(&self, id: &str, parameters: &Value) -> Result<Response> {
self.get(&format!("curated_podcasts/{}", id), parameters).await
}
pub async fn fetch_curated_podcasts_lists(&self, parameters: &Value) -> Result<Response> {
self.get("curated_podcasts", parameters).await
}
pub async fn fetch_podcast_genres(&self, parameters: &Value) -> Result<Response> {
self.get("genres", parameters).await
}
pub async fn fetch_podcast_regions(&self, parameters: &Value) -> Result<Response> {
self.get("regions", parameters).await
}
pub async fn fetch_podcast_languages(&self, parameters: &Value) -> Result<Response> {
self.get("languages", parameters).await
}
pub async fn just_listen(&self, parameters: &Value) -> Result<Response> {
self.get("just_listen", parameters).await
}
pub async fn fetch_recommendations_for_podcast(&self, id: &str, parameters: &Value) -> Result<Response> {
self.get(&format!("podcasts/{}/recommendations", id), parameters).await
}
pub async fn fetch_recommendations_for_episode(&self, id: &str, parameters: &Value) -> Result<Response> {
self.get(&format!("episodes/{}/recommendations", id), parameters).await
}
pub async fn fetch_playlist_by_id(&self, id: &str, parameters: &Value) -> Result<Response> {
self.get(&format!("playlists/{}", id), parameters).await
}
pub async fn fetch_my_playlists(&self, parameters: &Value) -> Result<Response> {
self.get("playlists", parameters).await
}
pub async fn submit_podcast(&self, parameters: &Value) -> Result<Response> {
self.post("podcasts/submit", parameters).await
}
pub async fn delete_podcast(&self, id: &str, parameters: &Value) -> Result<Response> {
self.delete(&format!("podcasts/{}", id), parameters).await
}
async fn get(&self, endpoint: &str, parameters: &Value) -> Result<Response> {
let request = self
.client
.get(format!("{}/{}", self.api.url(), endpoint))
.query(parameters);
Ok(self.request(request).await?)
}
async fn post(&self, endpoint: &str, parameters: &Value) -> Result<Response> {
let request = self
.client
.post(format!("{}/{}", self.api.url(), endpoint))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(Self::urlencoded_from_json(parameters));
Ok(self.request(request).await?)
}
async fn delete(&self, endpoint: &str, parameters: &Value) -> Result<Response> {
let request = self
.client
.delete(format!("{}/{}", self.api.url(), endpoint))
.query(parameters);
Ok(self.request(request).await?)
}
async fn request(&self, request: RequestBuilder) -> Result<Response> {
let request = if let Api::Production(key) = self.api {
request.header("X-ListenAPI-Key", key)
} else {
request
}
.header("User-Agent", self.user_agent)
.build()?;
let response = self
.client
.execute(request.try_clone().expect(
"Error can remain unhandled because we're not using streams, which are the try_clone fail condition",
))
.await;
match &response {
Ok(response) => match response.status() {
StatusCode::NOT_FOUND => return Err(Error::NotFoundError),
StatusCode::UNAUTHORIZED => return Err(Error::AuthenticationError),
StatusCode::TOO_MANY_REQUESTS => return Err(Error::RateLimitError),
StatusCode::BAD_REQUEST => return Err(Error::InvalidRequestError),
StatusCode::INTERNAL_SERVER_ERROR => return Err(Error::ListenApiError),
_ => {}
},
Err(err) => {
if err.is_connect() || err.is_timeout() {
return Err(Error::ApiConnectionError);
}
}
};
Ok(Response {
response: response?,
request,
})
}
fn urlencoded_from_json(json: &Value) -> String {
if let Some(v) = json.as_object() {
v.iter()
.map(|(key, value)| {
format!(
"{}={}",
key,
match value {
Value::String(s) => s.to_owned(),
_ => format!("{}", value),
}
)
})
.collect::<Vec<String>>()
.join("&")
} else {
String::new()
}
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
#[test]
fn urlencoded_from_json() {
assert_eq!(
super::Client::urlencoded_from_json(&json!({
"a": 1,
"b": true,
"c": "test_string"
})),
"a=1&b=true&c=test_string"
);
}
}