1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
use reqwest::get;
use scraper::{
ElementRef, Html, Selector,
node::Node::{Element, Text},
};
use serde::Deserialize;
use std::io::{Error, Result};
#[derive(Deserialize, Debug)]
struct GeniusApiResponse {
response: GeniusResponseBlock,
}
#[derive(Deserialize, Debug)]
struct GeniusResponseBlock {
hits: Vec<GeniusHit>,
}
#[derive(Deserialize, Debug)]
struct GeniusHit {
#[serde(rename = "type")]
hit_type: String,
result: GeniusResult,
}
#[derive(Deserialize, Debug)]
struct GeniusResult {
url: String,
}
pub async fn search(url: &str) -> Result<String> {
let response = get(url)
.await
.map_err(|_| Error::other("Could not perform lyrics search in engine."))?
.json::<GeniusApiResponse>()
.await
.map_err(|_| Error::other("Lyrics engine returned invalid response from search."))?;
let url = response
.response
.hits
.into_iter()
.find(|hit| hit.hit_type == "song")
.map(|hit| hit.result.url)
.ok_or_else(|| Error::other("Could not find a matching track in lyrics engine."))?;
Ok(url)
}
pub async fn get_lyrics(url: &str) -> Result<String> {
let song_html = get(url)
.await
.map_err(|_| Error::other("Could not fetch lyrics from engine."))?
.text()
.await
.map_err(|_| Error::other("Lyrics engine returned invalid response."))?;
let document = Html::parse_document(&song_html);
let selector = Selector::parse(r#"div[data-lyrics-container="true"]"#).unwrap();
let lyrics_div = document
.select(&selector)
.next()
.ok_or_else(|| Error::other("Could not find lyrics in response."))?;
let mut lyrics = String::new();
for node in lyrics_div.children() {
match node.value() {
Element(element) => {
if element.name() == "br" {
lyrics.push('\n');
} else if let Some(element_ref) = ElementRef::wrap(node) {
let text = element_ref.text().collect::<Vec<_>>().join("");
lyrics.push_str(&text);
}
}
Text(text) => {
lyrics.push_str(text);
}
_ => {}
}
}
Ok(lyrics)
}
|