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
use crate::{API_URL, Extended, MediaIds};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Retrieve the latest activity timestamps for the user. This endpoint provides timestamps for
/// various categories and media types, indicating the last time each was updated.
///
/// ```text
/// POST https://api.simkl.com/sync/activities
/// Headers:
///     Authorization: Bearer [token]
///     simkl-api-key: [client_id]
/// ```
pub const USER_ACTIVITIES: &str = "https://api.simkl.com/sync/activities";

#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
pub struct SyncSettings {
    pub all: DateTime<Utc>,
}

#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
pub struct MediaActivity {
    pub all: DateTime<Utc>,
    pub rated_at: DateTime<Utc>,
    #[serde(rename = "plantowatch")]
    pub plan_to_watch: DateTime<Utc>,
    pub watching: Option<DateTime<Utc>>,
    pub completed: DateTime<Utc>,
    pub hold: Option<DateTime<Utc>>,
    pub dropped: DateTime<Utc>,
    pub removed_from_list: DateTime<Utc>,
}

#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
pub struct Activities {
    pub all: DateTime<Utc>,
    pub settings: SyncSettings,
    pub tv_shows: MediaActivity,
    pub anime: MediaActivity,
    pub movies: MediaActivity,
}

/// Retrieve the entire watchlist.
///
/// ```text
/// POST https://api.simkl.com/sync/all-items/
/// Headers:
///     Authorization: Bearer [token]
///     simkl-api-key: [client_id]
/// ```
pub const USER_ITEMS: &str = "https://api.simkl.com/sync/all-items/";

/// Instead of getting everything, you can get only one element (animes, movies, shows, ..., ratings, ...). You can
/// also use a starting date
pub fn get_all_items_request(
    what: Option<String>,
    from: Option<DateTime<Utc>>,
    _extended: Option<Extended>,
) -> String {
    // TODO: may use payload instead because we can filter on more stuffs: https://simkl.docs.apiary.io/reference/sync/get-all-items
    let mut result = String::from(USER_ITEMS);
    if let Some(w) = what {
        result.push_str(&w);
        result.push('/');
    }
    if let Some(d) = from {
        result.push_str("?date_from=");
        result.push_str(&d.to_rfc3339());
    }
    result
}

pub fn get_add_to_history_request() -> String {
    let mut result = String::from(API_URL);
    result.push_str("/sync/history");
    // TODO: https://simkl.docs.apiary.io/#reference/sync/add-items-to-the-history/add-items-to-watched/watching-history?console=1
    result
}

pub fn get_remove_from_history_request() -> String {
    let mut result = String::from(API_URL);
    result.push_str("/sync/history/remove");
    // TODO: https://simkl.docs.apiary.io/#reference/sync/remove-items-from-history-and-from-lists/remove-items-from-watched/watching-history?console=1
    result
}

pub fn get_add_ratings_request() -> String {
    let mut result = String::from(API_URL);
    result.push_str("/sync/ratings");
    // TODO: https://simkl.docs.apiary.io/#reference/sync/add-ratings/add-new-ratings?console=1
    result
}

pub fn get_remove_ratings_request() -> String {
    let mut result = String::from(API_URL);
    result.push_str("/sync/ratings/remove");
    // TODO: https://simkl.docs.apiary.io/#reference/sync/remove-ratings/remove-ratings?console=1
    result
}

pub fn get_add_to_list_request() -> String {
    let mut result = String::from(API_URL);
    result.push_str("/sync/add-to-list");
    // TODO: https://simkl.docs.apiary.io/#reference/sync/add-item-to-the-list/add-items-to-specific-list?console=1
    result
}

pub fn get_check_if_watched_request() -> String {
    let mut result = String::from(API_URL);
    result.push_str("/sync/watched");
    // TODO: https://simkl.docs.apiary.io/#reference/sync/check-if-watched/get-specific-user's-watched-items?console=1
    result
}

// ============================================================================
// Sync payload types — request bodies for the POST sync endpoints
// ============================================================================

/// A watched season entry inside a show sync payload.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WatchedSeason {
    pub number: u32,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub episodes: Vec<WatchedEpisode>,
}

/// A single watched episode (used inside season lists or show-level episode arrays).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatchedEpisode {
    pub number: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub watched_at: Option<DateTime<Utc>>,
}

// ---------------------------------------------------------------------------
// History — POST /sync/history  (add) and POST /sync/history/remove (remove)
// ---------------------------------------------------------------------------

/// An individual movie to add/remove from watch history.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MovieHistoryItem {
    pub ids: MediaIds,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub watched_at: Option<DateTime<Utc>>,
}

/// An individual TV show to add to/remove from watch history.
/// Episodes can be specified at the show, season, or episode level.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShowHistoryItem {
    pub ids: MediaIds,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub seasons: Vec<WatchedSeason>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub episodes: Vec<WatchedEpisode>,
}

/// An individual anime to add to/remove from watch history.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnimeHistoryItem {
    pub ids: MediaIds,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub seasons: Vec<WatchedSeason>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub episodes: Vec<WatchedEpisode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub watched_at: Option<DateTime<Utc>>,
}

/// Payload for `POST /sync/history` (add to watched history) and `POST /sync/history/remove`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SyncHistoryPayload {
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub movies: Vec<MovieHistoryItem>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub shows: Vec<ShowHistoryItem>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub anime: Vec<AnimeHistoryItem>,
}

impl SyncHistoryPayload {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_movie(mut self, item: MovieHistoryItem) -> Self {
        self.movies.push(item);
        self
    }

    pub fn with_show(mut self, item: ShowHistoryItem) -> Self {
        self.shows.push(item);
        self
    }

    pub fn with_anime(mut self, item: AnimeHistoryItem) -> Self {
        self.anime.push(item);
        self
    }
}

// ---------------------------------------------------------------------------
// Ratings — POST /sync/ratings (add) and POST /sync/ratings/remove (remove)
// ---------------------------------------------------------------------------

/// An individual movie rating.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MovieRatingItem {
    pub ids: MediaIds,
    /// Rating value 1–10.
    pub rating: u8,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rated_at: Option<DateTime<Utc>>,
}

/// An individual show rating.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShowRatingItem {
    pub ids: MediaIds,
    /// Rating value 1–10.
    pub rating: u8,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rated_at: Option<DateTime<Utc>>,
}

/// An individual anime rating.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnimeRatingItem {
    pub ids: MediaIds,
    /// Rating value 1–10.
    pub rating: u8,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rated_at: Option<DateTime<Utc>>,
}

/// Payload for `POST /sync/ratings` (add ratings) and `POST /sync/ratings/remove`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SyncRatingPayload {
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub movies: Vec<MovieRatingItem>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub shows: Vec<ShowRatingItem>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub anime: Vec<AnimeRatingItem>,
}

impl SyncRatingPayload {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_movie(mut self, item: MovieRatingItem) -> Self {
        self.movies.push(item);
        self
    }

    pub fn with_show(mut self, item: ShowRatingItem) -> Self {
        self.shows.push(item);
        self
    }

    pub fn with_anime(mut self, item: AnimeRatingItem) -> Self {
        self.anime.push(item);
        self
    }
}

// ---------------------------------------------------------------------------
// List — POST /sync/add-to-list
// ---------------------------------------------------------------------------

/// A movie to add to a specific list.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MovieListItem {
    pub ids: MediaIds,
    /// The list to add to. Possible values: `plantowatch`, `notinteresting`.
    pub to: String,
}

/// A show to add to a specific list.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShowListItem {
    pub ids: MediaIds,
    /// The list to add to. Possible values: `plantowatch`, `notinteresting`, `watching`, `hold`, `completed`, `dropped`.
    pub to: String,
}

/// An anime to add to a specific list.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnimeListItem {
    pub ids: MediaIds,
    /// The list to add to. Possible values: `plantowatch`, `notinteresting`, `watching`, `hold`, `completed`, `dropped`.
    pub to: String,
}

/// Payload for `POST /sync/add-to-list`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SyncListPayload {
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub movies: Vec<MovieListItem>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub shows: Vec<ShowListItem>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub anime: Vec<AnimeListItem>,
}

impl SyncListPayload {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_movie(mut self, item: MovieListItem) -> Self {
        self.movies.push(item);
        self
    }

    pub fn with_show(mut self, item: ShowListItem) -> Self {
        self.shows.push(item);
        self
    }

    pub fn with_anime(mut self, item: AnimeListItem) -> Self {
        self.anime.push(item);
        self
    }
}

// ---------------------------------------------------------------------------
// Sync API response types
// ---------------------------------------------------------------------------

/// Item counts in a `SyncResult`.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SyncAddedCounts {
    pub movies: Option<u32>,
    pub shows: Option<u32>,
    pub episodes: Option<u32>,
    pub anime: Option<u32>,
}

/// Items the API could not process (unrecognised IDs, etc.).
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SyncNotFound {
    pub movies: Option<Vec<MediaIds>>,
    pub shows: Option<Vec<MediaIds>>,
    pub episodes: Option<Vec<MediaIds>>,
    pub anime: Option<Vec<MediaIds>>,
}

/// Standard response body for POST sync endpoints.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct SyncResult {
    pub added: Option<SyncAddedCounts>,
    pub deleted: Option<SyncAddedCounts>,
    pub not_found: Option<SyncNotFound>,
}

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

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

    #[test]
    fn test_sync_history_payload_serialise_movie() {
        let payload = SyncHistoryPayload::new().with_movie(MovieHistoryItem {
            ids: MediaIds::new().with_imdb("tt0816692".to_string()),
            watched_at: None,
        });
        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"movies\""));
        assert!(json.contains("tt0816692"));
        assert!(!json.contains("\"shows\""));
        assert!(!json.contains("\"anime\""));
    }

    #[test]
    fn test_sync_history_payload_serialise_show_with_seasons() {
        let payload = SyncHistoryPayload::new().with_show(ShowHistoryItem {
            ids: MediaIds::new().with_simkl(12345),
            seasons: vec![WatchedSeason {
                number: 1,
                episodes: vec![WatchedEpisode {
                    number: 1,
                    watched_at: None,
                }],
            }],
            episodes: vec![],
        });
        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"shows\""));
        assert!(json.contains("\"seasons\""));
        assert!(json.contains("\"episodes\""));
    }

    #[test]
    fn test_sync_rating_payload_serialise() {
        let payload = SyncRatingPayload::new().with_movie(MovieRatingItem {
            ids: MediaIds::new().with_imdb("tt0111161".to_string()),
            rating: 10,
            rated_at: None,
        });
        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"rating\":10"));
        assert!(json.contains("tt0111161"));
        assert!(!json.contains("\"shows\""));
    }

    #[test]
    fn test_sync_list_payload_serialise() {
        let payload = SyncListPayload::new().with_show(ShowListItem {
            ids: MediaIds::new().with_simkl(999),
            to: "plantowatch".to_string(),
        });
        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"plantowatch\""));
        assert!(json.contains("\"shows\""));
        assert!(!json.contains("\"movies\""));
    }

    #[test]
    fn test_get_add_to_history_url() {
        assert_eq!(
            get_add_to_history_request(),
            "https://api.simkl.com/sync/history"
        );
    }

    #[test]
    fn test_get_remove_from_history_url() {
        assert_eq!(
            get_remove_from_history_request(),
            "https://api.simkl.com/sync/history/remove"
        );
    }

    #[test]
    fn test_get_add_ratings_url() {
        assert_eq!(
            get_add_ratings_request(),
            "https://api.simkl.com/sync/ratings"
        );
    }

    #[test]
    fn test_get_add_to_list_url() {
        assert_eq!(
            get_add_to_list_request(),
            "https://api.simkl.com/sync/add-to-list"
        );
    }
}