|
1 | | -use log::trace; |
| 1 | +use std::sync::Arc; |
2 | 2 |
|
3 | | -use crate::model::track::Track; |
| 3 | +use log::debug; |
4 | 4 |
|
5 | | -#[derive(Clone)] |
6 | | -pub struct LyricsFetcher {} |
| 5 | +use crate::{config::Config, model::track::Track}; |
7 | 6 |
|
8 | | -impl LyricsFetcher { |
9 | | - pub fn new() -> LyricsFetcher { |
10 | | - Self {} |
11 | | - } |
| 7 | +pub trait LyricsFetcher { |
| 8 | + fn fetch(&self, track: &Track) -> String; |
| 9 | +} |
| 10 | + |
| 11 | +pub struct MusixMatchLyricsFetcher { |
| 12 | + api_key: String, |
| 13 | +} |
| 14 | + |
| 15 | +impl LyricsFetcher for MusixMatchLyricsFetcher { |
| 16 | + fn fetch(&self, track: &Track) -> String { |
| 17 | + let track_title = track.title.clone(); |
| 18 | + let track_authors = track.artists.join(", "); |
| 19 | + |
| 20 | + debug!("Fetching lyrics for {} by {}", track_title, track_authors); |
12 | 21 |
|
13 | | - /// Fetches the lyrics of the given song using the specified lyrics source |
14 | | - pub fn fetch(&self, track: &Track) -> String { |
15 | | - // std::thread::sleep(std::time::Duration::from_secs(2)); |
16 | | - trace!("Fetching lyrics for {track}"); |
| 22 | + let client = reqwest::blocking::Client::new(); |
17 | 23 |
|
18 | | - format!("Sample Lyrics for {}\n", track.title) |
| 24 | + let response = client |
| 25 | + .get("https://api.musixmatch.com/ws/1.1/matcher.lyrics.get") |
| 26 | + .query(&[ |
| 27 | + ("q_track", track_title.clone()), |
| 28 | + ("q_artist", track_authors), |
| 29 | + ("apikey", self.api_key.clone()), |
| 30 | + ]) |
| 31 | + .send() |
| 32 | + .unwrap(); |
| 33 | + |
| 34 | + if response.status() != 200 { |
| 35 | + debug!("Error fetching lyrics for {}", track_title); |
| 36 | + return format!("Error fetching lyrics for {}", track_title); |
| 37 | + } |
| 38 | + |
| 39 | + // Do this since we do not have a specific body type to parse into |
| 40 | + let text = response.text().unwrap(); |
| 41 | + let json: serde_json::Value = serde_json::from_str(&text).unwrap(); |
| 42 | + |
| 43 | + debug!("Received {:?}", json); |
| 44 | + |
| 45 | + if json["status_code"] != 200 { |
| 46 | + debug!("Error fetching lyrics for {}", track_title); |
| 47 | + return format!("Error fetching lyrics for {}", track_title); |
| 48 | + } |
| 49 | + |
| 50 | + json["message"]["body"]["lyrics"]["lyrics_body"].to_string() |
19 | 51 | } |
20 | 52 | } |
21 | 53 |
|
22 | | -impl Default for LyricsFetcher { |
23 | | - fn default() -> Self { |
24 | | - LyricsFetcher::new() // TODO: check the prefered fetcher |
25 | | - } |
| 54 | +pub fn default_fetcher(cfg: Arc<Config>) -> Box<dyn LyricsFetcher> { |
| 55 | + Box::new(MusixMatchLyricsFetcher { |
| 56 | + api_key: cfg.values().backend.clone().unwrap(), |
| 57 | + }) |
26 | 58 | } |
0 commit comments