yamuse 0.2.0

typed async client for the yandex music api: catalogue, likes, playlists, radio, lossless downloads and ynison realtime
Documentation
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! the client and its builder.

use std::sync::{Arc, RwLock};
use std::time::Duration;

use serde::de::DeserializeOwned;
use serde_json::Value;

use crate::error::{Error, Result};
use crate::models::Status;
use crate::params::Params;
use crate::transport::{
    DEFAULT_DOWNLOAD_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, RetryPolicy, Transport,
};
use crate::types::{BatchObject, Language};

/// default api origin.
pub const DEFAULT_BASE_URL: &str = "https://api.music.yandex.net";

/// default device descriptor sent with queue requests.
pub const DEFAULT_DEVICE: &str =
    "os=Rust; os_version=; manufacturer=yamuse; model=yamuse; clid=; device_id=random; uuid=random";

/// shared state behind a [`Client`]. cloning a client shares this.
#[derive(Debug)]
struct Inner {
    transport: Transport,
    base_url: String,
    language: Language,
    device: String,
    token: Option<String>,
    /// filled in by [`Client::init`]; some endpoints default their `userId` to it.
    account: RwLock<Option<Status>>,
}

/// a typed, async client for the yandex music api.
///
/// cloning is cheap — clones share one connection pool and one account cache — so
/// pass clones around rather than wrapping in another `Arc`.
///
/// # examples
///
/// ```no_run
/// use yamuse::Client;
///
/// # async fn run() -> Result<(), yamuse::Error> {
/// let client = Client::builder().token("your-oauth-token").build()?;
/// let tracks = client.tracks([2]).await?;
/// println!("{:?}", tracks.first().and_then(|t| t.title.as_deref()));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Client {
    inner: Arc<Inner>,
}

impl Client {
    /// start configuring a client.
    #[must_use]
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// build an anonymous client, without a token.
    ///
    /// enough for the device-auth endpoints and a few public ones; everything else
    /// answers 401.
    ///
    /// # errors
    ///
    /// returns [`Error::InvalidResponse`] when the default headers cannot be built.
    pub fn anonymous() -> Result<Self> {
        ClientBuilder::default().build()
    }

    /// load the account status, enabling endpoints that default to "me".
    ///
    /// call this once after building. without it, methods whose `user_id` is
    /// optional have no uid to fall back to and will fail.
    ///
    /// # errors
    ///
    /// returns a transport error, or [`Error::Unauthorized`] when the token is
    /// invalid.
    pub async fn init(&self) -> Result<&Self> {
        let status = self.account_status().await?;
        // the lock is only ever held for this write and for short uid reads
        if let Ok(mut guard) = self.inner.account.write() {
            *guard = Some(status);
        }
        Ok(self)
    }

    /// the cached account status, once [`init`](Self::init) has run.
    #[must_use]
    pub fn me(&self) -> Option<Status> {
        self.inner.account.read().ok()?.clone()
    }

    /// the authenticated account's uid, once [`init`](Self::init) has run.
    #[must_use]
    pub fn account_uid(&self) -> Option<i64> {
        self.inner.account.read().ok()?.as_ref()?.uid()
    }

    /// the oauth token this client authenticates with, if any.
    #[must_use]
    pub fn token(&self) -> Option<&str> {
        self.inner.token.as_deref()
    }

    /// the api origin requests are built against.
    #[must_use]
    pub fn base_url(&self) -> &str {
        &self.inner.base_url
    }

    /// the response language.
    #[must_use]
    pub fn language(&self) -> Language {
        self.inner.language
    }

    /// the device descriptor sent with queue requests.
    #[must_use]
    pub fn device(&self) -> &str {
        &self.inner.device
    }

    /// the http transport, for streaming downloads and raw retrievals.
    #[must_use]
    pub fn transport(&self) -> &Transport {
        &self.inner.transport
    }

    // ── internals shared by the method modules ──────────────────────────────

    /// build an absolute url from a path relative to the api origin.
    pub(crate) fn url(&self, path: &str) -> String {
        format!("{}{path}", self.inner.base_url)
    }

    /// resolve the uid an endpoint should act on: the explicit one, else "me".
    ///
    /// # errors
    ///
    /// returns [`Error::IdMissing`] when no uid was given and [`init`](Self::init)
    /// has not run — a clearer failure than the 404 the api would answer.
    pub(crate) fn resolve_uid(&self, user_id: Option<i64>) -> Result<i64> {
        user_id
            .or_else(|| self.account_uid())
            .ok_or(Error::IdMissing(
                "user id: pass one explicitly or call init() first",
            ))
    }

    pub(crate) async fn get<T: DeserializeOwned>(&self, path: &str, params: Params) -> Result<T> {
        self.inner.transport.get(&self.url(path), &params).await
    }

    /// deserialize a payload the tolerant way, so a field whose type changed
    /// upstream costs that field rather than the whole call.
    pub(crate) fn decode<T: DeserializeOwned>(&self, value: Value) -> Result<T> {
        self.inner.transport.decode(value)
    }

    pub(crate) async fn get_value(&self, path: &str, params: Params) -> Result<Value> {
        self.inner
            .transport
            .get_value(&self.url(path), &params, &[])
            .await
    }

    pub(crate) async fn get_with_headers<T: DeserializeOwned>(
        &self,
        path: &str,
        params: Params,
        headers: &[(&str, &str)],
    ) -> Result<T> {
        self.inner
            .transport
            .get_with_headers(&self.url(path), &params, headers)
            .await
    }

    pub(crate) async fn post_form<T: DeserializeOwned>(
        &self,
        path: &str,
        form: Params,
    ) -> Result<T> {
        self.inner.transport.post_form(&self.url(path), form).await
    }

    pub(crate) async fn post_form_value(&self, path: &str, form: Params) -> Result<Value> {
        self.inner
            .transport
            .post_form_value(&self.url(path), form, &[])
            .await
    }

    pub(crate) async fn post_form_value_with_headers(
        &self,
        path: &str,
        form: Params,
        headers: &[(&str, &str)],
    ) -> Result<Value> {
        self.inner
            .transport
            .post_form_value(&self.url(path), form, headers)
            .await
    }

    pub(crate) async fn post_json_value(&self, path: &str, json: &Value) -> Result<Value> {
        self.inner
            .transport
            .post_json_value(&self.url(path), json, &[])
            .await
    }

    pub(crate) async fn post_raw_json_value(
        &self,
        path: &str,
        json: String,
        headers: &[(&str, &str)],
    ) -> Result<Value> {
        self.inner
            .transport
            .post_raw_json_value(&self.url(path), json, headers)
            .await
    }

    pub(crate) async fn put_value(&self, path: &str, json: &Value) -> Result<Value> {
        self.inner.transport.put_value(&self.url(path), json).await
    }

    pub(crate) async fn delete_value(&self, path: &str, json: &Value) -> Result<Value> {
        self.inner
            .transport
            .delete_value(&self.url(path), json)
            .await
    }

    /// `POST` to an absolute url — the oauth host is not the api origin.
    pub(crate) async fn post_form_absolute(&self, url: &str, form: Params) -> Result<Value> {
        self.inner.transport.post_form_value(url, form, &[]).await
    }

    /// fetch a batch of objects from a `/{type}s` endpoint.
    ///
    /// the api takes these ids as a repeated form field rather than in the path,
    /// which is why an "id lookup" is a `POST`.
    pub(crate) async fn get_batch<T: DeserializeOwned>(
        &self,
        object: BatchObject,
        ids: impl IntoIterator<Item = impl std::fmt::Display>,
        extra: Params,
    ) -> Result<Vec<T>> {
        let kind = object.as_str();
        let suffix = if object == BatchObject::Playlist {
            "/list"
        } else {
            ""
        };
        let form = extra.add_all(&format!("{kind}-ids"), ids);
        self.post_form(&format!("/{kind}s{suffix}"), form).await
    }

    /// whether a mutation endpoint answered with its success marker.
    ///
    /// most answer the bare string `"ok"`; the track like/dislike endpoints answer
    /// an object carrying the new library `revision` instead.
    pub(crate) fn is_ok_response(value: &Value) -> bool {
        match value {
            Value::String(s) => s == "ok",
            Value::Object(map) => {
                map.contains_key("revision")
                    || map.get("status") == Some(&Value::String("ok".into()))
            },
            _ => false,
        }
    }
}

/// builder for [`Client`].
#[derive(Clone)]
pub struct ClientBuilder {
    token: Option<String>,
    base_url: String,
    language: Language,
    device: String,
    user_agent: String,
    headers: Vec<(String, String)>,
    timeout: Duration,
    download_timeout: Duration,
    retry: RetryPolicy,
    http: Option<reqwest::Client>,
    on_field_repair: Option<crate::transport::FieldRepairHook>,
}

// hand-written because the dropped-field hook is a closure.
impl std::fmt::Debug for ClientBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientBuilder")
            .field("base_url", &self.base_url)
            .field("language", &self.language)
            .field("device", &self.device)
            .field("user_agent", &self.user_agent)
            .field("timeout", &self.timeout)
            .field("download_timeout", &self.download_timeout)
            .field("retry", &self.retry)
            .field("has_token", &self.token.is_some())
            .field("on_field_repair", &self.on_field_repair.is_some())
            .finish_non_exhaustive()
    }
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self {
            token: None,
            base_url: DEFAULT_BASE_URL.to_owned(),
            language: Language::default(),
            device: DEFAULT_DEVICE.to_owned(),
            user_agent: DEFAULT_USER_AGENT.to_owned(),
            headers: Vec::new(),
            timeout: DEFAULT_TIMEOUT,
            download_timeout: DEFAULT_DOWNLOAD_TIMEOUT,
            retry: RetryPolicy::default(),
            http: None,
            on_field_repair: None,
        }
    }
}

impl ClientBuilder {
    /// authenticate with an oauth token.
    #[must_use]
    pub fn token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// override the api origin — useful for pointing tests at a mock server.
    #[must_use]
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        let mut base_url = base_url.into();
        base_url.truncate(base_url.trim_end_matches('/').len());
        self.base_url = base_url;
        self
    }

    /// set the response language.
    #[must_use]
    pub fn language(mut self, language: Language) -> Self {
        self.language = language;
        self
    }

    /// set the device descriptor sent with queue requests.
    #[must_use]
    pub fn device(mut self, device: impl Into<String>) -> Self {
        self.device = device.into();
        self
    }

    /// override the `user-agent`.
    #[must_use]
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = user_agent.into();
        self
    }

    /// add a header sent with every request.
    #[must_use]
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// set the per-request timeout for json calls.
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// set the timeout for raw downloads.
    #[must_use]
    pub fn download_timeout(mut self, timeout: Duration) -> Self {
        self.download_timeout = timeout;
        self
    }

    /// set the retry policy for idempotent requests.
    #[must_use]
    pub fn retry(mut self, retry: RetryPolicy) -> Self {
        self.retry = retry;
        self
    }

    /// supply a pre-configured `reqwest` client — proxies, custom tls, a shared
    /// connection pool.
    #[must_use]
    pub fn http_client(mut self, http: reqwest::Client) -> Self {
        self.http = Some(http);
        self
    }

    /// be told when a response field had to be repaired because its type did not
    /// match the model.
    ///
    /// the api does change field types without notice, and this crate repairs just
    /// that field rather than failing the request (see [`crate::tolerant`]). that
    /// keeps things working, but silently — wire this to your logger so drift
    /// surfaces instead of accumulating.
    ///
    /// filter on [`FieldRepair::is_lossy`](crate::tolerant::FieldRepair::is_lossy)
    /// to ignore harmless number narrowing and hear only about real drift.
    ///
    /// # examples
    ///
    /// ```
    /// # fn main() -> Result<(), yamuse::Error> {
    /// let client = yamuse::Client::builder()
    ///     .token("t")
    ///     .on_field_repair(|repair| eprintln!("yandex music api: {repair}"))
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn on_field_repair(
        mut self,
        hook: impl Fn(&crate::tolerant::FieldRepair) + Send + Sync + 'static,
    ) -> Self {
        self.on_field_repair = Some(std::sync::Arc::new(hook));
        self
    }

    /// build the client.
    ///
    /// # errors
    ///
    /// returns [`Error::InvalidResponse`] when the token, language or a custom
    /// header contains bytes that are not valid in an http header, or
    /// [`Error::Network`] when the default http client cannot be constructed.
    pub fn build(self) -> Result<Client> {
        let http = match self.http {
            Some(http) => http,
            None => reqwest::Client::builder()
                .build()
                .map_err(|e| Error::Network(format!("could not build the http client: {e}")))?,
        };

        let transport = Transport::new(
            http,
            self.token.as_deref(),
            self.language.as_str(),
            &self.user_agent,
            &self.headers,
            self.timeout,
            self.download_timeout,
            self.retry,
            self.on_field_repair,
        )?;

        Ok(Client {
            inner: Arc::new(Inner {
                transport,
                base_url: self.base_url,
                language: self.language,
                device: self.device,
                token: self.token,
                account: RwLock::new(None),
            }),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn urls_are_built_against_the_configured_origin() {
        let client = Client::builder()
            .base_url("https://example.test/")
            .build()
            .unwrap();
        assert_eq!(client.base_url(), "https://example.test");
        assert_eq!(client.url("/tracks/1"), "https://example.test/tracks/1");
    }

    #[test]
    fn an_anonymous_client_carries_no_token() {
        let client = Client::anonymous().unwrap();
        assert!(client.token().is_none());
        assert!(client.account_uid().is_none());
        assert!(client.me().is_none());
    }

    #[test]
    fn builder_options_land_on_the_client() {
        let client = Client::builder()
            .token("t")
            .language(Language::En)
            .device("os=Test")
            .build()
            .unwrap();
        assert_eq!(client.token(), Some("t"));
        assert_eq!(client.language(), Language::En);
        assert_eq!(client.device(), "os=Test");
    }

    #[test]
    fn a_uid_is_required_when_init_has_not_run() {
        let client = Client::anonymous().unwrap();
        assert!(client.resolve_uid(None).is_err());
        assert_eq!(client.resolve_uid(Some(42)).unwrap(), 42);
    }

    #[test]
    fn a_token_with_illegal_header_bytes_is_rejected_at_build_time() {
        // a newline in a header value would otherwise smuggle a second header
        assert!(Client::builder().token("bad\nvalue").build().is_err());
    }

    #[test]
    fn success_markers_cover_both_shapes_the_api_uses() {
        assert!(Client::is_ok_response(&Value::String("ok".into())));
        assert!(Client::is_ok_response(&serde_json::json!({"revision": 42})));
        assert!(Client::is_ok_response(&serde_json::json!({"status": "ok"})));

        assert!(!Client::is_ok_response(&Value::String("nope".into())));
        assert!(!Client::is_ok_response(&serde_json::json!({})));
        assert!(!Client::is_ok_response(&Value::Null));
        assert!(!Client::is_ok_response(
            &serde_json::json!({"status": "error"})
        ));
    }

    #[test]
    fn clones_share_the_account_cache() {
        let client = Client::anonymous().unwrap();
        let clone = client.clone();
        // both views start empty and point at the same inner state
        assert!(client.me().is_none());
        assert!(clone.me().is_none());
        assert!(Arc::ptr_eq(&client.inner, &clone.inner));
    }
}