From: Ruben Beltran del Rio Date: Tue, 7 Feb 2023 21:10:04 +0000 (+0100) Subject: Save WIP X-Git-Tag: 2.0.0~5 X-Git-Url: https://git.r.bdr.sh/rbdr/lyricli/commitdiff_plain/1b8bdf0f82d6273dc39a67ac579d34d5b0d7d21f?ds=sidebyside;hp=c96090328d49fddfe0cc22609b3f97250502c15b Save WIP --- diff --git a/Sources/lyricli/lyrics_engine.swift b/Sources/lyricli/lyrics_engine.swift index 085a61c..1a182d0 100644 --- a/Sources/lyricli/lyrics_engine.swift +++ b/Sources/lyricli/lyrics_engine.swift @@ -4,8 +4,10 @@ import HTMLEntities // Given a track, attempts to fetch the lyrics from lyricswiki class LyricsEngine { + private let clientToken = "_-P6qiz2dPDMaRUih-VxSS--PBYA4OtWrHiTgVY7Qd3lMss_oewL04FX8lmh37ma" + // URL of the API endpoint to use - private let apiURL = "https://lyrics.wikia.com/api.php?action=lyrics&func=getSong&fmt=realjson" + private let apiURL = "https://api.genius.com/search" // Method used to call the API private let apiMethod = "GET" @@ -25,7 +27,7 @@ class LyricsEngine { if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { if let name: String = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { - if let url = URL(string: "\(apiURL)&artist=\(artist)&song=\(name)") { + if let url = URL(string: "\(apiURL)&q=\(artist) \(name)") { // We'll lock until the async call is finished @@ -35,7 +37,7 @@ class LyricsEngine { // Call the API and unlock when you're done - fetchLyricsFromAPI(withURL: url, completionHandler: {lyricsResult -> Void in + searchLyricsUsingAPI(withURL: url, completionHandler: {lyricsResult -> Void in lyrics = lyricsResult requestFinished = true asyncLock.signal() @@ -60,7 +62,7 @@ class LyricsEngine { // Fetch the lyrics URL from the API, triggers the request to fetch the // lyrics page - private func fetchLyricsFromAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) { + private func searchLyricsUsingAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) { var apiRequest = URLRequest(url: url) apiRequest.httpMethod = "GET" @@ -73,12 +75,18 @@ class LyricsEngine { if let data = data { if let jsonResponse = try? JSONSerialization.jsonObject(with: data) { if let jsonResponse = jsonResponse as? [String: Any] { - if let lyricsUrlString = jsonResponse["url"] as? String { - if let lyricsUrl = URL(string: lyricsUrlString) { - - // At this point we have a valid wiki url - self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler) - return + if let hits = jsonResponse["hits"] as? [Any] { + if let firstHit = hits[0] as? [String: Any] { + if let firstHitData = firstHit["result"] as? [String: Any] { + if let lyricsUrlString = firstHitData["url"] as? String { + if let lyricsUrl = URL(string: lyricsUrlString) { + + // At this point we have a valid wiki url + self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler) + return + } + } + } } } }