3 node::Node::{Element, Text},
4 ElementRef, Html, Selector,
6 use serde::Deserialize;
7 use std::io::{Error, ErrorKind::Other, Result};
9 #[derive(Deserialize, Debug)]
10 struct GeniusApiResponse {
11 response: GeniusResponseBlock,
14 #[derive(Deserialize, Debug)]
15 struct GeniusResponseBlock {
19 #[derive(Deserialize, Debug)]
21 #[serde(rename = "type")]
26 #[derive(Deserialize, Debug)]
31 pub async fn search(url: &str) -> Result<String> {
32 let response = get(url)
34 .map_err(|_| Error::new(Other, "Could not perform lyrics search in engine."))?
35 .json::<GeniusApiResponse>()
40 "Lyrics engine returned invalid response from search.",
47 .find(|hit| hit.hit_type == "song")
48 .map(|hit| hit.result.url)
49 .ok_or_else(|| Error::new(Other, "Could not find a matching track in lyrics engine."))?;
54 pub async fn get_lyrics(url: &str) -> Result<String> {
55 let song_html = get(url)
57 .map_err(|_| Error::new(Other, "Could not fetch lyrics from engine."))?
60 .map_err(|_| Error::new(Other, "Lyrics engine returned invalid response."))?;
62 let document = Html::parse_document(&song_html);
63 let selector = Selector::parse(r#"div[data-lyrics-container="true"]"#).unwrap();
64 let lyrics_div = document
67 .ok_or_else(|| Error::new(Other, "Could not find lyrics in response."))?;
69 let mut lyrics = String::new();
70 for node in lyrics_div.children() {
73 if element.name() == "br" {
76 if let Some(element_ref) = ElementRef::wrap(node) {
77 let text = element_ref.text().collect::<Vec<_>>().join("");
78 lyrics.push_str(&text);
83 lyrics.push_str(text);