xmltv 2.1.0

XMLTV for electronic program guide (EPG) parser and generator 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
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use utils::*;

pub mod utils;

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, Default)]
pub struct NameAndLang {
    #[serde(rename = "$text", skip_serializing_if = "String::is_empty")]
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none", rename = "@lang")]
    pub lang: Option<String>,
}

#[derive(Debug, PartialEq, Clone, Serialize, Default)]
pub struct ValueAndLang {
    #[serde(rename = "$text", skip_serializing_if = "String::is_empty")]
    pub value: String,
    #[serde(skip_serializing_if = "Option::is_none", rename = "@lang")]
    pub lang: Option<String>,
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct EmptyTag {}

/// Date should be the date when the listings were originally produced in whatever format; if you're converting data from another source, then
/// use the date given by that source.  The date when the conversion itself was done is not important.
///
/// To publicize your wonderful program which generated this file, you can use `generator-info-name` (preferably in the form 'progname/version')
/// and `generator-info-url` (a link to more info about the program).
///
/// ```dtd
/// <!ELEMENT tv (channel*, programme*)>
/// <!ATTLIST tv date   CDATA #IMPLIED
/// source-info-url     CDATA #IMPLIED
/// source-info-name    CDATA #IMPLIED
/// source-data-url     CDATA #IMPLIED
/// generator-info-name CDATA #IMPLIED
/// generator-info-url  CDATA #IMPLIED >
/// ```
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, Default)]
pub struct Tv {
    /// `source-info-url` is a URL describing the data source in some human-readable form.  So if you are getting your listings from
    /// SAT.1, you might set this to the URL of a page explaining how to subscribe to their feed.  If you are getting them from a website, the
    /// URL might be the index of the site or at least of the TV listings section.
    #[serde(skip_serializing_if = "Option::is_none", rename = "@source-info-url")]
    pub source_info_url: Option<String>,
    /// `source-info-name` is the link text for that URL; it should generally be the human-readable name of your listings supplier.
    /// Sometimes the link text might be printed without the link itself, in hardcopy listings for example.
    #[serde(skip_serializing_if = "Option::is_none", rename = "@source-info-name")]
    pub source_info_name: Option<String>,
    /// `source-data-url' is where the actual data is grabbed from.  This should link directly to the machine-readable data files if possible,
    /// but it's not rigorously defined what 'actual data' means.  If you are parsing the data from human-readable pages, then it's more appropriate
    /// to link to them with the source-info stuff and omit this attribute.
    #[serde(skip_serializing_if = "Option::is_none", rename = "@source-data-url")]
    pub source_data_url: Option<String>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "@generator-info-name"
    )]
    pub generator_info_name: Option<String>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "@generator-info-url"
    )]
    pub generator_info_url: Option<String>,
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "channel"
    )]
    pub channels: Vec<Channel>,
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "programme"
    )]
    pub programmes: Vec<Programme>,
}

impl Tv {
    /// Find all programmes by a channel ID
    pub fn find_by_channel(&self, channel_id: &str) -> Vec<&Programme> {
        self.programmes
            .iter()
            .filter(|p| p.channel == channel_id)
            .collect()
    }

    /// Get a channel by its ID
    pub fn get_channel(&self, channel_id: &str) -> Option<&Channel> {
        self.channels.iter().find(|c| c.id == channel_id)
    }

    /// Sort programmes by start date (important for RSS/Atom feeds)
    pub fn sort_programmes_by_date(&mut self) {
        self.programmes.sort_by(|a, b| a.start.cmp(&b.start));
    }
}

/// Structure representing a XMLTV channel.
/// Each 'programme' element (see below) should have an attribute 'channel' giving the channel on which it is broadcast.  If you want to
/// provide more detail about channels, you can give some 'channel' elements before listing the programmes.  The 'id' attribute of the
/// channel should match what is given in the 'channel' attribute of the programme.
///
/// Typically, all the channels used in a particular TV listing will be included and then the programmes using those channels.  But it's
/// entirely optional to include channel details - you can just leave out channel elements or provide only some of them.  It is also okay to
/// give just channels and no programmes, if you just want to describe what TV channels are available in a certain area.
///
// Each channel has one id attribute, which must be unique and should preferably be in the form suggested by RFC2838 (the 'broadcast'
/// element of the grammar in that RFC, in other words, a DNS-like name but without any URI scheme).  Then one or more display names which are
/// shown to the user.  You might want a different display name for different languages, but also you can have more than one name for the
/// same language.  Names listed earlier are considered 'more canonical'.
///
/// Since the display name is just there as a way for humans to refer to the channel, it's acceptable to just put the channel number if it's
/// fairly universal among viewers of the channel.  But remember that this isn't an official statement of what channel number has been
/// allocated, and the same number might be used for a different channel somewhere else.
///
/// The ordering of channel elements makes no difference to the meaning of the file, since they are looked up by id and not by their position.
/// However it makes things like diffing easier if you write the channel elements sorted by ASCII order of their ids.
///
/// ```dtd
/// <!ELEMENT channel (display-name+, icon*, url*) >
/// <!ATTLIST channel id CDATA #REQUIRED >
/// ```
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, Default)]
pub struct Channel {
    #[serde(rename = "@id")]
    pub id: String,
    /// A user-friendly name for the channel - maybe even a channel number.  List the most canonical / common ones first and the most
    /// obscure names last.  The lang attribute follows RFC 1766.
    ///
    /// ```dtd
    /// <!ELEMENT display-name (#PCDATA)>
    /// <!ATTLIST display-name lang CDATA #IMPLIED>
    /// ```
    #[serde(
        rename = "display-name",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub display_names: Vec<NameAndLang>,
    #[serde(
        rename = "icon",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub icons: Vec<Icon>,
    #[serde(
        rename = "url",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub urls: Vec<Url>,
}

/// A URL where you can find out more about the element that contains it (programme or channel).  This might be the official site, or a fan
/// page, whatever you like really.
///
/// If multiple url elements are given, the most authoritative or official (which might conflict...) sites should be listed first.
///
/// If the URL does not define a real (i.e. clickable) link then the scheme should be set to something other than 'http://' such as 'uri://'
///
/// ```dtd
/// <!ELEMENT url (#PCDATA)>
/// <!ATTLIST url system CDATA #IMPLIED>
/// ```
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, Default)]
pub struct Url {
    #[serde(rename = "$text")]
    pub value: String,
    /// The system attribute may be used to identify the source or target of the url, or some other useful feature of the target.
    #[serde(skip_serializing_if = "Option::is_none", rename = "@system")]
    pub system: Option<String>,
}

/// Structure representing a XMLTV program element:
///
/// ```dtd
/// <!ELEMENT programme (title+, sub-title*, desc*, credits?, date?,
///                      category*, keyword*, language?, orig-language?,
///                      length?, icon*, url*, country*, episode-num*,
///                      video?, audio?, previously-shown?, premiere?,
///                      last-chance?, new?, subtitles*, rating*,
///                      star-rating*, review*, image* )>
/// <!ATTLIST programme start     CDATA #REQUIRED
///                     stop      CDATA #IMPLIED
///                     pdc-start CDATA #IMPLIED
///                     vps-start CDATA #IMPLIED
///                     showview  CDATA #IMPLIED
///                     videoplus CDATA #IMPLIED
///                     channel   CDATA #REQUIRED
///                     clumpidx  CDATA "0/1" >
/// ```
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, Default)]
pub struct Programme {
    // Attributes
    #[serde(rename = "@channel")]
    pub channel: String,
    #[serde(rename = "@start")]
    pub start: String,
    #[serde(skip_serializing_if = "Option::is_none", rename = "@stop")]
    pub stop: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "@pdc-start")]
    pub pdc_start: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "@vps-start")]
    pub vps_start: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub showview: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub videoplus: Option<String>,
    /// TV listings sometimes have the problem of listing two or more
    /// programmes in the same timeslot, such as 'News; Weather'.  We call
    /// this a 'clump' of programmes, and the 'clumpidx' attribute
    /// differentiates between two programmes sharing the same timeslot and
    /// channel.  In this case News would have clumpidx="0/2" and Weather
    /// would have clumpidx="1/2".  If you don't have this problem, be thankful!
    #[serde(skip_serializing_if = "Option::is_none")]
    pub clumpidx: Option<String>,
    // Children
    /// Structure representing a XMLTV title: Programme title, eg 'The Simpsons'.
    ///
    /// ```dtd
    /// <!ELEMENT title (#PCDATA)>
    /// <!ATTLIST title lang CDATA #IMPLIED>
    /// ```
    #[serde(
        rename = "title",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub titles: Vec<ValueAndLang>,
    /// Structure representing a XMLTV sub title: Sub-title or episode title, eg 'Datalore'. Should probably be
    /// called 'secondary title' to avoid confusion with captioning!
    ///
    /// ```dtd
    /// <!ELEMENT sub-title (#PCDATA)>
    /// <!ATTLIST sub-title lang CDATA #IMPLIED>
    /// ```
    #[serde(
        rename = "sub-title",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub sub_titles: Vec<ValueAndLang>,
    /// Structure representing a XMLTV description of the programme or episode.
    ///
    /// Unlike other elements, long bits of whitespace here are treated as equivalent to a single space and newlines are permitted, so you can
    /// break lines and write a pretty-looking paragraph if you wish.
    ///
    /// ```dtd
    /// <!ELEMENT desc (#PCDATA)>
    /// <!ATTLIST desc lang CDATA #IMPLIED>
    /// ```
    #[serde(
        rename = "desc",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub descriptions: Vec<ValueAndLang>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credits: Option<Credits>,
    /// `<!ELEMENT date (#PCDATA)>`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date: Option<String>,
    /// XMLTV Program category. Type of programme, eg 'soap', 'comedy' or whatever the
    /// equivalents are in your language.  There's no predefined set of categories and it's okay for a programme to belong to several.
    ///
    /// ```dtd
    /// <!ELEMENT category (#PCDATA)>
    /// <!ATTLIST category lang CDATA #IMPLIED>
    /// ```
    #[serde(
        rename = "category",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub categories: Vec<NameAndLang>,
    /// Keywords for the programme, eg 'prison-drama', 'based-on-novel', 'super-hero'.  There's no predefined set of keywords and it's likely
    /// for a programme to have several.  It is recommended that keywords containing multiple words are hyphenated.
    ///
    /// ```dtd
    /// <!ELEMENT keyword (#PCDATA)>
    /// <!ATTLIST keyword lang CDATA #IMPLIED>
    /// ```
    #[serde(
        rename = "keyword",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub keywords: Vec<ValueAndLang>,
    /// The language the programme will be broadcast in.  This does not include the language of any subtitles, but it is affected by dubbing
    /// into a different language.  For example, if a French film is dubbed into English, language=en and orig-language=fr.
    ///
    /// There are two ways to specify the language.  You can use the two-letter codes such as en or fr, or you can give a name such as
    /// 'English' or 'Deutsch'.  In the latter case you might want to use the 'lang' attribute, for example: `<language lang="fr">Allemand</language>`.
    ///
    /// ```dtd
    /// <!ELEMENT language (#PCDATA)>
    /// <!ATTLIST language lang CDATA #IMPLIED>
    /// ```
    #[serde(rename = "language", skip_serializing_if = "Option::is_none")]
    pub language: Option<ValueAndLang>,
    /// The original language, before dubbing.  The same remarks as for 'language' apply.
    ///
    /// ```dtd
    /// <!ELEMENT orig-language (#PCDATA)>
    /// <!ATTLIST orig-language lang CDATA #IMPLIED>
    /// ```
    #[serde(rename = "orig-language", skip_serializing_if = "Option::is_none")]
    pub orig_language: Option<ValueAndLang>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub length: Option<Length>,
    #[serde(
        rename = "icon",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub icons: Vec<Icon>,
    #[serde(
        rename = "url",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub urls: Vec<Url>,
    /// A country where the programme was made or one of the countries in a joint production.  You can give the name of a country, in which case
    /// you might want to specify the language in which this name is written, or you can give a two-letter uppercase country code, in which case the
    /// lang attribute should not be given.  For example: `<country lang="en">Italy</country><country>GB</country>`
    ///
    /// ```dtd
    /// <!ELEMENT country (#PCDATA)>
    /// <!ATTLIST country lang CDATA #IMPLIED>
    /// ```
    #[serde(
        rename = "country",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub countries: Vec<NameAndLang>,
    #[serde(
        rename = "episode-num",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub episode_num: Vec<EpisodeNum>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub video: Option<Video>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio: Option<Audio>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "previously-shown")]
    pub previously_shown: Option<PreviouslyShown>,
    /// Different channels have different meanings for this word - sometimes it means a film has never before been seen on TV in
    /// that country, but other channels use it to mean 'the first showing of this film on our channel in the current run'.  It might have been
    /// shown before, but now they have paid for another set of showings, which makes the first in that set count as a premiere!
    ///
    /// So this element doesn't have a clear meaning, just use it to represent where 'premiere' would appear in a printed TV listing.  You can use
    /// the content of the element to explain exactly what is meant, for example:
    /// ```xml
    /// <premiere lang="en">
    ///   First showing on national terrestrial TV
    /// </premiere>
    /// ```
    ///
    /// The textual content is a 'paragraph' as for <desc>.  If you don't want to give an explanation, just write empty content: `<premiere />`
    ///
    /// ```dtd
    /// <!ELEMENT premiere (#PCDATA)>
    /// <!ATTLIST premiere lang CDATA #IMPLIED>
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub premiere: Option<ValueAndLang>,
    /// In a way this is the opposite of premiere.  Some channels buy the rights to show a movie a certain number of times, and
    /// the first may be flagged 'premiere', the last as 'last showing'.
    ///
    /// For symmetry with premiere, you may use the element content to give a 'paragraph' describing exactly what is meant - it's unlikely to be the
    /// last showing ever!  Otherwise, explicitly put empty content: `<last-chance />`
    ///
    /// ```dtd
    /// <!ELEMENT last-chance (#PCDATA)>
    /// <!ATTLIST last-chance lang CDATA #IMPLIED>
    /// ```
    #[serde(rename = "last-chance", skip_serializing_if = "Option::is_none")]
    pub last_chance: Option<ValueAndLang>,
    /// This is the first screened programme from a new show that has never been shown on television before - if not worldwide then at
    /// least never before in this country.  After the first episode or programme has been shown, subsequent ones are no longer 'new'.
    /// Similarly the second series of an established programme is not 'new'.
    ///
    /// Note that this does not mean 'new season' or 'new episode' of an existing show.  You can express part of that using the episode-num stuff.
    ///
    /// `<!ELEMENT new EMPTY>`
    #[serde(
        skip_serializing_if = "std::ops::Not::not",
        serialize_with = "bool_to_new_tag",
        deserialize_with = "new_tag_to_boolean",
        default
    )]
    pub new: bool, // TODO: as boolean, default false
    #[serde(skip_serializing_if = "Vec::is_empty", default = "Vec::new")]
    pub subtitles: Vec<Subtitles>,
    #[serde(
        rename = "rating",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub ratings: Vec<Rating>,
    #[serde(
        rename = "star-rating",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub star_ratings: Vec<StarRating>,
    #[serde(
        rename = "review",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub reviews: Vec<Review>,
    #[serde(
        rename = "image",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub images: Vec<Icon>,
}

impl Programme {
    /// Parse start date as DateTime<Utc>
    pub fn start_datetime(&self) -> Result<DateTime<Utc>, chrono::ParseError> {
        // XMLTV format: "YYYYMMDDHHMMSS +HHMM"
        DateTime::parse_from_str(&self.start, "%Y%m%d%H%M%S %z").map(|dt| dt.with_timezone(&Utc))
    }

    /// If exist, parse end date
    pub fn stop_datetime(&self) -> Option<DateTime<Utc>> {
        self.stop
            .as_ref()
            .and_then(|s| DateTime::parse_from_str(s, "%Y%m%d%H%M%S %z").ok())
            .map(|dt| dt.with_timezone(&Utc))
    }

    /// Check a programme is live
    pub fn is_live(&self) -> bool {
        let now = Utc::now();
        if let (Ok(start), Some(stop)) = (self.start_datetime(), self.stop_datetime()) {
            return now >= start && now <= stop;
        }
        false
    }

    /// Get the title in the wanted language or the first available title if unspecified
    pub fn get_title(&self, lang: Option<&str>) -> Option<&str> {
        if let Some(l) = lang {
            self.titles
                .iter()
                .find(|t| t.lang.as_deref() == Some(l))
                .map(|t| t.value.as_str())
        } else {
            self.titles.first().map(|t| t.value.as_str())
        }
    }

    /// Remove heavy elements: you must provide the list of item you want to empty.
    pub fn cleanse(&mut self, items: &[String]) {
        for item in items {
            match item.as_str() {
                "credits" => self.credits = None,
                "directors" => {
                    if let Some(c) = self.credits.as_mut() {
                        c.directors.clear();
                    }
                }
                "actors" => {
                    if let Some(c) = self.credits.as_mut() {
                        c.actors.clear();
                    }
                }
                "writers" => {
                    if let Some(c) = self.credits.as_mut() {
                        c.writers.clear();
                    }
                }
                "adapters" => {
                    if let Some(c) = self.credits.as_mut() {
                        c.adapters.clear();
                    }
                }
                "producers" => {
                    if let Some(c) = self.credits.as_mut() {
                        c.producers.clear();
                    }
                }
                "composers" => {
                    if let Some(c) = self.credits.as_mut() {
                        c.composers.clear();
                    }
                }
                "editors" => {
                    if let Some(c) = self.credits.as_mut() {
                        c.editors.clear();
                    }
                }
                "presenters" => {
                    if let Some(c) = self.credits.as_mut() {
                        c.presenters.clear();
                    }
                }
                "commentators" => {
                    if let Some(c) = self.credits.as_mut() {
                        c.commentators.clear();
                    }
                }
                "guests" => {
                    if let Some(c) = self.credits.as_mut() {
                        c.guests.clear();
                    }
                }
                "images" => self.images.clear(),
                "icons" => self.icons.clear(),
                "descriptions" | "desc" => self.descriptions.clear(),
                "categories" => self.categories.clear(),
                "keywords" => self.keywords.clear(),
                "sub-titles" => self.sub_titles.clear(),
                "languages" => self.language = None,
                "origin-languages" => self.orig_language = None,
                "length" => self.length = None,
                "countries" => self.countries.clear(),
                "episode-nums" => self.episode_num.clear(),
                "video" | "videos" => self.video = None,
                "audio" | "audios" => self.audio = None,
                "previously-shown" | "previously-showns" => self.previously_shown = None,
                "premiere" | "premieres" => self.premiere = None,
                "last-chance" | "last-chances" => self.last_chance = None,
                "new" => self.new = false,
                "subtitles" => self.subtitles.clear(),
                "ratings" => self.ratings.clear(),
                "star-ratings" => self.star_ratings.clear(),
                "reviews" => self.reviews.clear(),
                "urls" => self.urls.clear(),
                "date" | "dates" => self.date = None,
                _ => {}
            }
        }
    }

    /// Generates a stable hash (u64) using FNV-1a, without any external dependencies.
    /// Useful for fast comparisons and HashMap keys.
    /// Unlike `DefaultHasher`, FNV-1a produces identical values across Rust versions and runs.
    pub fn generate_hash(&self) -> u64 {
        fn fnv1a(state: u64, bytes: &[u8]) -> u64 {
            const PRIME: u64 = 0x00000100_000001B3;
            bytes
                .iter()
                .fold(state, |h, &b| (h ^ b as u64).wrapping_mul(PRIME))
        }
        const OFFSET: u64 = 0xcbf29ce484222325;
        let title = self.titles.first().map(|t| t.value.as_str()).unwrap_or("");
        let h = fnv1a(OFFSET, self.channel.as_bytes());
        let h = fnv1a(h, b"\0");
        let h = fnv1a(h, self.start.as_bytes());
        let h = fnv1a(h, b"\0");
        fnv1a(h, title.as_bytes())
    }

    /// Return readable hash (String) for debug or logs.
    pub fn fingerprint(&self) -> String {
        format!(
            "{}-{}-{}",
            self.channel,
            self.start,
            self.titles
                .first()
                .map(|t| t.value.as_str())
                .unwrap_or("no-title")
        )
    }
}

/// XMLTV Program actor
///
/// ```dtd
/// <!ATTLIST actor role  CDATA      #IMPLIED
///                 guest (no | yes) #IMPLIED >
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Actor {
    #[serde(rename = "$text")]
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none", rename = "@role")]
    pub role: Option<String>,
    #[serde(
        rename = "@guest",
        serialize_with = "bool_to_yes_no",
        deserialize_with = "yes_no_to_bool",
        skip_serializing_if = "std::ops::Not::not",
        default
    )]
    pub guest: bool,
}

/// XMLTV Program credits of the programme.
///
/// People are listed in decreasing order of importance; so for example the starring actors appear first followed by the smaller parts.  As
/// with other parts of this file format, not mentioning a particular actor (for example) does not imply that he _didn't_ star in the film -
/// so normally you'd list only the few most important people.
///
/// Adapter can be either somebody who adapted a work for television, or somebody who did the translation from another language.  Maybe these
/// should be separate, but if so how would 'translator' fit in with the 'language' element?
///
/// URL can be, for example, a link to a webpage with more information about the actor, director, etc..
///
/// ```dtd
/// <!ELEMENT credits (director*, actor*, writer*, adapter*, producer*,
///                    composer*, editor*, presenter*, commentator*,
///                    guest* )>
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Credits {
    /// `<!ELEMENT director    (#PCDATA | image | url)* >`
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "director"
    )]
    pub directors: Vec<String>,
    /// `<!ELEMENT actor       (#PCDATA | image | url)* >`
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "actor"
    )]
    pub actors: Vec<Actor>,
    /// `<!ELEMENT writer      (#PCDATA | image | url)* >`
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "writer"
    )]
    pub writers: Vec<String>,
    /// `<!ELEMENT adapter     (#PCDATA | image | url)* >`
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "adapter"
    )]
    pub adapters: Vec<String>,
    /// `<!ELEMENT producer    (#PCDATA | image | url)* >`
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "producer"
    )]
    pub producers: Vec<String>,
    /// `<!ELEMENT composer    (#PCDATA | image | url)* >`
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "composer"
    )]
    pub composers: Vec<String>,
    /// `<!ELEMENT editor      (#PCDATA | image | url)* >`
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "editor"
    )]
    pub editors: Vec<String>,
    /// `<!ELEMENT presenter   (#PCDATA | image | url)* >`
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "presenter"
    )]
    pub presenters: Vec<String>,
    /// `<!ELEMENT commentator (#PCDATA | image | url)* >`
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "commentator"
    )]
    pub commentators: Vec<String>,
    /// `<!ELEMENT guest       (#PCDATA | image | url)* >`
    #[serde(
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new",
        rename = "guest"
    )]
    pub guests: Vec<String>,
}

/// ```dtd
/// <!ELEMENT episode-num (#PCDATA)>
/// <!ATTLIST episode-num system CDATA "onscreen">
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EpisodeNum {
    #[serde(rename = "$text")]
    pub value: String,
    /// The system attribute may be used to identify the source or target of the url, or some other useful feature of the target.
    #[serde(rename = "@system")]
    pub system: String,
}

/// Video details: the subelements describe the picture quality as follows.
///
/// ```dtd
/// <!ELEMENT video (present?, colour?, aspect?, quality?)>
/// <!ELEMENT present (#PCDATA)>
/// <!ELEMENT colour (#PCDATA)>
/// <!ELEMENT aspect (#PCDATA)>
/// <!ELEMENT quality (#PCDATA)>
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Video {
    /// Whether this programme has a picture (no, in the case of radio stations broadcast on TV or 'Blue'), legal values are
    /// 'yes' or 'no'.  Obviously if the value is 'no', the other elements are meaningless.
    pub present: Option<TagWithOnlyText>, // TODO: flatten & parse
    /// 'yes' for colour, 'no' for black-and-white.
    pub colour: Option<TagWithOnlyText>, // TODO: flatten & parse
    /// The horizontal:vertical aspect ratio, eg `4:3` or `16:9`.
    pub aspect: Option<TagWithOnlyText>,
    /// Information on the quality, eg `HDTV`, `800x600`.
    pub quality: Option<TagWithOnlyText>,
}

/// Contains only the value in a tag: `<tag>value</tag>`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct TagWithOnlyText {
    #[serde(rename = "$text")]
    pub value: String,
}

/// Audio details, similar to video details above.
///
/// ```dtd
/// <!ELEMENT audio (present?, stereo?)>
/// <!ELEMENT stereo (#PCDATA)>
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Audio {
    /// Whether this programme has any sound at all, 'yes' or 'no'.
    #[serde(rename = "@present", skip_serializing_if = "Option::is_none")]
    pub present: Option<bool>,
    /// Description of the stereo-ness of the sound.  Legal values are currently 'mono','stereo','dolby','dolby digital','bilingual'
    /// and 'surround'. 'bilingual' in this case refers to a single audio stream where the left and right channels contain monophonic audio
    /// in different languages.  Other values may be added later.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stereo: Option<TagWithOnlyText>, // TODO: flatten 1 level
}

/// When and where the programme was last shown, if known.  Normally in TV listings 'repeat' means 'previously shown on this channel', but
/// if you don't know what channel the old screening was on (but do know that it happened) then you can omit the 'channel' attribute.
/// Similarly you can omit the 'start' attribute if you don't know when the previous transmission was (though you can of course give just the
/// year, etc.).
///
/// The absence of this element does not say for certain that the programme is brand new and has never been screened anywhere before.
///
/// ```dtd
/// <!ELEMENT previously-shown EMPTY>
/// <!ATTLIST previously-shown start   CDATA #IMPLIED
///                            channel CDATA #IMPLIED >
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct PreviouslyShown {
    #[serde(skip_serializing_if = "Option::is_none", rename = "@start")]
    pub start: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "@channel")]
    pub channel: Option<String>,
}

/// These can be either 'teletext' (sent digitally, and displayed at the viewer's request), 'onscreen' (superimposed on the
/// picture and impossible to get rid of), or 'deaf-signed' (in-vision signing for users of sign language). You can have multiple subtitle
/// streams to handle different languages.  Language for subtitles is specified in the same way as for programmes.
///
/// ```dtd
/// <!ELEMENT subtitles (language?)>
/// <!ATTLIST subtitles type (teletext | onscreen | deaf-signed) #IMPLIED>
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Subtitles {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<ValueAndLang>,
    // TODO: constraint values
    #[serde(rename = "@type", skip_serializing_if = "Option::is_none")]
    pub r#type: Option<String>, // TODO: enum
}

/// Various bodies decide on classifications for films - usually a minimum age you must be to see it.  In principle the same
/// could be done for ordinary TV programmes.  Because there are many systems for doing this, you can also specify the rating system used
/// (which in practice is the same as the body which made the rating).
///
/// ```dtd
/// <!ELEMENT rating (value, icon*)>
/// <!ATTLIST rating system CDATA #IMPLIED>
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Rating {
    pub value: String, // TODO:
    #[serde(
        rename = "icon",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub icons: Vec<Icon>,
    #[serde(rename = "@system", skip_serializing_if = "Option::is_none")]
    pub system: Option<String>,
}

/// many listings guides award a programme a score as a quick guide to how good it is.  The value of this element should be
/// 'N / M', for example one star out of a possible five stars would be '1 / 5'.  Zero stars is also a possible score (and not the same as
/// 'unrated').  You should try to map whatever wacky system your listings source uses to a number of stars: so for example if they have thumbs
/// up, thumbs sideways and thumbs down, you could map that to two, one or zero stars out of two.  If a programme is marked as recommended in a
/// listings guide you could map this to '1 / 1'. Because there could be many ways to provide star-ratings or recommendations for a programme, you can
/// specify multiple star-ratings. You can specify the star-rating system used, or the provider of the recommendation, with the system attribute.
/// Whitespace between the numbers and slash is ignored.
///
/// ```dtd
/// <!ELEMENT star-rating (value, icon*)>
/// <!ATTLIST star-rating system CDATA #IMPLIED>
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct StarRating {
    pub value: String, // TODO:
    #[serde(
        rename = "icon",
        skip_serializing_if = "Vec::is_empty",
        default = "Vec::new"
    )]
    pub icons: Vec<Icon>,
    #[serde(rename = "@system", skip_serializing_if = "Option::is_none")]
    pub system: Option<String>,
}

/// Listings guides may provide reviews of programmes in addition to, or in place of, standard programme descriptions. They are
/// usually written by in-house reviewers, but reviews can also be made available by third-party organisations/individuals. The value of this
/// element must be either the text of the review, or a URL that links to it. Optional attributes giving the review source and the individual reviewer
/// can also be specified.
///
/// ```dtd
/// <!ELEMENT review (#PCDATA)>
/// <!ATTLIST review type     (text | url) #REQUIRED
///                  source   CDATA        #IMPLIED
///                  reviewer CDATA        #IMPLIED
///                  lang     CDATA        #IMPLIED>
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Review {
    #[serde(rename = "$text")]
    pub value: String,
    #[serde(rename = "@type")]
    pub r#type: String,
    #[serde(rename = "@source", skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    #[serde(rename = "@reviewer", skip_serializing_if = "Option::is_none")]
    pub reviewer: Option<String>,
    #[serde(rename = "@lang", skip_serializing_if = "Option::is_none")]
    pub lang: Option<String>,
}

/// An icon associated with the element that contains it.
/// - src: uri of image
/// - width, height: (optional) dimensions of image
///
/// These dimensions are pixel dimensions for the time being, eventually this will change to be more like HTML's 'img'.
///
/// ```dtd
/// <!ELEMENT icon EMPTY>
/// <!ATTLIST icon src         CDATA #REQUIRED
/// width       CDATA #IMPLIED
/// height      CDATA #IMPLIED>
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Icon {
    #[serde(rename = "@src")]
    pub src: String,
    #[serde(skip_serializing_if = "Option::is_none", rename = "@width")]
    pub width: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "@height")]
    pub height: Option<String>,
}

/// The true length of the programme, not counting advertisements or trailers.  But this does take account of any bits which were cut out
///of the broadcast version - eg if a two hour film is cut to 110 minutes and then padded with 20 minutes of advertising, length will be 110
/// minutes even though end time minus start time is 130 minutes.
///
/// ```dtd
/// <!ELEMENT length (#PCDATA)>
/// <!ATTLIST length units (seconds | minutes | hours) #REQUIRED>
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Length {
    #[serde(rename = "$text")]
    pub length: u32,
    #[serde(rename = "@units")]
    pub units: Units,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[repr(u8)]
pub enum Units {
    Seconds,
    Minutes,
    Hours,
}
impl Length {
    /// Get a tuple of hours, minutes and seconds.
    /// Hours are capped at `u8::MAX` (255) for extreme values.
    pub fn to_hms(&self) -> (u8, u8, u8) {
        let (h, m, s) = match self.units {
            Units::Seconds => {
                let (m, s) = divmod(self.length, 60);
                let (h, m) = divmod(m, 60);
                (h, m, s)
            }
            Units::Minutes => {
                let (h, m) = divmod(self.length, 60);
                (h, m, 0)
            }
            Units::Hours => (self.length, 0, 0),
        };
        (h.min(u32::from(u8::MAX)) as u8, m as u8, s as u8)
    }
}

impl std::fmt::Display for Units {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Units::Seconds => fmt.write_str("seconds"),
            Units::Minutes => fmt.write_str("minutes"),
            Units::Hours => fmt.write_str("hours"),
        }
    }
}

/// Integer division: returns (quotient, remainder).
fn divmod(x: u32, y: u32) -> (u32, u32) {
    (x / y, x % y)
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{Timelike, Utc};

    #[test]
    fn test_programme_date_parsing() {
        let prog = Programme {
            start: "20231027205000 +0200".to_string(),
            stop: Some("20231027223000 +0200".to_string()),
            ..Default::default()
        };

        let start = prog.start_datetime().expect("Should parse start date");
        let stop = prog.stop_datetime().expect("Should parse stop date");

        // Check UTC conversion (20:50 +0200 -> 18:50 UTC)
        assert_eq!(start.hour(), 18);
        assert_eq!(start.minute(), 50);
        assert_eq!(stop.hour(), 20);
        assert_eq!(stop.minute(), 30);
    }

    #[test]
    fn test_programme_is_live() {
        let now = Utc::now();
        let start = now - chrono::Duration::minutes(30);
        let stop = now + chrono::Duration::minutes(30);

        let prog = Programme {
            start: start.format("%Y%m%d%H%M%S +0000").to_string(),
            stop: Some(stop.format("%Y%m%d%H%M%S +0000").to_string()),
            ..Default::default()
        };

        assert!(prog.is_live(), "Programme should be live");
    }

    #[test]
    fn test_generate_hash_stability() {
        let prog1 = Programme {
            channel: "TF1.fr".to_string(),
            start: "20231027205000".to_string(),
            titles: vec![ValueAndLang {
                value: "Journal".to_string(),
                lang: None,
            }],
            ..Default::default()
        };

        let prog2 = Programme {
            channel: "TF1.fr".to_string(),
            start: "20231027205000".to_string(),
            titles: vec![ValueAndLang {
                value: "Journal".to_string(),
                lang: None,
            }],
            ..Default::default()
        };

        assert_eq!(
            prog1.generate_hash(),
            prog2.generate_hash(),
            "Hash should be the same with same metadata."
        );
    }

    #[test]
    fn test_get_title_with_lang() {
        let prog = Programme {
            titles: vec![
                ValueAndLang {
                    value: "News".to_string(),
                    lang: Some("en".to_string()),
                },
                ValueAndLang {
                    value: "Journal".to_string(),
                    lang: Some("fr".to_string()),
                },
            ],
            ..Default::default()
        };

        assert_eq!(prog.get_title(Some("fr")), Some("Journal"));
        assert_eq!(prog.get_title(Some("en")), Some("News"));
        assert_eq!(prog.get_title(None), Some("News")); // First by default
    }

    #[test]
    fn test_tv_find_methods() {
        let mut tv = Tv::default();
        tv.channels.push(Channel {
            id: "arte.tv".to_string(),
            display_names: vec![NameAndLang {
                name: "Arte".to_string(),
                lang: None,
            }],
            ..Default::default()
        });

        tv.programmes.push(Programme {
            channel: "arte.tv".to_string(),
            start: "20231027205000".to_string(),
            ..Default::default()
        });

        // Test get_channel
        let chan = tv.get_channel("arte.tv");
        assert!(chan.is_some());
        assert_eq!(chan.unwrap().id, "arte.tv");

        // Test find_by_channel
        let progs = tv.find_by_channel("arte.tv");
        assert_eq!(progs.len(), 1);
        assert_eq!(progs[0].channel, "arte.tv");
    }

    #[test]
    fn test_tv_cleanse() {
        let mut prog = Programme {
            channel: "TF1".to_string(),
            categories: vec![NameAndLang {
                name: "Sport".to_string(),
                lang: None,
            }],
            credits: Some(Credits::default()),
            ..Default::default()
        };

        prog.cleanse(&["categories".to_string(), "credits".to_string()]);

        assert!(prog.categories.is_empty());
        assert!(prog.credits.is_none());
    }
}