ontv 0.0.1

A rich desktop application for tracking tv shows
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
mod etag;
mod hex;
mod raw;

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::str::FromStr;

use anyhow::{anyhow, bail, ensure, Context, Result};
use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub(crate) use self::etag::Etag;
pub(crate) use self::hex::Hex;
pub(crate) use self::raw::Raw;

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[repr(transparent)]
#[serde(transparent)]
pub(crate) struct SeriesId(Uuid);

impl SeriesId {
    /// Generate a new random series identifier.
    #[inline]
    pub(crate) fn random() -> Self {
        Self(Uuid::new_v4())
    }
}

impl fmt::Display for SeriesId {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl FromStr for SeriesId {
    type Err = uuid::Error;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(uuid::Uuid::from_str(s)?))
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[repr(transparent)]
#[serde(transparent)]
pub(crate) struct EpisodeId(Uuid);

impl EpisodeId {
    /// Generate a new random episode identifier.
    #[inline]
    pub(crate) fn random() -> Self {
        Self(Uuid::new_v4())
    }
}

impl fmt::Display for EpisodeId {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl FromStr for EpisodeId {
    type Err = uuid::Error;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(uuid::Uuid::from_str(s)?))
    }
}

#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum ThemeType {
    Light,
    #[default]
    Dark,
}

#[inline]
fn default_days() -> u64 {
    7
}

/// The state for the settings page.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Config {
    #[serde(default)]
    pub(crate) theme: ThemeType,
    #[serde(default)]
    pub(crate) tvdb_legacy_apikey: String,
    #[serde(default)]
    pub(crate) tmdb_api_key: String,
    #[serde(default = "default_days")]
    pub(crate) schedule_duration_days: u64,
}

impl Default for Config {
    #[inline]
    fn default() -> Self {
        Self {
            theme: Default::default(),
            tvdb_legacy_apikey: Default::default(),
            tmdb_api_key: Default::default(),
            schedule_duration_days: default_days(),
        }
    }
}

impl Config {
    /// Build iced theme.
    #[inline]
    pub(crate) fn theme(&self) -> iced::Theme {
        match self.theme {
            ThemeType::Light => iced::Theme::Light,
            ThemeType::Dark => iced::Theme::Dark,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "type")]
pub(crate) enum RemoteId {
    Series {
        uuid: SeriesId,
        remotes: BTreeSet<RemoteSeriesId>,
    },
    Episode {
        uuid: EpisodeId,
        remotes: BTreeSet<RemoteEpisodeId>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "remote")]
pub(crate) enum RemoteSeriesId {
    Tvdb { id: u32 },
    Tmdb { id: u32 },
    Imdb { id: Raw<16> },
}

impl RemoteSeriesId {
    pub(crate) fn url(&self) -> String {
        match self {
            RemoteSeriesId::Tvdb { id } => {
                format!("https://thetvdb.com/search?query={id}")
            }
            RemoteSeriesId::Tmdb { id } => {
                format!("https://www.themoviedb.org/tv/{id}")
            }
            RemoteSeriesId::Imdb { id } => {
                format!("https://www.imdb.com/title/{id}/")
            }
        }
    }
}

impl fmt::Display for RemoteSeriesId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RemoteSeriesId::Tvdb { id } => {
                write!(f, "thetvdb.com ({id})")
            }
            RemoteSeriesId::Tmdb { id } => {
                write!(f, "themoviedb.org ({id})")
            }
            RemoteSeriesId::Imdb { id } => {
                write!(f, "imdb.com ({id})")
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "remote")]
pub(crate) enum RemoteEpisodeId {
    Tvdb { id: u32 },
    Tmdb { id: u32 },
    Imdb { id: Raw<16> },
}

/// A series.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) struct Series {
    /// Allocated UUID.
    pub(crate) id: SeriesId,
    /// Title of the series.
    pub(crate) title: String,
    /// First air date of the series.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) first_air_date: Option<NaiveDate>,
    /// Overview of the series.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) overview: Option<String>,
    /// Poster image.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) poster: Option<Image>,
    /// Banner image.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) banner: Option<Image>,
    /// Fanart image.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) fanart: Option<Image>,
    /// Indicates if the series is tracked or not, in that it will receive updates.
    #[serde(default, skip_serializing_if = "is_false")]
    pub(crate) tracked: bool,
    /// Locally known last modified timestamp.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) last_modified: Option<DateTime<Utc>>,
    /// Locally known last etag.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) last_etag: Option<Etag>,
    /// Last sync time for each remote.
    #[serde(
        default,
        skip_serializing_if = "BTreeMap::is_empty",
        with = "btree_as_vec"
    )]
    pub(crate) last_sync: BTreeMap<RemoteSeriesId, DateTime<Utc>>,
    /// The remote identifier that is used to synchronize this series.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) remote_id: Option<RemoteSeriesId>,
    /// Remote series ids.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) remote_ids: Vec<RemoteSeriesId>,
}

#[inline]
fn is_false(b: &bool) -> bool {
    !*b
}

mod btree_as_vec {
    use std::collections::BTreeMap;
    use std::fmt;

    use serde::de;
    use serde::ser;
    use serde::ser::SerializeSeq;

    pub(crate) fn serialize<S, K, V>(
        value: &BTreeMap<K, V>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: ser::Serializer,
        K: ser::Serialize,
        V: ser::Serialize,
    {
        let mut serializer = serializer.serialize_seq(Some(value.len()))?;

        for (key, value) in value {
            serializer.serialize_element(&(key, value))?;
        }

        serializer.end()
    }

    pub(crate) fn deserialize<'de, S, K, V>(deserializer: S) -> Result<BTreeMap<K, V>, S::Error>
    where
        S: de::Deserializer<'de>,
        K: Ord + de::Deserialize<'de>,
        V: de::Deserialize<'de>,
    {
        return deserializer.deserialize_seq(Visitor(BTreeMap::new()));
    }

    impl<'de, K, V> de::Visitor<'de> for Visitor<K, V>
    where
        K: Ord + de::Deserialize<'de>,
        V: de::Deserialize<'de>,
    {
        type Value = BTreeMap<K, V>;

        #[inline]
        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "expected sequence")
        }

        #[inline]
        fn visit_seq<A>(mut self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: de::SeqAccess<'de>,
        {
            while let Some(element) = seq.next_element::<(K, V)>()? {
                self.0.insert(element.0, element.1);
            }

            Ok(self.0)
        }
    }

    struct Visitor<K, V>(BTreeMap<K, V>);
}

/// A season in a series.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) struct Watched {
    /// Unique identifier for this watch.
    pub(crate) id: Uuid,
    /// Identifier of watched series.
    pub(crate) series: SeriesId,
    /// Identifier of watched episode.
    pub(crate) episode: EpisodeId,
    /// Timestamp when it was watched.
    pub(crate) timestamp: DateTime<Utc>,
}

/// Season number.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(untagged)]
pub(crate) enum SeasonNumber {
    /// Season used for non-numbered episodes.
    #[default]
    Specials,
    /// A regular numbered season.
    Number(u32),
}

impl SeasonNumber {
    #[inline]
    fn is_special(&self) -> bool {
        matches!(self, SeasonNumber::Specials)
    }

    /// Build season title.
    pub(crate) fn short(&self) -> SeasonShort<'_> {
        SeasonShort { season: self }
    }
}

pub(crate) struct SeasonShort<'a> {
    season: &'a SeasonNumber,
}

impl fmt::Display for SeasonShort<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.season {
            SeasonNumber::Specials => "S".fmt(f),
            SeasonNumber::Number(n) => n.fmt(f),
        }
    }
}

impl fmt::Display for SeasonNumber {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SeasonNumber::Specials => write!(f, "Specials"),
            SeasonNumber::Number(number) => write!(f, "Season {number}"),
        }
    }
}

/// A season in a series.
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) struct Season {
    /// The number of the season.
    #[serde(default, skip_serializing_if = "SeasonNumber::is_special")]
    pub(crate) number: SeasonNumber,
    #[serde(default)]
    pub(crate) air_date: Option<NaiveDate>,
    #[serde(default)]
    pub(crate) name: Option<String>,
    #[serde(default)]
    pub(crate) overview: Option<String>,
    #[serde(default)]
    pub(crate) poster: Option<Image>,
}

/// An episode in a series.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) struct Episode {
    /// Uuid of the watched episode.
    pub(crate) id: EpisodeId,
    /// Name of the episode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) name: Option<String>,
    /// Overview of the episode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) overview: Option<String>,
    /// Absolute number in the series.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) absolute_number: Option<u32>,
    /// Season number.
    #[serde(default)]
    pub(crate) season: SeasonNumber,
    /// Episode number inside of its season.
    pub(crate) number: u32,
    /// Air date of the episode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) aired: Option<NaiveDate>,
    /// Episode image.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) filename: Option<Image>,
    /// The remote identifier that is used to synchronize this episode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) remote_id: Option<RemoteEpisodeId>,
    /// Remote episode ids.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub(crate) remote_ids: BTreeSet<RemoteEpisodeId>,
}

impl Episode {
    /// Test if the given episode has aired by the provided timestamp.
    pub(crate) fn has_aired(&self, now: &DateTime<Utc>) -> bool {
        let Some(aired) = &self.aired else {
            return false;
        };

        *aired <= now.date_naive()
    }
}

impl fmt::Display for Episode {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} / {}", self.season, self.number)
    }
}

/// Image format in use.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum ImageExt {
    Jpg,
}

impl ImageExt {
    /// Parse a banner URL.
    fn parse(input: &str) -> Result<Self> {
        match input {
            "jpg" => Ok(ImageExt::Jpg),
            _ => {
                bail!("unsupported image format")
            }
        }
    }
}

impl fmt::Display for ImageExt {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ImageExt::Jpg => write!(f, "jpg"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum ArtKind {
    /// Poster art.
    Posters,
    /// Banner art.
    Banners,
    /// Background art.
    Backgrounds,
    /// Episodes art.
    Episodes,
}

impl ArtKind {
    fn parse(input: &str) -> Result<Self> {
        match input {
            "posters" => Ok(ArtKind::Posters),
            "banners" => Ok(ArtKind::Banners),
            "backgrounds" => Ok(ArtKind::Backgrounds),
            "episodes" => Ok(ArtKind::Episodes),
            _ => {
                bail!("unsupported art kind")
            }
        }
    }
}

impl fmt::Display for ArtKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ArtKind::Posters => write!(f, "posters"),
            ArtKind::Banners => write!(f, "banners"),
            ArtKind::Backgrounds => write!(f, "backgrounds"),
            ArtKind::Episodes => write!(f, "episodes"),
        }
    }
}

/// The identifier of an image.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", tag = "type", content = "data")]
pub(crate) enum TvdbImageKind {
    Legacy(u64, ArtKind, Hex<16>),
    V4(u64, ArtKind, Hex<16>),
    Banner(Hex<16>),
    BannerSuffixed(u64, Raw<16>),
    Graphical(Hex<16>),
    GraphicalSuffixed(u64, Raw<16>),
    Fanart(Hex<16>),
    FanartSuffixed(u64, Raw<16>),
    ScreenCap(u64, Hex<16>),
    Episodes(u32, u32),
    Blank(u32),
    Missing,
}

/// An image from thetvdb.com.org
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) struct TvdbImage {
    #[serde(flatten)]
    pub(crate) kind: TvdbImageKind,
    pub(crate) ext: ImageExt,
}

impl fmt::Display for TvdbImage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ext = &self.ext;

        match &self.kind {
            TvdbImageKind::Legacy(series_id, kind, id) => {
                write!(f, "/banners/series/{series_id}/{kind}/{id}.{ext}")
            }
            TvdbImageKind::V4(series_id, kind, id) => {
                write!(f, "/banners/v4/series/{series_id}/{kind}/{id}.{ext}")
            }
            TvdbImageKind::Banner(id) => {
                write!(f, "/banners/posters/{id}.{ext}")
            }
            TvdbImageKind::BannerSuffixed(series_id, suffix) => {
                write!(f, "/banners/posters/{series_id}-{suffix}.{ext}")
            }
            TvdbImageKind::Graphical(id) => {
                write!(f, "/banners/graphical/{id}.{ext}")
            }
            TvdbImageKind::GraphicalSuffixed(series_id, suffix) => {
                write!(f, "/banners/graphical/{series_id}-{suffix}.{ext}")
            }
            TvdbImageKind::Fanart(id) => {
                write!(f, "/banners/fanart/original/{id}.{ext}")
            }
            TvdbImageKind::FanartSuffixed(series_id, suffix) => {
                write!(f, "/banners/fanart/original/{series_id}-{suffix}.{ext}")
            }
            TvdbImageKind::ScreenCap(episode_id, id) => {
                write!(f, "/banners/v4/episode/{episode_id}/screencap/{id}.{ext}")
            }
            TvdbImageKind::Episodes(episode_id, image_id) => {
                write!(f, "/banners/episodes/{episode_id}/{image_id}.{ext}")
            }
            TvdbImageKind::Blank(series_id) => {
                write!(f, "/banners/blank/{series_id}.{ext}")
            }
            TvdbImageKind::Missing => {
                write!(f, "/banners/images/missing/series.{ext}")
            }
        }
    }
}

/// The identifier of an image.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", tag = "type", content = "data")]
pub(crate) enum TmdbImageKind {
    Base64(Raw<32>),
}

/// An image from themoviedb.org
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) struct TmdbImage {
    #[serde(flatten)]
    pub(crate) kind: TmdbImageKind,
    pub(crate) ext: ImageExt,
}

impl fmt::Display for TmdbImage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ext = &self.ext;

        match self.kind {
            TmdbImageKind::Base64(id) => {
                write!(f, "/t/p/original/{id}.{ext}")?;
            }
        }

        Ok(())
    }
}

/// The identifier of an image.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", tag = "from")]
pub(crate) enum Image {
    /// An image from thetvdb.com
    Tvdb(TvdbImage),
    /// An image from themoviedb.org
    Tmdb(TmdbImage),
}

impl Image {
    /// Parse an image URL from thetvdb.
    pub(crate) fn parse_tvdb(mut input: &str) -> Result<Self> {
        input = input.trim_start_matches('/');

        let mut it = input.split('/');

        ensure!(
            matches!(it.next(), Some("banners")),
            "{input}: missing `banners`"
        );

        Self::parse_banner_it(it).with_context(|| anyhow!("bad image: {input}"))
    }

    /// Parse without expecting a `banners` prefix.
    #[inline]
    pub(crate) fn parse_tvdb_banner(input: &str) -> Result<Self> {
        Self::parse_banner_it(input.split('/')).with_context(|| anyhow!("bad image: {input}"))
    }

    #[inline]
    pub(crate) fn parse_tmdb(input: &str) -> Result<Self> {
        let input = input.trim_start_matches('/');

        let Some((id, ext)) = input.split_once('.') else {
            bail!("missing extension");
        };

        let id = Raw::new(id).context("base identifier")?;
        let kind = TmdbImageKind::Base64(id);
        let ext = ImageExt::parse(ext)?;
        Ok(Image::Tmdb(TmdbImage { kind, ext }))
    }

    fn parse_banner_it<'a, I>(mut it: I) -> Result<Self>
    where
        I: DoubleEndedIterator<Item = &'a str>,
    {
        use arrayvec::ArrayVec;

        let rest = it.next_back().context("missing last component")?;

        let Some((rest, ext)) = rest.split_once('.') else {
            bail!("missing extension");
        };

        let ext = ImageExt::parse(ext)?;

        let mut array = ArrayVec::<_, 6>::new();

        for part in it {
            array.try_push(part).map_err(|e| anyhow!("{e}"))?;
        }

        array.try_push(rest).map_err(|e| anyhow!("{e}"))?;

        let kind = match &array[..] {
            // blank/77092.jpg
            ["blank", series_id] => TvdbImageKind::Blank(series_id.parse()?),
            // images/missing/series.jpg
            ["images", "missing", "series"] => TvdbImageKind::Missing,
            ["v4", "series", series_id, kind, rest] => {
                let kind = ArtKind::parse(kind)?;
                let id = Hex::from_hex(rest).context("bad id")?;
                TvdbImageKind::V4(series_id.parse()?, kind, id)
            }
            ["series", series_id, kind, id] => {
                let series_id = series_id.parse()?;
                let kind = ArtKind::parse(kind)?;
                let id = Hex::from_hex(id).context("bad id")?;
                TvdbImageKind::Legacy(series_id, kind, id)
            }
            ["posters", rest] => {
                if let Some((series_id, suffix)) = rest.split_once('-') {
                    let series_id = series_id.parse()?;
                    let suffix = Raw::new(suffix).context("suffix overflow")?;
                    TvdbImageKind::BannerSuffixed(series_id, suffix)
                } else {
                    let id = Hex::from_hex(rest).context("bad id")?;
                    TvdbImageKind::Banner(id)
                }
            }
            ["graphical", rest] => {
                if let Some((series_id, suffix)) = rest.split_once('-') {
                    let series_id = series_id.parse()?;
                    let suffix = Raw::new(suffix).context("suffix overflow")?;
                    TvdbImageKind::GraphicalSuffixed(series_id, suffix)
                } else {
                    let id = Hex::from_hex(rest).context("bad hex")?;
                    TvdbImageKind::Graphical(id)
                }
            }
            ["fanart", "original", rest] => {
                if let Some((series_id, suffix)) = rest.split_once('-') {
                    let series_id = series_id.parse()?;
                    let suffix = Raw::new(suffix).context("suffix overflow")?;
                    TvdbImageKind::FanartSuffixed(series_id, suffix)
                } else {
                    let id = Hex::from_hex(rest).context("bad hex")?;
                    TvdbImageKind::Fanart(id)
                }
            }
            // Example: v4/episode/8538342/screencap/63887bf74c84e.jpg
            ["v4", "episode", episode_id, "screencap", rest] => {
                let id = Hex::from_hex(rest).context("bad id")?;
                TvdbImageKind::ScreenCap(episode_id.parse()?, id)
            }
            ["episodes", episode_id, rest] => {
                TvdbImageKind::Episodes(episode_id.parse()?, rest.parse()?)
            }
            _ => {
                bail!("unsupported image");
            }
        };

        Ok(Image::Tvdb(TvdbImage { kind, ext }))
    }
}

impl fmt::Display for Image {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Image::Tvdb(image) => write!(f, "tvdb:{image}"),
            Image::Tmdb(image) => write!(f, "tmdb:{image}"),
        }
    }
}

impl From<TvdbImage> for Image {
    #[inline]
    fn from(image: TvdbImage) -> Self {
        Image::Tvdb(image)
    }
}

impl From<TmdbImage> for Image {
    #[inline]
    fn from(image: TmdbImage) -> Self {
        Image::Tmdb(image)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub(crate) enum TaskKind {
    /// Find updates.
    FindUpdates,
    /// Task to download series data.
    DownloadSeriesById { series_id: SeriesId },
    /// Task to add a series by a remote identifier.
    DownloadSeriesByRemoteId { remote_id: RemoteSeriesId },
}

/// Actions that can be performed after a task has completed.
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "kebab-case")]
pub(crate) enum TaskFinished {
    /// Do nothing.
    #[default]
    None,
    /// Update series.
    UpdateSeries {
        /// Series to update.
        series_id: SeriesId,
        /// Update etag.
        last_etag: Option<Etag>,
        /// Update last modified date.
        last_modifed: Option<DateTime<Utc>>,
    },
}

impl TaskFinished {
    fn is_none(&self) -> bool {
        matches!(self, TaskFinished::None)
    }
}

/// A task in a queue.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Task {
    /// The identifier of the task.
    pub(crate) id: Uuid,
    /// The kind of the task.
    #[serde(flatten)]
    pub(crate) kind: TaskKind,
    /// When the task is scheduled for.
    pub(crate) scheduled: DateTime<Utc>,
    /// Task finished actions.
    #[serde(default, skip_serializing_if = "TaskFinished::is_none")]
    pub(crate) finished: TaskFinished,
}

impl Task {
    /// Test if task involves the given series.
    pub(crate) fn is_series(&self, id: &SeriesId) -> bool {
        match &self.kind {
            TaskKind::DownloadSeriesById { series_id, .. } => *series_id == *id,
            TaskKind::DownloadSeriesByRemoteId { .. } => false,
            TaskKind::FindUpdates => false,
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct SearchSeries {
    pub(crate) id: RemoteSeriesId,
    pub(crate) name: String,
    pub(crate) poster: Option<Image>,
    pub(crate) overview: Option<String>,
    pub(crate) first_aired: Option<NaiveDate>,
}

/// A series that is scheduled to be aired.
pub(crate) struct ScheduledSeries {
    pub(crate) series_id: SeriesId,
    pub(crate) episodes: Vec<EpisodeId>,
}

/// A scheduled day.
pub(crate) struct ScheduledDay {
    pub(crate) date: NaiveDate,
    pub(crate) schedule: Vec<ScheduledSeries>,
}