more graceful error handling

This commit is contained in:
Aaron Manning 2024-08-10 15:11:00 +10:00
parent 4fb4948dcc
commit 0652a4bc6b

View File

@ -40,7 +40,7 @@ fn main() -> anyhow::Result<()> {
let headings = document.select(&headings_selector).map(|a| a.inner_html()).collect::<Vec<_>>();
let heading_selector = scraper::Selector::parse("div#pageContent > h2").unwrap();
let album_name = document.select(&heading_selector).next().unwrap().inner_html();
let album_name = document.select(&heading_selector).next().context("could not find album name heading")?.inner_html();
for element in document.select(&tracks_selector) {
@ -49,14 +49,30 @@ fn main() -> anyhow::Result<()> {
tag.set_album(album_name.clone());
let download_link_selector = scraper::Selector::parse("td.playlistDownloadSong > a").unwrap();
let download_link = element.select(&download_link_selector).next().unwrap();
let download_link = element.select(&download_link_selector).next().context("could not find download link")?;
let columns_selector = scraper::Selector::parse("td").unwrap();
let columns = element.select(&columns_selector).collect::<Vec<_>>();
let track = columns[headings.iter().position(|x| x == "<b>#</b>").unwrap()].inner_html().trim_end_matches(".").parse::<u32>().unwrap();
if let Some(track) =
headings.iter().position(|x| x == "<b>#</b>")
.and_then(|idx| {
columns[idx]
.inner_html()
.trim_end_matches(".")
.parse::<u32>().ok()
})
{
tag.set_track(track);
if let Some(cd) = headings.iter().position(|x| x == "<b>CD</b>") {
tag.set_disc(columns[cd].inner_html().parse::<u32>().unwrap_or(1));
}
if let Some(disc) =
headings.iter().position(|x| x == "<b>CD</b>").and_then(|idx| {
columns[idx]
.inner_html()
.parse::<u32>().ok()
})
{
tag.set_disc(disc);
}
let track_url = format!(
@ -77,7 +93,7 @@ fn main() -> anyhow::Result<()> {
let document = scraper::Html::parse_document(track_page);
let audio_selector = scraper::Selector::parse("audio").unwrap();
let audio = document.select(&audio_selector).next().unwrap();
let audio = document.select(&audio_selector).next().context("could not find audio tag")?;
let meta_selector = scraper::Selector::parse("p[align='left'] > b").unwrap();
let meta = document.select(&meta_selector);
@ -108,7 +124,7 @@ fn main() -> anyhow::Result<()> {
let mut audio_file = audio_response.as_bytes().to_vec();
tag.write_to(&mut audio_file, id3::Version::Id3v24).unwrap();
tag.write_to(&mut audio_file, id3::Version::Id3v24)?;
fs::write(output.join(sanitize_filename::sanitize(path.as_ref())), audio_response.as_bytes())
.context("error writing audio file")?;