use anyhow::Result;
use std::env;
use std::path::Path;
use yt_transcript_rs::api::YouTubeTranscriptApi;
#[tokio::main]
async fn main() -> Result<()> {
println!("YouTube Transcript API - Cookie Authentication Example");
println!("-----------------------------------------------------");
let cookie_file = env::var("YOUTUBE_COOKIE_FILE").ok();
let api = if let Some(cookie_path) = &cookie_file {
println!("Using cookie file: {}", cookie_path);
let path = Path::new(cookie_path);
YouTubeTranscriptApi::new(Some(path), None, None)?
} else {
println!("No cookie file specified (YOUTUBE_COOKIE_FILE not set)");
println!("Using without cookie authentication");
YouTubeTranscriptApi::new(None, None, None)?
};
let video_id = if cookie_file.is_some() {
"mQvteoFiMlg" } else {
"arj7oStGLkU" };
let languages = &["en"];
let preserve_formatting = false;
println!("Fetching transcript for video ID: {}", video_id);
println!("(The API will handle cookie consent if needed)");
match api
.fetch_transcript(video_id, languages, preserve_formatting)
.await
{
Ok(transcript) => {
println!("\nSuccessfully fetched transcript!");
println!("Video ID: {}", transcript.video_id);
println!(
"Language: {} ({})",
transcript.language, transcript.language_code
);
println!("Is auto-generated: {}", transcript.is_generated);
println!("Number of snippets: {}", transcript.snippets.len());
println!("\nTranscript content (first 5 snippets):");
for snippet in transcript.snippets.iter().take(5) {
println!(
"[{:.1}-{:.1}s] {}",
snippet.start,
snippet.start + snippet.duration,
snippet.text
);
}
println!("... (truncated)");
}
Err(e) => {
println!("Failed to fetch transcript: {:?}", e);
if format!("{:?}", e).contains("AgeRestricted") {
println!("\nThis video is age-restricted. To access it, you need to:");
println!("1. Export cookies from a browser where you're logged into YouTube");
println!(
"2. Set the YOUTUBE_COOKIE_FILE environment variable to point to your cookie file"
);
println!("3. Run this example again");
} else if format!("{:?}", e).contains("FailedToCreateConsentCookie") {
println!("\nCouldn't create a consent cookie automatically.");
println!("To resolve this:");
println!(
"1. Export cookies from a browser where you've already accepted YouTube's consent"
);
println!(
"2. Set the YOUTUBE_COOKIE_FILE environment variable to point to your cookie file"
);
}
}
}
Ok(())
}