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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
//! # lyric_finder
//!
//! This crate provides a [`Client`](Client) struct for retrieving a song's lyric.
//!
//! It ultilizes the [Genius](https://genius.com) website and its APIs to get lyric data.
//!
//! ## Example
//!
//! ```rust
//! # use anyhow::Result;
//! #
//! # async fn run() -> Result<()> {
//! let client =  lyric_finder::Client::new();
//! let result = client.get_lyric("shape of you").await?;
//! match result {
//!     lyric_finder::LyricResult::Some {
//!         track,
//!         artists,
//!         lyric,
//!     } => {
//!         println!("{} by {}'s lyric:\n{}", track, artists, lyric);
//!     }
//!     lyric_finder::LyricResult::None => {
//!         println!("lyric not found!");
//!     }
//! }
//! # Ok(())
//! # }
//! ```

const SEARCH_BASE_URL: &str = "https://genius.com/api/search";

pub struct Client {
    http: reqwest::Client,
}

#[derive(Debug)]
pub enum LyricResult {
    Some {
        track: String,
        artists: String,
        lyric: String,
    },
    None,
}

impl Client {
    pub fn new() -> Self {
        Self {
            http: reqwest::Client::new(),
        }
    }

    /// Construct a client reusing an exisiting http client
    pub fn from_http_client(http: &reqwest::Client) -> Self {
        Self { http: http.clone() }
    }

    /// Search songs satisfying a given `query`.
    pub async fn search_songs(&self, query: &str) -> anyhow::Result<Vec<search::Result>> {
        log::debug!("search songs: query={query}");

        let body = self
            .http
            .get(format!("{SEARCH_BASE_URL}?q={query}"))
            .send()
            .await?
            .json::<search::Body>()
            .await?;

        if body.meta.status != 200 {
            let message = match body.meta.message {
                Some(m) => m,
                None => format!("request failed with status code: {}", body.meta.status),
            };
            anyhow::bail!(message);
        }

        Ok(body
            .response
            .map(|r| {
                r.hits
                    .into_iter()
                    .filter(|hit| hit.ty == "song")
                    .map(|hit| hit.result)
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default())
    }

    /// Retrieve a song's lyric from a "genius.com" `url`.
    pub async fn retrieve_lyric(&self, url: &str) -> anyhow::Result<String> {
        let html = self.http.get(url).send().await?.text().await?;
        log::debug!("retrieve lyric from url={url}: html={html}");
        let lyric = parse::parse(html)?;
        Ok(lyric.trim().to_string())
    }

    /// Process a lyric obtained by crawling the [Genius](https://genius.com) website.
    ///
    /// The lyric received this way may have weird newline spacings between sections (*).
    /// The below function tries an ad-hoc method to fix this issue.
    ///
    /// (*): A section often starts with `[`.
    fn process_lyric(lyric: String) -> String {
        // the below code modifies the `lyric` to make the newline between sections consistent
        lyric.replace("\n\n[", "\n[").replace("\n[", "\n\n[")
    }

    /// Get the lyric of a song satisfying a given `query`.
    pub async fn get_lyric(&self, query: &str) -> anyhow::Result<LyricResult> {
        // The function first searches songs satisfying the query
        // then it retrieves the song's lyric by crawling the "genius.com" website.

        let result = {
            let mut results = self.search_songs(query).await?;
            log::debug!("search results: {results:?}");
            if results.is_empty() {
                return Ok(LyricResult::None);
            }
            results.remove(0)
        };

        let lyric = self.retrieve_lyric(&result.url).await?;
        Ok(LyricResult::Some {
            track: result.title,
            artists: result.artist_names,
            lyric: Self::process_lyric(lyric),
        })
    }
}

impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

mod parse {
    use html5ever::tendril::TendrilSink;
    use html5ever::*;
    use markup5ever_rcdom::{Handle, NodeData, RcDom};

    const LYRIC_CONTAINER_ATTR: &str = "data-lyrics-container";

    /// Parse the HTML content of a "genius.com" lyric page to retrieve the corresponding lyric.
    pub fn parse(html: String) -> anyhow::Result<String> {
        // parse HTML content into DOM node(s)
        let dom = parse_document(RcDom::default(), Default::default())
            .from_utf8()
            .read_from(&mut (html.as_bytes()))?;

        let filter = |data: &NodeData| match data {
            NodeData::Element { ref attrs, .. } => attrs
                .borrow()
                .iter()
                .any(|attr| attr.name.local.to_string() == LYRIC_CONTAINER_ATTR),
            _ => false,
        };

        Ok(parse_dom_node(dom.document, &Some(filter), false))
    }

    /// Parse a dom node and extract the text of children nodes satisfying a requirement.
    ///
    /// The requirement is represented by a `filter` function and a `should_parse` variable.
    /// Once a node satisfies a requirement, its children should also satisfy it.
    fn parse_dom_node<F>(node: Handle, filter: &Option<F>, mut should_parse: bool) -> String
    where
        F: Fn(&NodeData) -> bool,
    {
        log::debug!("parse dom node: node={node:?}, should_parse={should_parse}");

        let mut s = String::new();

        if !should_parse {
            if let Some(f) = filter {
                should_parse = f(&node.data);
            }
        }

        match &node.data {
            NodeData::Text { contents } => {
                if should_parse {
                    s.push_str(&contents.borrow().to_string());
                }
            }
            NodeData::Element { ref name, .. } => {
                if let expanded_name!(html "br") = name.expanded() {
                    if should_parse {
                        s.push('\n');
                    }
                }
            }
            _ => {}
        }

        node.children.borrow().iter().for_each(|node| {
            s.push_str(&parse_dom_node(node.clone(), filter, should_parse));
        });

        s
    }
}

mod search {
    use serde::Deserialize;

    #[derive(Debug, Deserialize)]
    pub struct Body {
        pub meta: Metadata,
        pub response: Option<Response>,
    }

    #[derive(Debug, Deserialize)]
    pub struct Metadata {
        pub status: u16,
        pub message: Option<String>,
    }

    #[derive(Debug, Deserialize)]
    pub struct Response {
        pub hits: Vec<Hit>,
    }

    #[derive(Debug, Deserialize)]
    pub struct Hit {
        #[serde(rename(deserialize = "type"))]
        pub ty: String,
        pub result: Result,
    }

    #[derive(Debug, Deserialize)]
    pub struct Result {
        pub url: String,
        pub title: String,
        pub artist_names: String,
    }
}