simkl 0.1.0

Library to build queries for SIMKL and decoding JSON responses using Serde
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
//! Ratings API — two endpoints:
//!
//! * **By ID** `GET /ratings?simkl=...&fields=...&client_id=...`
//! * **By Watchlist** `GET /ratings/{type}?user_watchlist=...&fields=...&client_id=...`

use serde::Deserialize;

use crate::request::SimklRequest;

// ---------------------------------------------------------------------------
// Field-name constants
// ---------------------------------------------------------------------------

/// Constants for the `fields` query parameter accepted by both ratings endpoints.
pub mod fields {
    pub const SIMKL: &str = "simkl";
    pub const EXT: &str = "ext";
    pub const RANK: &str = "rank";
    pub const STATUS: &str = "status";
    pub const YEAR: &str = "year";
    pub const REACTIONS: &str = "reactions";
    pub const HAS_TRAILER: &str = "has_trailer";
    pub const DROPRATE: &str = "droprate";
}

// ---------------------------------------------------------------------------
// Shared sub-structs used by responses
// ---------------------------------------------------------------------------

/// Rating + vote count from one source (e.g. Simkl, IMDB, MAL).
#[derive(Debug, Clone, Deserialize)]
pub struct RatingScore {
    pub rating: Option<f32>,
    pub votes: Option<u64>,
    pub droprate: Option<String>,
    pub rank: Option<u64>,
}

/// Reactions breakdown attached to a `RatingsResponse`.
#[derive(Debug, Clone, Deserialize)]
pub struct Reactions {
    pub total: Option<u32>,
    pub reviews: Option<u32>,
    pub comments: Option<u32>,
    pub positive: Option<u32>,
    pub negative: Option<u32>,
    pub neutral: Option<u32>,
}

/// Rank sub-object in `RatingsResponse`.
#[derive(Debug, Clone, Deserialize)]
pub struct RankInfo {
    pub r#type: Option<String>,
    pub value: Option<String>,
}

// ---------------------------------------------------------------------------
// Ratings by ID
// ---------------------------------------------------------------------------

/// Response for `GET /ratings?simkl=...`.
///
/// All fields are `Option<T>` because the API returns partial objects
/// depending on which `fields` were requested.
#[derive(Debug, Clone, Deserialize)]
pub struct RatingsResponse {
    pub id: Option<u64>,
    pub link: Option<String>,
    pub simkl: Option<RatingScore>,
    pub release_year: Option<String>,
    pub reactions: Option<Reactions>,
    pub rank: Option<RankInfo>,
    pub droprate: Option<String>,
    /// Uppercase key as sent by the API.
    #[serde(rename = "IMDB")]
    pub imdb: Option<RatingScore>,
    pub has_trailer: Option<bool>,
}

/// Request for `GET /ratings` (look up by a single ID).
///
/// # Example
/// ```
/// use simkl::ratings::RatingsById;
/// use simkl::request::SimklRequest;
///
/// let url = RatingsById::new(10280)
///     .with_fields("simkl,rank,reactions")
///     .with_client_id("MY_KEY")
///     .build_url();
/// assert!(url.contains("simkl=10280"));
/// ```
#[derive(Debug, Clone, Default)]
pub struct RatingsById {
    /// Simkl ID to look up.
    pub simkl: Option<u64>,
    /// Additional ID fields (hulu, netflix, mal, tvdb, tmdb, imdb, anidb,
    /// crunchyroll, anilist, kitsu, livechart, anisearch, animeplanet,
    /// traktslug, letterboxd, type).
    pub hulu: Option<u64>,
    pub netflix: Option<u64>,
    pub mal: Option<u64>,
    pub tvdb: Option<u64>,
    pub tmdb: Option<u64>,
    pub imdb: Option<String>,
    pub anidb: Option<u64>,
    pub crunchyroll: Option<u64>,
    pub anilist: Option<u64>,
    pub kitsu: Option<u64>,
    pub livechart: Option<u64>,
    pub anisearch: Option<u64>,
    pub animeplanet: Option<u64>,
    pub traktslug: Option<String>,
    pub letterboxd: Option<String>,
    pub r#type: Option<String>,
    /// Comma-separated list of field constants (see [`fields`]).
    pub fields: Option<String>,
    /// API key (`client_id`).
    pub client_id: Option<String>,
}

impl RatingsById {
    pub fn new(simkl_id: u64) -> Self {
        Self {
            simkl: Some(simkl_id),
            ..Default::default()
        }
    }

    pub fn with_simkl(mut self, id: u64) -> Self {
        self.simkl = Some(id);
        self
    }

    pub fn with_hulu(mut self, id: u64) -> Self {
        self.hulu = Some(id);
        self
    }

    pub fn with_netflix(mut self, id: u64) -> Self {
        self.netflix = Some(id);
        self
    }

    pub fn with_mal(mut self, id: u64) -> Self {
        self.mal = Some(id);
        self
    }

    pub fn with_tvdb(mut self, id: u64) -> Self {
        self.tvdb = Some(id);
        self
    }

    pub fn with_tmdb(mut self, id: u64) -> Self {
        self.tmdb = Some(id);
        self
    }

    pub fn with_imdb(mut self, id: impl Into<String>) -> Self {
        self.imdb = Some(id.into());
        self
    }

    pub fn with_anidb(mut self, id: u64) -> Self {
        self.anidb = Some(id);
        self
    }

    pub fn with_crunchyroll(mut self, id: u64) -> Self {
        self.crunchyroll = Some(id);
        self
    }

    pub fn with_anilist(mut self, id: u64) -> Self {
        self.anilist = Some(id);
        self
    }

    pub fn with_kitsu(mut self, id: u64) -> Self {
        self.kitsu = Some(id);
        self
    }

    pub fn with_livechart(mut self, id: u64) -> Self {
        self.livechart = Some(id);
        self
    }

    pub fn with_anisearch(mut self, id: u64) -> Self {
        self.anisearch = Some(id);
        self
    }

    pub fn with_animeplanet(mut self, id: u64) -> Self {
        self.animeplanet = Some(id);
        self
    }

    pub fn with_traktslug(mut self, slug: impl Into<String>) -> Self {
        self.traktslug = Some(slug.into());
        self
    }

    pub fn with_letterboxd(mut self, slug: impl Into<String>) -> Self {
        self.letterboxd = Some(slug.into());
        self
    }

    pub fn with_type(mut self, media_type: impl Into<String>) -> Self {
        self.r#type = Some(media_type.into());
        self
    }

    /// Comma-separated list of fields to include (see [`fields`] module).
    pub fn with_fields(mut self, fields: impl Into<String>) -> Self {
        self.fields = Some(fields.into());
        self
    }

    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client_id = Some(client_id.into());
        self
    }
}

impl SimklRequest for RatingsById {
    fn endpoint(&self) -> String {
        "/ratings".to_string()
    }

    fn query_params(&self) -> Vec<(String, String)> {
        let mut params: Vec<(String, String)> = Vec::new();

        if let Some(id) = self.simkl {
            params.push(("simkl".to_string(), id.to_string()));
        }
        if let Some(id) = self.hulu {
            params.push(("hulu".to_string(), id.to_string()));
        }
        if let Some(id) = self.netflix {
            params.push(("netflix".to_string(), id.to_string()));
        }
        if let Some(id) = self.mal {
            params.push(("mal".to_string(), id.to_string()));
        }
        if let Some(id) = self.tvdb {
            params.push(("tvdb".to_string(), id.to_string()));
        }
        if let Some(id) = self.tmdb {
            params.push(("tmdb".to_string(), id.to_string()));
        }
        if let Some(ref id) = self.imdb {
            params.push(("imdb".to_string(), id.clone()));
        }
        if let Some(id) = self.anidb {
            params.push(("anidb".to_string(), id.to_string()));
        }
        if let Some(id) = self.crunchyroll {
            params.push(("crunchyroll".to_string(), id.to_string()));
        }
        if let Some(id) = self.anilist {
            params.push(("anilist".to_string(), id.to_string()));
        }
        if let Some(id) = self.kitsu {
            params.push(("kitsu".to_string(), id.to_string()));
        }
        if let Some(id) = self.livechart {
            params.push(("livechart".to_string(), id.to_string()));
        }
        if let Some(id) = self.anisearch {
            params.push(("anisearch".to_string(), id.to_string()));
        }
        if let Some(id) = self.animeplanet {
            params.push(("animeplanet".to_string(), id.to_string()));
        }
        if let Some(ref slug) = self.traktslug {
            params.push(("traktslug".to_string(), slug.clone()));
        }
        if let Some(ref slug) = self.letterboxd {
            params.push(("letterboxd".to_string(), slug.clone()));
        }
        if let Some(ref t) = self.r#type {
            params.push(("type".to_string(), t.clone()));
        }
        if let Some(ref f) = self.fields {
            params.push(("fields".to_string(), f.clone()));
        }
        if let Some(ref cid) = self.client_id {
            params.push(("client_id".to_string(), cid.clone()));
        }

        params
    }
}

// ---------------------------------------------------------------------------
// Ratings by Watchlist
// ---------------------------------------------------------------------------

/// Response item for `GET /ratings/{type}?user_watchlist=...`.
#[derive(Debug, Clone, Deserialize)]
pub struct WatchlistRatingsItem {
    pub id: Option<u64>,
    pub r#type: Option<String>,
    pub link: Option<String>,
    pub release_status: Option<String>,
    pub release_year: Option<u32>,
    pub rank: Option<u64>,
    pub simkl: Option<RatingScore>,
    pub imdb: Option<RatingScore>,
    pub mal: Option<RatingScore>,
}

/// Media type filter for the watchlist ratings endpoint path segment.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum WatchlistType {
    /// No type filter — returns all types.
    #[default]
    All,
    Tv,
    Anime,
    Movies,
}

impl WatchlistType {
    pub fn as_str(&self) -> &'static str {
        match self {
            WatchlistType::All => "",
            WatchlistType::Tv => "tv",
            WatchlistType::Anime => "anime",
            WatchlistType::Movies => "movies",
        }
    }
}

/// Request for `GET /ratings/{type}?user_watchlist=...`.
///
/// # Example
/// ```
/// use simkl::ratings::{RatingsByWatchlist, WatchlistType};
/// use simkl::request::SimklRequest;
///
/// let url = RatingsByWatchlist::default()
///     .with_watchlist_type(WatchlistType::Movies)
///     .with_user_watchlist("watching,plantowatch")
///     .with_client_id("MY_KEY")
///     .build_url();
/// assert!(url.contains("/ratings/movies"));
/// assert!(url.contains("user_watchlist=watching%2Cplantowatch"));
/// ```
#[derive(Debug, Clone, Default)]
pub struct RatingsByWatchlist {
    /// Optional path segment (`tv`, `anime`, `movies`).
    pub watchlist_type: WatchlistType,
    /// Comma-separated watchlist statuses, e.g. `"watching,plantowatch"`.
    pub user_watchlist: Option<String>,
    /// Comma-separated list of field constants (see [`fields`]).
    pub fields: Option<String>,
    /// API key (`client_id`).
    pub client_id: Option<String>,
}

impl RatingsByWatchlist {
    pub fn with_watchlist_type(mut self, t: WatchlistType) -> Self {
        self.watchlist_type = t;
        self
    }

    pub fn with_user_watchlist(mut self, statuses: impl Into<String>) -> Self {
        self.user_watchlist = Some(statuses.into());
        self
    }

    pub fn with_fields(mut self, fields: impl Into<String>) -> Self {
        self.fields = Some(fields.into());
        self
    }

    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client_id = Some(client_id.into());
        self
    }
}

impl SimklRequest for RatingsByWatchlist {
    fn endpoint(&self) -> String {
        let type_seg = self.watchlist_type.as_str();
        if type_seg.is_empty() {
            "/ratings".to_string()
        } else {
            format!("/ratings/{}", type_seg)
        }
    }

    fn query_params(&self) -> Vec<(String, String)> {
        let mut params: Vec<(String, String)> = Vec::new();

        if let Some(ref wl) = self.user_watchlist {
            params.push(("user_watchlist".to_string(), wl.clone()));
        }
        if let Some(ref f) = self.fields {
            params.push(("fields".to_string(), f.clone()));
        }
        if let Some(ref cid) = self.client_id {
            params.push(("client_id".to_string(), cid.clone()));
        }

        params
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_ratings_by_id_minimal() {
        let url = RatingsById::new(10280)
            .with_client_id("testkey")
            .build_url();
        assert_eq!(
            url,
            "https://api.simkl.com/ratings?simkl=10280&client_id=testkey"
        );
    }

    #[test]
    fn test_ratings_by_id_with_fields() {
        let url = RatingsById::new(10280)
            .with_fields("simkl,rank,reactions")
            .with_client_id("testkey")
            .build_url();
        assert_eq!(
            url,
            "https://api.simkl.com/ratings?simkl=10280&fields=simkl%2Crank%2Creactions&client_id=testkey"
        );
    }

    #[test]
    fn test_ratings_by_id_with_imdb() {
        let url = RatingsById::default()
            .with_imdb("tt0944947")
            .with_client_id("testkey")
            .build_url();
        assert_eq!(
            url,
            "https://api.simkl.com/ratings?imdb=tt0944947&client_id=testkey"
        );
    }

    #[test]
    fn test_ratings_by_watchlist_all_types() {
        let url = RatingsByWatchlist::default()
            .with_user_watchlist("watching,plantowatch")
            .with_client_id("testkey")
            .build_url();
        assert_eq!(
            url,
            "https://api.simkl.com/ratings?user_watchlist=watching%2Cplantowatch&client_id=testkey"
        );
    }

    #[test]
    fn test_ratings_by_watchlist_movies() {
        let url = RatingsByWatchlist::default()
            .with_watchlist_type(WatchlistType::Movies)
            .with_user_watchlist("watching,plantowatch")
            .with_fields("simkl,rank")
            .with_client_id("testkey")
            .build_url();
        assert_eq!(
            url,
            "https://api.simkl.com/ratings/movies?user_watchlist=watching%2Cplantowatch&fields=simkl%2Crank&client_id=testkey"
        );
    }

    #[test]
    fn test_ratings_by_watchlist_tv() {
        let url = RatingsByWatchlist::default()
            .with_watchlist_type(WatchlistType::Tv)
            .with_user_watchlist("completed")
            .with_client_id("testkey")
            .build_url();
        assert!(url.starts_with("https://api.simkl.com/ratings/tv?"));
        assert!(url.contains("user_watchlist=completed"));
    }

    #[test]
    fn test_ratings_by_watchlist_anime() {
        let url = RatingsByWatchlist::default()
            .with_watchlist_type(WatchlistType::Anime)
            .with_user_watchlist("watching")
            .with_client_id("testkey")
            .build_url();
        assert!(url.starts_with("https://api.simkl.com/ratings/anime?"));
    }

    #[test]
    fn test_field_constants() {
        assert_eq!(fields::SIMKL, "simkl");
        assert_eq!(fields::EXT, "ext");
        assert_eq!(fields::RANK, "rank");
        assert_eq!(fields::STATUS, "status");
        assert_eq!(fields::YEAR, "year");
        assert_eq!(fields::REACTIONS, "reactions");
        assert_eq!(fields::HAS_TRAILER, "has_trailer");
        assert_eq!(fields::DROPRATE, "droprate");
    }
}