use sha2::{Digest, Sha256};
const EMBED_BASE: &str = "https://iframe.mediadelivery.net/embed";
#[must_use]
pub fn embed_url(library_id: impl AsRef<str>, video_id: impl AsRef<str>) -> String {
format!("{EMBED_BASE}/{}/{}", library_id.as_ref(), video_id.as_ref())
}
#[must_use]
pub fn embed_url_signed(
library_id: impl AsRef<str>,
video_id: impl AsRef<str>,
token_security_key: impl AsRef<str>,
expires_unix_seconds: i64,
) -> String {
let video_id = video_id.as_ref();
let token = embed_token(token_security_key.as_ref(), video_id, expires_unix_seconds);
format!(
"{EMBED_BASE}/{}/{video_id}?token={token}&expires={expires_unix_seconds}",
library_id.as_ref()
)
}
#[must_use]
pub fn embed_token(token_security_key: &str, video_id: &str, expires_unix_seconds: i64) -> String {
let mut hasher = Sha256::new();
hasher.update(token_security_key.as_bytes());
hasher.update(video_id.as_bytes());
hasher.update(expires_unix_seconds.to_string().as_bytes());
hex::encode(hasher.finalize())
}
#[must_use]
pub fn hls_url(pull_zone_host: impl AsRef<str>, video_id: impl AsRef<str>) -> String {
format!(
"https://{}/{}/playlist.m3u8",
pull_zone_host.as_ref().trim_end_matches('/'),
video_id.as_ref()
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embed_token_matches_bunny_formula() {
assert_eq!(
embed_token("mysecretkey", "abc-123", 1_700_000_000),
"54ce9c375a5def073eb128910d013c1f5ae5385fae501af7e807fe4f8de927f4"
);
}
#[test]
fn url_builders_shape() {
assert_eq!(embed_url("12345", "abc-123"), "https://iframe.mediadelivery.net/embed/12345/abc-123");
assert_eq!(
embed_url_signed("12345", "abc-123", "mysecretkey", 1_700_000_000),
"https://iframe.mediadelivery.net/embed/12345/abc-123?token=54ce9c375a5def073eb128910d013c1f5ae5385fae501af7e807fe4f8de927f4&expires=1700000000"
);
assert_eq!(hls_url("vz-abc.b-cdn.net", "abc-123"), "https://vz-abc.b-cdn.net/abc-123/playlist.m3u8");
assert_eq!(hls_url("vz-abc.b-cdn.net/", "abc-123"), "https://vz-abc.b-cdn.net/abc-123/playlist.m3u8");
}
}