Skip to content

Commit

Permalink
Parse time myself
Browse files Browse the repository at this point in the history
  • Loading branch information
jameshi16 committed Aug 4, 2024
1 parent 1c16d86 commit cb5dda9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
2 changes: 1 addition & 1 deletion rust/twitch_utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ log = "0.4.22"
reqwest = {version = "0.11.27", features = ["json", "blocking"]}
serde = { version = "1.0.204", features = ["derive"] }
twitch_api = { version = "0.7.0-rc.7", features = ["all", "reqwest"] }
iso8601-duration = { version = "0.2.0", features = ["chrono"] }
chrono = "0.4.38"
regex = "1.10.6"
34 changes: 27 additions & 7 deletions rust/twitch_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,27 @@ pub const USER_AGENT: &str = concat!(
" (https://vanorsigma.github.io/neuro-chat-elo)"
);

/// Twitch's duration timestamp can't be parsed by iso8601 parsers that I can find
fn parse_time(duration_str: &str) -> Result<u32, Box<dyn std::error::Error>> {
let re = regex::Regex::new(r"(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?").unwrap();

let captures = re
.captures(duration_str)
.expect("should pass even with empty string");

let hours = captures
.get(1)
.map_or(Ok(0), |m| m.as_str().parse::<u32>())?;
let minutes = captures
.get(2)
.map_or(Ok(0), |m| m.as_str().parse::<u32>())?;
let seconds = captures
.get(3)
.map_or(Ok(0), |m| m.as_str().parse::<u32>())?;

Ok(hours * 3600 + minutes * 60 + seconds)
}

#[derive(Clone)]
pub struct TwitchAPIWrapper {
pub twitch: HelixClient<'static, reqwest::Client>,
Expand Down Expand Up @@ -74,13 +95,12 @@ impl TwitchAPIWrapper {

let end_timestamp = start_timestamp
.checked_add_signed(
vod_info.data[0]
.duration
.as_str()
.parse::<iso8601_duration::Duration>()
.expect("cannot get vod end duration")
.to_chrono()
.expect("can convert to timedelta"),
chrono::TimeDelta::new(
parse_time(vod_info.data[0].duration.as_str()).expect("parsable duration")
as i64,
0,
)
.expect("can convert to timedelta"),
)
.expect("can get end duration");

Expand Down

0 comments on commit cb5dda9

Please sign in to comment.