rustypipe 0.11.4

Client for the public YouTube / YouTube Music API (Innertube), inspired by NewPipe
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
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
//! Parser for textual dates and times.
//!
//! The YouTube API mostly outputs pre-formatted dates and times
//! like "18 minutes ago" or "Jul 2, 2014" instead of standardized
//! machine-readable date and time formats.
//!
//! Additionally these formats are localized, meaning they depend
//! on the configured language.
//!
//! This module can parse these dates using an embedded dictionary which
//! contains date/time unit tokens for all supported languages.

use std::ops::Mul;

use serde::{Deserialize, Serialize};
use time::{Date, Duration, Month, OffsetDateTime, UtcOffset};

use crate::{
    param::Language,
    util::{self, dictionary, SplitTokens},
};

/// Parsed TimeAgo string, contains amount and time unit.
///
/// Example: "14 hours ago" => `TimeAgo {n: 14, unit: TimeUnit::Hour}`
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TimeAgo {
    /// Number of time units
    pub n: u8,
    /// Time unit
    pub unit: TimeUnit,
}

/// Parsed date string that may be relative or absolute.
///
/// Examples:
///
/// - "Jul 2, 2014" => `ParsedDate::Absolute("2014-07-02")`
/// - "2 months ago" => `ParsedDate::Relative(TimeAgo {n: 2, unit: TimeUnit::Month})`
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ParsedDate {
    /// Absolute date
    ///
    /// Example: "Jul 2, 2014"
    Absolute(Date),
    /// Relative date
    ///
    /// Example: "2 months ago"
    Relative(TimeAgo),
}

/// Parsed time unit
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "lowercase")]
#[allow(missing_docs)]
pub enum TimeUnit {
    Second,
    Minute,
    Hour,
    Day,
    Week,
    Month,
    Year,
    LastWeek,
    LastWeekday,
}

/// Value of a parsed TimeAgo token, used in the dictionary
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct TaToken {
    pub n: u8,
    pub unit: Option<TimeUnit>,
}

impl TimeUnit {
    pub fn secs(self) -> u32 {
        match self {
            TimeUnit::Second => 1,
            TimeUnit::Minute => 60,
            TimeUnit::Hour => 3600,
            TimeUnit::Day => 24 * 3600,
            TimeUnit::Week => 7 * 24 * 3600,
            TimeUnit::Month => 30 * 24 * 3600,
            TimeUnit::Year => 365 * 24 * 3600,
            TimeUnit::LastWeekday | TimeUnit::LastWeek => 0,
        }
    }
}

impl TaToken {
    fn into_timeago(self) -> Option<TimeAgo> {
        self.unit.map(|unit| TimeAgo { n: self.n, unit })
    }
}

impl TimeAgo {
    fn secs(self) -> u32 {
        u32::from(self.n) * self.unit.secs()
    }

    fn into_datetime(self, utc_offset: UtcOffset) -> OffsetDateTime {
        let ts = util::now_sec().to_offset(utc_offset);
        match self.unit {
            TimeUnit::Month => ts.replace_date(util::shift_months(ts.date(), -i32::from(self.n))),
            TimeUnit::Year => ts.replace_date(util::shift_years(ts.date(), -i32::from(self.n))),
            TimeUnit::LastWeek => {
                ts.replace_date(util::shift_weeks_monday(ts.date(), -i32::from(self.n)))
            }
            TimeUnit::LastWeekday => ts.replace_date(
                Date::from_iso_week_date(
                    ts.year(),
                    ts.iso_week(),
                    time::Weekday::Monday.nth_next(self.n),
                )
                .unwrap(),
            ),
            _ => ts - Duration::from(self),
        }
    }
}

impl Mul<u8> for TimeAgo {
    type Output = Self;

    fn mul(self, rhs: u8) -> Self::Output {
        TimeAgo {
            n: self.n * rhs,
            unit: self.unit,
        }
    }
}

impl From<TimeAgo> for Duration {
    fn from(ta: TimeAgo) -> Self {
        Duration::seconds(ta.secs().into())
    }
}

impl ParsedDate {
    fn into_datetime(self, utc_offset: UtcOffset) -> OffsetDateTime {
        match self {
            ParsedDate::Absolute(date) => date.with_hms(0, 0, 0).unwrap().assume_offset(utc_offset),
            ParsedDate::Relative(timeago) => timeago.into_datetime(utc_offset),
        }
    }
}

/// Prepare the datestring for parsing: lowercase and filter out unnecessary punctuation
fn filter_datestr(string: &str) -> String {
    string
        .to_lowercase()
        .chars()
        .filter_map(|c| {
            if matches!(c, '\u{200b}' | '.' | ',') || c.is_ascii_digit() {
                None
            } else if c == '-' {
                Some(' ')
            } else {
                Some(c)
            }
        })
        .collect()
}

struct TaTokenParser<'a> {
    iter: SplitTokens<'a>,
    tokens: &'a phf::Map<&'static str, TaToken>,
}

impl<'a> TaTokenParser<'a> {
    fn new(entry: &'a dictionary::Entry, by_char: bool, nd: bool, filtered_str: &'a str) -> Self {
        let tokens = if nd {
            &entry.timeago_nd_tokens
        } else {
            &entry.timeago_tokens
        };
        Self {
            iter: SplitTokens::new(filtered_str, by_char),
            tokens,
        }
    }
}

impl Iterator for TaTokenParser<'_> {
    type Item = TimeAgo;

    fn next(&mut self) -> Option<Self::Item> {
        // Quantity for parsing separate quantity + unit tokens
        let mut qu = 1;
        self.iter.find_map(|word| {
            self.tokens.get(word).and_then(|t| match t.unit {
                Some(unit) => Some(TimeAgo { n: t.n * qu, unit }),
                None => {
                    qu = t.n;
                    None
                }
            })
        })
    }
}

fn parse_textual_month(lang: Language, filtered_str: &str) -> Option<u8> {
    let entry = dictionary::entry(lang);
    filtered_str
        .split_whitespace()
        .find_map(|word| entry.months.get(word).copied())
        .map(|mon| {
            // Mongolian has an extra number word that adds 10 to a month
            if lang == Language::Mn && filtered_str.split_whitespace().any(|s| s == "арван") {
                mon + 10
            } else {
                mon
            }
        })
}

/// Parse a TimeAgo string (e.g. "29 minutes ago") into a TimeAgo object.
///
/// Returns [`None`] if the date could not be parsed.
pub fn parse_timeago(lang: Language, textual_date: &str) -> Option<TimeAgo> {
    let entry = dictionary::entry(lang);
    let filtered_str = filter_datestr(textual_date);

    let qu: u8 = util::parse_numeric_prod(textual_date).unwrap_or(1);

    // French uses 'a' as a short form of years.
    // Since 'a' is also a word in French, it cannot be parsed as a token.
    if matches!(
        lang,
        Language::Fr | Language::FrCa | Language::Es | Language::Es419 | Language::EsUs
    ) && textual_date.ends_with(" a")
    {
        return Some(TimeAgo {
            n: qu,
            unit: TimeUnit::Year,
        });
    }

    TaTokenParser::new(&entry, util::lang_by_char(lang), false, &filtered_str)
        .next()
        .map(|ta| ta * qu)
}

/// Parse a TimeAgo string (e.g. "29 minutes ago") into a Chrono DateTime object.
///
/// Returns [`None`] if the date could not be parsed.
pub fn parse_timeago_dt(lang: Language, textual_date: &str) -> Option<OffsetDateTime> {
    parse_timeago(lang, textual_date).map(|t| t.into_datetime(UtcOffset::UTC))
}

pub fn parse_timeago_dt_or_warn(
    lang: Language,
    textual_date: &str,
    warnings: &mut Vec<String>,
) -> Option<OffsetDateTime> {
    let res = parse_timeago_dt(lang, textual_date);
    if res.is_none() {
        warnings.push(format!("could not parse timeago `{textual_date}`"));
    }
    res
}

/// Parse a textual date (e.g. "29 minutes ago" or "Jul 2, 2014") into a ParsedDate object.
///
/// Returns [`None`] if the date could not be parsed.
pub fn parse_textual_date(
    lang: Language,
    utc_offset: UtcOffset,
    textual_date: &str,
) -> Option<ParsedDate> {
    let entry = dictionary::entry(lang);
    let by_char = util::lang_by_char(lang);
    let filtered_str = filter_datestr(textual_date);

    let nums = util::parse_numeric_vec::<u16>(textual_date);

    if nums.is_empty() {
        entry
            .timeago_nd_tokens
            .get(&filtered_str)
            .and_then(|t| t.into_timeago())
            .or_else(|| TaTokenParser::new(&entry, by_char, true, &filtered_str).next())
            .or_else(|| TaTokenParser::new(&entry, by_char, false, &filtered_str).next())
            .map(ParsedDate::Relative)
    } else {
        if nums.len() == 1 && nums[0] < 2000 {
            if let Some(timeago) = TaTokenParser::new(&entry, by_char, false, &filtered_str).next()
            {
                return Some(ParsedDate::Relative(timeago * nums[0] as u8));
            }
        }

        let mut y: Option<u16> = None;
        let mut m = parse_textual_month(lang, &filtered_str).map(u16::from);
        let mut d: Option<u16> = None;

        for num in nums {
            if num > 31 {
                if y.is_none() {
                    y = Some(num);
                } else {
                    return None;
                }
            } else if m.is_none() && (entry.month_before_day || d.is_some()) {
                m = Some(num);
            } else if d.is_none() {
                d = Some(num);
            } else {
                return None;
            }
        }
        if m.is_none() && d.is_some() {
            m = d;
            d = None;
        }

        match (y, m, d) {
            (y, Some(m), d) => Month::try_from(m as u8)
                .ok()
                .and_then(|m| {
                    Date::from_calendar_date(
                        y.map(i32::from).unwrap_or_else(|| {
                            OffsetDateTime::now_utc().to_offset(utc_offset).year()
                        }),
                        m,
                        d.unwrap_or(1) as u8,
                    )
                    .ok()
                })
                .map(ParsedDate::Absolute),
            _ => None,
        }
    }
}

/// Parse a textual date (e.g. "29 minutes ago" or "Jul 2, 2014") into a OffsetDateTime object.
///
/// Returns None if the date could not be parsed.
pub fn parse_textual_date_to_dt(
    lang: Language,
    utc_offset: UtcOffset,
    textual_date: &str,
) -> Option<OffsetDateTime> {
    parse_textual_date(lang, utc_offset, textual_date).map(|t| t.into_datetime(utc_offset))
}

/// Parse a textual date (e.g. "29 minutes ago" "Jul 2, 2014") into a Date object.
///
/// Returns None if the date could not be parsed.
#[cfg(feature = "userdata")]
pub fn parse_textual_date_to_d(
    lang: Language,
    utc_offset: UtcOffset,
    textual_date: &str,
    warnings: &mut Vec<String>,
) -> Option<Date> {
    parse_textual_date_or_warn(lang, utc_offset, textual_date, warnings)
        .map(|d| d.to_offset(utc_offset).date())
}

pub fn parse_textual_date_or_warn(
    lang: Language,
    utc_offset: UtcOffset,
    textual_date: &str,
    warnings: &mut Vec<String>,
) -> Option<OffsetDateTime> {
    let res = parse_textual_date_to_dt(lang, utc_offset, textual_date);
    if res.is_none() {
        warnings.push(format!("could not parse textual date `{textual_date}`"));
    }
    res
}

/// Parse a textual video duration (e.g. "11 minutes, 20 seconds")
///
/// Returns None if the duration could not be parsed
pub fn parse_video_duration(lang: Language, video_duration: &str) -> Option<u32> {
    let entry = dictionary::entry(lang);
    let by_char = util::lang_by_char(lang);

    let parts = split_duration_txt(video_duration, matches!(lang, Language::Si | Language::Sw));
    let mut secs = 0;

    if parts.is_empty() {
        return None;
    }

    for part in parts {
        let mut n = if part.digits.is_empty() {
            1
        } else {
            part.digits.parse::<u32>().ok()?
        };
        let mut tokens = TaTokenParser::new(&entry, by_char, false, &part.word).peekable();
        tokens.peek()?;

        tokens.for_each(|ta| {
            secs += n * ta.secs();
            n = 1;
        });
    }

    Some(secs)
}

pub fn parse_video_duration_or_warn(
    lang: Language,
    video_duration: &str,
    warnings: &mut Vec<String>,
) -> Option<u32> {
    let res = parse_video_duration(lang, video_duration);
    if res.is_none() {
        warnings.push(format!("could not parse video duration `{video_duration}`"));
    }
    res
}

#[derive(Default)]
struct DurationTxtSegment {
    digits: String,
    word: String,
}

/// Split a video duration string into its segments.
///
/// Each segment consists of a word and a string of digits (one of them may be empty).
///
/// The `start_word` parameter determines whether the segments should start with a word
/// instead of a number. This is the case in Swahili and Singhalese.
///
/// Example (start_word=false):
/// - `1 minute, 13 seconds` -> `{1;minute} {13;seconds}`
/// - `foo 1 minute, 13 seconds bar` -> `{foo} {1;minute} {13;seconds bar}`
///
/// Example (start_word=true):
/// - `dakika 1 na sekunde 1` -> `{1;dakika} {1;na sekunde}`
/// - `foo dakika 1 na sekunde 1 bar` -> `{1;foo dakika} {1;na sekunde} {bar}`
fn split_duration_txt(txt: &str, start_word: bool) -> Vec<DurationTxtSegment> {
    let mut segments = Vec::new();

    // 1: parse digits, 2: parse word
    let mut state: u8 = 0;
    let mut seg = DurationTxtSegment::default();

    for c in txt.trim().chars() {
        if c.is_ascii_digit() {
            if state == 2 && (!seg.digits.is_empty() || (!start_word && segments.is_empty())) {
                segments.push(seg);
                seg = DurationTxtSegment::default();
            }
            seg.digits.push(c);
            state = 1;
        } else {
            if (state == 1) && (!seg.word.is_empty() || (start_word && segments.is_empty())) {
                segments.push(seg);
                seg = DurationTxtSegment::default();
            }
            if !matches!(c, '.' | ',') {
                c.to_lowercase().for_each(|c| seg.word.push(c));
            }
            state = 2;
        }
    }
    if !seg.word.is_empty() || !seg.digits.is_empty() {
        segments.push(seg);
    }

    segments
}

#[cfg(test)]
mod tests {
    use std::{collections::BTreeMap, fs::File, io::BufReader, str::FromStr};

    use path_macro::path;
    use rstest::rstest;
    use time::macros::{date, datetime};

    use super::*;
    use crate::util::tests::TESTFILES;

    #[rstest]
    #[case::de(Language::De, "vor 1 Sekunde", Some(TimeAgo { n: 1, unit: TimeUnit::Second }))]
    #[case::ar(Language::Ar, "قبل ساعة واحدة", Some(TimeAgo { n: 1, unit: TimeUnit::Hour }))]
    // No-break space
    #[case::nbsp(Language::De, "Vor 3\u{a0}Tagen aktualisiert", Some(TimeAgo { n: 3, unit: TimeUnit::Day }))]
    fn t_parse(
        #[case] lang: Language,
        #[case] textual_date: &str,
        #[case] expect: Option<TimeAgo>,
    ) {
        let time_ago = parse_timeago(lang, textual_date);
        assert_eq!(time_ago, expect);
    }

    #[test]
    fn t_testfile() {
        let json_path = path!(*TESTFILES / "dict" / "timeago_samples.json");

        let expect = [
            TimeAgo {
                n: 10,
                unit: TimeUnit::Minute,
            },
            TimeAgo {
                n: 20,
                unit: TimeUnit::Minute,
            },
            TimeAgo {
                n: 1,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 2,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 7,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 8,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 9,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 10,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 11,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 12,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 13,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 14,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 15,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 3,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 4,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 4,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 5,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 6,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 6,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 20,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 2,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 3,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 5,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 6,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 8,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 10,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 12,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 2,
                unit: TimeUnit::Week,
            },
            TimeAgo {
                n: 3,
                unit: TimeUnit::Week,
            },
            TimeAgo {
                n: 4,
                unit: TimeUnit::Week,
            },
            TimeAgo {
                n: 1,
                unit: TimeUnit::Month,
            },
            TimeAgo {
                n: 8,
                unit: TimeUnit::Month,
            },
            TimeAgo {
                n: 11,
                unit: TimeUnit::Month,
            },
            TimeAgo {
                n: 1,
                unit: TimeUnit::Year,
            },
            TimeAgo {
                n: 2,
                unit: TimeUnit::Year,
            },
            TimeAgo {
                n: 3,
                unit: TimeUnit::Year,
            },
            TimeAgo {
                n: 4,
                unit: TimeUnit::Year,
            },
        ];

        let json_file = File::open(json_path).unwrap();
        let strings_map: BTreeMap<Language, Vec<String>> =
            serde_json::from_reader(BufReader::new(json_file)).unwrap();

        for (lang, strings) in &strings_map {
            assert_eq!(strings.len(), expect.len());
            strings.iter().enumerate().for_each(|(n, s)| {
                assert_eq!(
                    parse_timeago(*lang, s),
                    Some(expect[n]),
                    "Language: {lang}, txt: `{s}`"
                );
            });
        }
    }

    #[test]
    fn t_testfile_short() {
        let json_path = path!(*TESTFILES / "dict" / "timeago_samples_short.json");

        let expect = [
            TimeAgo {
                n: 35,
                unit: TimeUnit::Minute,
            },
            TimeAgo {
                n: 50,
                unit: TimeUnit::Minute,
            },
            TimeAgo {
                n: 1,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 2,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 3,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 4,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 5,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 6,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 7,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 8,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 9,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 12,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 17,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 18,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 19,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 20,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 10,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 11,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 13,
                unit: TimeUnit::Hour,
            },
            TimeAgo {
                n: 1,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 2,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 3,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 4,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 6,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 8,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 10,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 11,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 12,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 13,
                unit: TimeUnit::Day,
            },
            TimeAgo {
                n: 2,
                unit: TimeUnit::Week,
            },
            TimeAgo {
                n: 3,
                unit: TimeUnit::Week,
            },
            TimeAgo {
                n: 1,
                unit: TimeUnit::Month,
            },
            TimeAgo {
                n: 4,
                unit: TimeUnit::Week,
            },
            TimeAgo {
                n: 7,
                unit: TimeUnit::Month,
            },
            TimeAgo {
                n: 10,
                unit: TimeUnit::Month,
            },
            TimeAgo {
                n: 1,
                unit: TimeUnit::Year,
            },
            TimeAgo {
                n: 2,
                unit: TimeUnit::Year,
            },
            TimeAgo {
                n: 3,
                unit: TimeUnit::Year,
            },
            TimeAgo {
                n: 4,
                unit: TimeUnit::Year,
            },
            TimeAgo {
                n: 5,
                unit: TimeUnit::Year,
            },
        ];

        let json_file = File::open(json_path).unwrap();
        let strings_map: BTreeMap<Language, Vec<String>> =
            serde_json::from_reader(BufReader::new(json_file)).unwrap();

        for (lang, strings) in &strings_map {
            assert_eq!(strings.len(), expect.len(), "Language: {lang}");
            strings.iter().enumerate().for_each(|(n, s)| {
                let mut exp = expect[n];
                if *lang == Language::Mn && exp.unit == TimeUnit::Week {
                    exp.unit = TimeUnit::Day;
                    exp.n *= 7;
                }

                assert_eq!(
                    parse_timeago(*lang, s),
                    Some(exp),
                    "Language: {lang}, txt: `{s}`"
                );
            });
        }
    }

    #[test]
    fn t_timeago_table() {
        #[derive(Debug, Clone, Deserialize)]
        struct TimeagoTable {
            entries: BTreeMap<Language, BTreeMap<TimeUnit, TimeagoTableEntry>>,
        }

        #[derive(Debug, Clone, Deserialize)]
        struct TimeagoTableEntry {
            cases: BTreeMap<String, u8>,
        }

        let json_path = path!(*TESTFILES / "dict" / "timeago_table.json");
        let json_file = File::open(json_path).unwrap();
        let timeago_table: TimeagoTable =
            serde_json::from_reader(BufReader::new(json_file)).unwrap();
        let mut n_cases = 0;

        timeago_table.entries.iter().for_each(|(lang, entries)| {
            for (t, entry) in entries {
                entry.cases.iter().for_each(|(txt, n)| {
                    let timeago = parse_timeago(*lang, txt);
                    let textual_date = parse_textual_date(*lang, UtcOffset::UTC, txt);
                    assert_eq!(
                        timeago,
                        Some(TimeAgo { n: *n, unit: *t }),
                        "lang: {lang}, txt: {txt}"
                    );
                    assert_eq!(
                        textual_date,
                        Some(ParsedDate::Relative(TimeAgo { n: *n, unit: *t })),
                        "textual_date lang: {lang}, txt: {txt}"
                    );

                    n_cases += 1;
                });
            }
        });

        assert_eq!(n_cases, 1065);
    }

    #[rstest]
    #[case(Language::En, "Updated today", Some(ParsedDate::Relative(TimeAgo { n: 0, unit: TimeUnit::Day })))]
    #[case(Language::En, "Updated yesterday", Some(ParsedDate::Relative(TimeAgo { n: 1, unit: TimeUnit::Day })))]
    #[case(Language::En, "Updated 2 days ago", Some(ParsedDate::Relative(TimeAgo { n: 2, unit: TimeUnit::Day })))]
    #[case(Language::Si, "ඊයේ යාවත්කාලීන කරන ලදී", Some(ParsedDate::Relative(TimeAgo { n: 1, unit: TimeUnit::Day })))]
    #[case(
        Language::En,
        "Last updated on Jun 04, 2003",
        Some(ParsedDate::Absolute(date!(2003-6-4)))
    )]
    #[case(
        Language::Bn,
        "যোগ দিয়েছেন 24 সেপ, 2013",
        Some(ParsedDate::Absolute(date!(2013-9-24)))
    )]
    #[case(Language::Ja, "2023年7月", Some(ParsedDate::Absolute(date!(2023-07-01))))]
    #[case(Language::De, "Juli 2023", Some(ParsedDate::Absolute(date!(2023-07-01))))]
    fn t_parse_date(
        #[case] lang: Language,
        #[case] textual_date: &str,
        #[case] expect: Option<ParsedDate>,
    ) {
        let parsed_date = parse_textual_date(lang, UtcOffset::UTC, textual_date);
        assert_eq!(parsed_date, expect);
    }

    #[rstest]
    #[case(Language::En, "Jan 5", date!(0000-01-05))]
    fn t_parse_date_this_year(
        #[case] lang: Language,
        #[case] textual_date: &str,
        #[case] expect: Date,
    ) {
        let parsed_date = parse_textual_date(lang, UtcOffset::UTC, textual_date);
        let expected_date = expect
            .replace_year(OffsetDateTime::now_utc().year())
            .unwrap();
        assert_eq!(parsed_date, Some(ParsedDate::Absolute(expected_date)));
    }

    #[test]
    fn t_parse_date_samples() {
        let json_path = path!(*TESTFILES / "dict" / "playlist_samples.json");
        let json_file = File::open(json_path).unwrap();
        let date_samples: BTreeMap<Language, BTreeMap<String, String>> =
            serde_json::from_reader(BufReader::new(json_file)).unwrap();

        for (lang, samples) in &date_samples {
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Today").unwrap()),
                Some(ParsedDate::Relative(TimeAgo {
                    n: 0,
                    unit: TimeUnit::Day
                })),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Yesterday").unwrap()),
                Some(ParsedDate::Relative(TimeAgo {
                    n: 1,
                    unit: TimeUnit::Day
                })),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Ago").unwrap()),
                Some(ParsedDate::Relative(TimeAgo {
                    n: 5,
                    unit: TimeUnit::Day
                })),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Jan").unwrap()),
                Some(ParsedDate::Absolute(date!(2020 - 1 - 3))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Feb").unwrap()),
                Some(ParsedDate::Absolute(date!(2016 - 2 - 7))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Mar").unwrap()),
                Some(ParsedDate::Absolute(date!(2015 - 3 - 9))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Apr").unwrap()),
                Some(ParsedDate::Absolute(date!(2017 - 4 - 2))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("May").unwrap()),
                Some(ParsedDate::Absolute(date!(2014 - 5 - 22))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Jun").unwrap()),
                Some(ParsedDate::Absolute(date!(2014 - 6 - 28))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Jul").unwrap()),
                Some(ParsedDate::Absolute(date!(2014 - 7 - 2))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Aug").unwrap()),
                Some(ParsedDate::Absolute(date!(2015 - 8 - 23))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Sep").unwrap()),
                Some(ParsedDate::Absolute(date!(2018 - 9 - 16))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Oct").unwrap()),
                Some(ParsedDate::Absolute(date!(2014 - 10 - 31))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Nov").unwrap()),
                Some(ParsedDate::Absolute(date!(2016 - 11 - 3))),
                "lang: {lang}"
            );
            assert_eq!(
                parse_textual_date(*lang, UtcOffset::UTC, samples.get("Dec").unwrap()),
                Some(ParsedDate::Absolute(date!(2021 - 12 - 24))),
                "lang: {lang}"
            );
        }
    }

    #[test]
    fn t_parse_history_date_samples() {
        let json_path = path!(*TESTFILES / "dict" / "history_date_samples.json");
        let json_file = File::open(json_path).unwrap();
        let date_samples: BTreeMap<Language, BTreeMap<String, String>> =
            serde_json::from_reader(BufReader::new(json_file)).unwrap();

        for (lang, samples) in date_samples {
            for (k, v) in samples {
                let expected = match k.as_str() {
                    "this_week" => ParsedDate::Relative(TimeAgo {
                        n: 0,
                        unit: TimeUnit::LastWeek,
                    }),
                    "last_week" => ParsedDate::Relative(TimeAgo {
                        n: 1,
                        unit: TimeUnit::LastWeek,
                    }),
                    _ => {
                        if let Ok(wd) = time::Weekday::from_str(&k) {
                            ParsedDate::Relative(TimeAgo {
                                n: wd.number_days_from_monday(),
                                unit: TimeUnit::LastWeekday,
                            })
                        } else {
                            let mut date_nums = k.split('-');
                            let mut y = date_nums.next().unwrap().parse::<i32>().unwrap();
                            if y == 0 {
                                y = OffsetDateTime::now_utc().date().year();
                            }
                            let m = date_nums.next().unwrap().parse::<u8>().unwrap();
                            let d = date_nums.next().unwrap().parse::<u8>().unwrap();
                            ParsedDate::Absolute(
                                Date::from_calendar_date(y, m.try_into().unwrap(), d).unwrap(),
                            )
                        }
                    }
                };
                assert_eq!(
                    parse_textual_date(lang, UtcOffset::UTC, &v),
                    Some(expected),
                    "lang={lang}; {k}"
                );
            }
        }
    }

    #[test]
    fn t_parse_video_duration() {
        let json_path = path!(*TESTFILES / "dict" / "video_duration_samples.json");
        let json_file = File::open(json_path).unwrap();
        let date_samples: BTreeMap<Language, BTreeMap<String, u32>> =
            serde_json::from_reader(BufReader::new(json_file)).unwrap();

        for (lang, samples) in &date_samples {
            for (txt, duration) in samples {
                assert_eq!(
                    parse_video_duration(*lang, txt),
                    Some(*duration),
                    "lang: {lang}; txt: `{txt}`"
                );
            }
        }
    }

    #[rstest]
    #[case(Language::Ar, "19 دقيقة وثانيتان", 1142)]
    #[case(Language::Ar, "دقيقة و13 ثانية", 73)]
    #[case(Language::Sw, "dakika 1 na sekunde 13", 73)]
    #[case(Language::Ar, "1 س و41 د", 6060)]
    #[case(Language::Ar, "4 د و33 ث", 273)]
    fn t_parse_video_duration2(
        #[case] lang: Language,
        #[case] video_duration: &str,
        #[case] expect: u32,
    ) {
        assert_eq!(parse_video_duration(lang, video_duration), Some(expect));
    }

    #[test]
    fn t_to_datetime() {
        // Absolute date
        let date =
            parse_textual_date_to_dt(Language::En, UtcOffset::UTC, "Last updated on Jan 3, 2020")
                .unwrap();
        assert_eq!(date, datetime!(2020-1-3 0:00 +0));

        // Relative date
        let date = parse_textual_date_to_dt(Language::En, UtcOffset::UTC, "1 year ago").unwrap();
        let now = OffsetDateTime::now_utc();
        assert_eq!(date.year(), now.year() - 1);
    }
}