animedb 0.3.1

Local-first anime and manga metadata catalog for Rust media servers
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
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt;
use std::str::FromStr;

use crate::error::{Error, Result};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)]
#[serde(rename_all = "snake_case")]
pub enum MediaKind {
    Anime,
    Manga,
    Show,
    Movie,
}

impl MediaKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Anime => "anime",
            Self::Manga => "manga",
            Self::Show => "show",
            Self::Movie => "movie",
        }
    }
}

impl fmt::Display for MediaKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for MediaKind {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        match value {
            "anime" | "ANIME" => Ok(Self::Anime),
            "manga" | "MANGA" => Ok(Self::Manga),
            "show" | "SHOW" => Ok(Self::Show),
            "movie" | "MOVIE" => Ok(Self::Movie),
            other => Err(Error::Validation(format!(
                "unsupported media kind: {other}"
            ))),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)]
#[serde(rename_all = "snake_case")]
pub enum SourceName {
    AniList,
    MyAnimeList,
    Jikan,
    Kitsu,
    Tvmaze,
    Imdb,
}

impl SourceName {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AniList => "anilist",
            Self::MyAnimeList => "myanimelist",
            Self::Jikan => "jikan",
            Self::Kitsu => "kitsu",
            Self::Tvmaze => "tvmaze",
            Self::Imdb => "imdb",
        }
    }
}

impl fmt::Display for SourceName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for SourceName {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        match value {
            "anilist" => Ok(Self::AniList),
            "myanimelist" => Ok(Self::MyAnimeList),
            "jikan" => Ok(Self::Jikan),
            "kitsu" => Ok(Self::Kitsu),
            "tvmaze" => Ok(Self::Tvmaze),
            "imdb" => Ok(Self::Imdb),
            other => Err(Error::Validation(format!("unsupported source: {other}"))),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExternalId {
    pub source: SourceName,
    pub source_id: String,
    pub url: Option<String>,
}

impl ExternalId {
    pub fn is_strong_identity(&self) -> bool {
        matches!(self.source, SourceName::MyAnimeList | SourceName::AniList)
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SourcePayload {
    pub source: SourceName,
    pub source_id: String,
    pub url: Option<String>,
    pub remote_updated_at: Option<String>,
    pub raw_json: Option<Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CanonicalMedia {
    pub media_kind: MediaKind,
    pub title_display: String,
    pub title_romaji: Option<String>,
    pub title_english: Option<String>,
    pub title_native: Option<String>,
    pub synopsis: Option<String>,
    pub format: Option<String>,
    pub status: Option<String>,
    pub season: Option<String>,
    pub season_year: Option<i32>,
    pub episodes: Option<i32>,
    pub chapters: Option<i32>,
    pub volumes: Option<i32>,
    pub country_of_origin: Option<String>,
    pub cover_image: Option<String>,
    pub banner_image: Option<String>,
    pub provider_rating: Option<f64>,
    pub nsfw: bool,
    pub aliases: Vec<String>,
    pub genres: Vec<String>,
    pub tags: Vec<String>,
    pub external_ids: Vec<ExternalId>,
    pub source_payloads: Vec<SourcePayload>,
    pub field_provenance: Vec<FieldProvenance>,
}

impl CanonicalMedia {
    pub fn validate(&self) -> Result<()> {
        if self.title_display.trim().is_empty() {
            return Err(Error::Validation("title_display cannot be empty".into()));
        }

        if self.external_ids.is_empty() {
            return Err(Error::Validation(
                "at least one external id is required to persist media".into(),
            ));
        }

        Ok(())
    }

    pub fn name(&self) -> &str {
        &self.title_display
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StoredMedia {
    pub id: i64,
    pub media_kind: MediaKind,
    pub title_display: String,
    pub title_romaji: Option<String>,
    pub title_english: Option<String>,
    pub title_native: Option<String>,
    pub synopsis: Option<String>,
    pub format: Option<String>,
    pub status: Option<String>,
    pub season: Option<String>,
    pub season_year: Option<i32>,
    pub episodes: Option<i32>,
    pub chapters: Option<i32>,
    pub volumes: Option<i32>,
    pub country_of_origin: Option<String>,
    pub cover_image: Option<String>,
    pub banner_image: Option<String>,
    pub provider_rating: Option<f64>,
    pub nsfw: bool,
    pub aliases: Vec<String>,
    pub genres: Vec<String>,
    pub tags: Vec<String>,
    pub external_ids: Vec<ExternalId>,
    pub source_payloads: Vec<SourcePayload>,
    pub field_provenance: Vec<FieldProvenance>,
}

impl StoredMedia {
    pub fn name(&self) -> &str {
        &self.title_display
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FieldProvenance {
    pub field_name: String,
    pub source: SourceName,
    pub source_id: String,
    pub score: f64,
    pub reason: String,
    pub updated_at: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SearchOptions {
    pub limit: usize,
    pub offset: usize,
    pub media_kind: Option<MediaKind>,
    pub format: Option<String>,
}

impl Default for SearchOptions {
    fn default() -> Self {
        Self {
            limit: 20,
            offset: 0,
            media_kind: None,
            format: None,
        }
    }
}

impl SearchOptions {
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }

    pub fn with_offset(mut self, offset: usize) -> Self {
        self.offset = offset;
        self
    }

    pub fn with_media_kind(mut self, media_kind: MediaKind) -> Self {
        self.media_kind = Some(media_kind);
        self
    }

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

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SearchHit {
    pub media_id: i64,
    pub media_kind: MediaKind,
    pub title_display: String,
    pub synopsis: Option<String>,
    pub score: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SyncMode {
    Full,
    Incremental,
}

impl SyncMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::Incremental => "incremental",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncCursor {
    pub page: usize,
}

impl Default for SyncCursor {
    fn default() -> Self {
        Self { page: 1 }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyncRequest {
    pub source: SourceName,
    pub media_kind: Option<MediaKind>,
    pub mode: SyncMode,
    pub page_size: usize,
    pub max_pages: Option<usize>,
    pub start_cursor: Option<SyncCursor>,
}

impl SyncRequest {
    pub fn new(source: SourceName) -> Self {
        Self {
            source,
            media_kind: None,
            mode: SyncMode::Full,
            page_size: 50,
            max_pages: None,
            start_cursor: None,
        }
    }

    pub fn with_media_kind(mut self, media_kind: MediaKind) -> Self {
        self.media_kind = Some(media_kind);
        self
    }

    pub fn with_mode(mut self, mode: SyncMode) -> Self {
        self.mode = mode;
        self
    }

    pub fn with_page_size(mut self, page_size: usize) -> Self {
        self.page_size = page_size;
        self
    }

    pub fn with_max_pages(mut self, max_pages: usize) -> Self {
        self.max_pages = Some(max_pages);
        self
    }

    pub fn with_start_cursor(mut self, cursor: SyncCursor) -> Self {
        self.start_cursor = Some(cursor);
        self
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyncOutcome {
    pub source: SourceName,
    pub media_kind: Option<MediaKind>,
    pub fetched_pages: usize,
    pub upserted_records: usize,
    pub last_cursor: Option<SyncCursor>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyncReport {
    pub outcomes: Vec<SyncOutcome>,
    pub total_upserted_records: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PersistedSyncState {
    pub source: SourceName,
    pub scope: String,
    pub cursor: Option<SyncCursor>,
    pub last_success_at: Option<String>,
    pub last_error: Option<String>,
    pub last_page: Option<i64>,
    pub mode: SyncMode,
}

// ---------------------------------------------------------------------------
// Episode types
// ---------------------------------------------------------------------------

/// Canonical episode data from a provider, used for sync/upsert.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CanonicalEpisode {
    pub source: SourceName,
    pub source_id: String,
    pub media_kind: MediaKind,
    pub season_number: Option<i32>,
    pub episode_number: Option<i32>,
    pub absolute_number: Option<i32>,
    pub title_display: Option<String>,
    pub title_original: Option<String>,
    pub synopsis: Option<String>,
    pub air_date: Option<String>,
    pub runtime_minutes: Option<i32>,
    pub thumbnail_url: Option<String>,
    pub raw_titles_json: Option<Value>,
    pub raw_json: Option<Value>,
}

/// Canonical episode data persisted in SQLite.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StoredEpisode {
    pub id: i64,
    pub media_id: i64,
    pub season_number: Option<i32>,
    pub episode_number: Option<i32>,
    pub absolute_number: Option<i32>,
    pub title_display: Option<String>,
    pub title_original: Option<String>,
    pub titles_json: Option<Value>,
    pub synopsis: Option<String>,
    pub air_date: Option<String>,
    pub runtime_minutes: Option<i32>,
    pub thumbnail_url: Option<String>,
}

/// Episode record as received from a specific provider (raw/normalized).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EpisodeSourceRecord {
    pub id: i64,
    pub episode_id: Option<i64>,
    pub source: SourceName,
    pub source_id: String,
    pub media_id: i64,
    pub media_kind: MediaKind,
    pub season_number: Option<i32>,
    pub episode_number: Option<i32>,
    pub absolute_number: Option<i32>,
    pub title_display: Option<String>,
    pub title_original: Option<String>,
    pub titles_json: Option<Value>,
    pub synopsis: Option<String>,
    pub air_date: Option<String>,
    pub runtime_minutes: Option<i32>,
    pub thumbnail_url: Option<String>,
    pub raw_json: Option<Value>,
    pub fetched_at: String,
}

/// A media record paired with its enriched episode list.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MediaDocument {
    pub media: StoredMedia,
    pub episodes: Vec<StoredEpisode>,
}