|
| 1 | +use crate::fingerprinting::user_agent; |
| 2 | +use regex::Regex; |
| 3 | +use reqwest::header::HeaderMap; |
| 4 | +use reqwest::StatusCode; |
| 5 | +use std::error::Error; |
| 6 | +use std::sync::OnceLock; |
| 7 | +use std::time::Duration; |
| 8 | +use unicode_normalization::UnicodeNormalization; |
| 9 | + |
| 10 | +pub struct LyricSearchInfo { |
| 11 | + pub artist_name: String, |
| 12 | + pub song_name: String, |
| 13 | +} |
| 14 | + |
| 15 | +pub fn fetch_genius_lyrics(info: &LyricSearchInfo) -> Result<String, Box<dyn Error>> { |
| 16 | + static RE_PAREN: OnceLock<Regex> = OnceLock::new(); |
| 17 | + static RE_FEAT: OnceLock<Regex> = OnceLock::new(); |
| 18 | + static RE_TAG_START: OnceLock<Regex> = OnceLock::new(); |
| 19 | + static RE_TAG_END: OnceLock<Regex> = OnceLock::new(); |
| 20 | + |
| 21 | + let re_paren = RE_PAREN.get_or_init(|| Regex::new(r#"\(.*?\)"#).unwrap()); |
| 22 | + let re_feat = RE_FEAT.get_or_init(|| Regex::new(r#"\(.*?(?:feat\.|ft\.).*?\)"#).unwrap()); |
| 23 | + let re_tag_start = RE_TAG_START.get_or_init(|| Regex::new(r#"<.+?>"#).unwrap()); |
| 24 | + let re_tag_end = RE_TAG_END.get_or_init(|| Regex::new(r#"<.+?/>"#).unwrap()); |
| 25 | + |
| 26 | + // Remove parens with feat. or ft. in them e.g. Song Title (feat. XXX). |
| 27 | + let song = re_feat.replace_all(&info.song_name, ""); |
| 28 | + |
| 29 | + let url = make_url(&format!("{}-{}", info.artist_name, song)); |
| 30 | + |
| 31 | + let html = match fetch_lyrics_html(&url)? { |
| 32 | + Some(lyrics) => Some(lyrics), |
| 33 | + None => { |
| 34 | + // Try one more time, this time with all parens removed from the song title. |
| 35 | + if song.contains('(') { |
| 36 | + let song = re_paren.replace_all(&song, ""); |
| 37 | + let url = make_url(&format!("{}-{}", info.artist_name, song)); |
| 38 | + fetch_lyrics_html(&url)? |
| 39 | + } else { |
| 40 | + None |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + .ok_or("lyrics not found")?; |
| 45 | + |
| 46 | + // Reduce the amount of text we need to look at to find the lyrics. Lyrics are in between |
| 47 | + // the <div id="lyrics-root> and <div class="LyricsFooter"> tags. |
| 48 | + let root = &html[html |
| 49 | + .find("id=\"lyrics-root\"") |
| 50 | + .ok_or("lyrics-root not found")? |
| 51 | + ..html |
| 52 | + .find("class=\"LyricsFooter") |
| 53 | + .ok_or("LyricsFooter not found")?]; |
| 54 | + |
| 55 | + let mut lyrics = String::new(); |
| 56 | + |
| 57 | + for container in root.split("data-lyrics-container=\"true\"").skip(1) { |
| 58 | + let container = container.trim().replace("<br/>", "\n"); |
| 59 | + |
| 60 | + for line in container.lines() { |
| 61 | + // Remove all opening and closing HTML tags. |
| 62 | + let replaced = re_tag_start.replace_all(line, "").to_string(); |
| 63 | + let replaced = re_tag_end.replace_all(&replaced, "").to_string(); |
| 64 | + // Clean up some remaining garbage. |
| 65 | + let replaced = replaced.replace("<div", ""); |
| 66 | + let replaced = replaced.split("\">").last().unwrap(); |
| 67 | + |
| 68 | + // Exclude annotation lines. |
| 69 | + if replaced.get(0..1) != Some("[") { |
| 70 | + lyrics.push_str(&html_escape::decode_html_entities(&replaced)); |
| 71 | + lyrics.push('\n'); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + Ok(lyrics.trim().to_string()) |
| 76 | +} |
| 77 | + |
| 78 | +fn fetch_lyrics_html(url: &str) -> Result<Option<String>, Box<dyn Error>> { |
| 79 | + let mut headers = HeaderMap::new(); |
| 80 | + headers.insert("User-Agent", user_agent::random().parse()?); |
| 81 | + headers.insert("Content-Language", "en_US".parse()?); |
| 82 | + |
| 83 | + let client = reqwest::blocking::Client::new(); |
| 84 | + let response = client |
| 85 | + .get(url) |
| 86 | + .timeout(Duration::from_secs(20)) |
| 87 | + .headers(headers) |
| 88 | + .send()?; |
| 89 | + |
| 90 | + if response.status() == StatusCode::NOT_FOUND { |
| 91 | + Ok(None) |
| 92 | + } else { |
| 93 | + Ok(Some(response.text()?)) |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +fn make_url(query: &str) -> String { |
| 98 | + // Convert accents and umlauts etc. to plain ascii as otherwise the lyric lookup fails. |
| 99 | + let query = query.nfd().filter(char::is_ascii).collect::<String>(); |
| 100 | + |
| 101 | + // Other replacements. |
| 102 | + let query = query.replace('&', "and"); |
| 103 | + |
| 104 | + let lower = query.to_lowercase(); |
| 105 | + let mut chars = lower.chars(); |
| 106 | + let mut mangled = String::new(); |
| 107 | + let Some(first) = chars.next() else { |
| 108 | + return mangled; |
| 109 | + }; |
| 110 | + mangled.extend(first.to_uppercase()); |
| 111 | + |
| 112 | + let exclude = [ |
| 113 | + '\'', '"', '’', '`', '(', ')', '[', ']', '{', '}', '!', '?', ',', '.', '/', '|', |
| 114 | + ]; |
| 115 | + let mut skip = false; |
| 116 | + for char in chars { |
| 117 | + if char.is_whitespace() || char == '-' { |
| 118 | + if !skip { |
| 119 | + mangled.push('-'); |
| 120 | + skip = true; |
| 121 | + } |
| 122 | + } else if !exclude.contains(&char) { |
| 123 | + mangled.push(char); |
| 124 | + skip = false; |
| 125 | + } |
| 126 | + } |
| 127 | + let last = mangled.pop().unwrap(); |
| 128 | + if last != '-' { |
| 129 | + mangled.push(last); |
| 130 | + } |
| 131 | + format!("https://genius.com/{mangled}-lyrics") |
| 132 | +} |
0 commit comments