-import Foundation
-import SwiftSoup
-
-// Given a track, attempts to fetch the lyrics from lyricswiki
-class LyricsEngine {
-
- private let clientToken = <GENIUS_CLIENT_TOKEN>
-
- // URL of the API endpoint to use
- private let apiURL = "https://api.genius.com/search"
-
- // Method used to call the API
- private let apiMethod = "GET"
-
- // The track we'll be looking for
- private let track: Track
-
- // Fetches the lyrics and returns if found
- var lyrics: String? {
-
- var lyrics: String?
-
- // Encode the track artist and name and finish building the API call URL
-
- if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
- if let name = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
-
- if let url = URL(string: "\(apiURL)?access_token=\(clientToken)&q=\(artist)%20\(name)") {
-
- // We'll lock until the async call is finished
-
- var requestFinished = false
- let asyncLock = NSCondition()
- asyncLock.lock()
-
- // Call the API and unlock when you're done
-
- searchLyricsUsingAPI(withURL: url, completionHandler: {lyricsResult -> Void in
- lyrics = lyricsResult
- requestFinished = true
- asyncLock.signal()
- })
-
- while !requestFinished {
- asyncLock.wait()
- }
- asyncLock.unlock()
- }
- }
- }
-
- return lyrics
- }
-
- // Initializes with a track
- init(withTrack targetTrack: Track) {
-
- track = targetTrack
- }
-
- // Fetch the lyrics URL from the API, triggers the request to fetch the
- // lyrics page
- private func searchLyricsUsingAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
-
- var apiRequest = URLRequest(url: url)
- apiRequest.httpMethod = "GET"
-
- let task = URLSession.shared.dataTask(with: apiRequest, completionHandler: {data, _, _ -> Void in
-
- // If the response is parseable JSON, and has a url, we'll look for
- // the lyrics in there
-
- if let data = data {
- if let jsonResponse = try? JSONSerialization.jsonObject(with: data) {
- if let jsonResponse = jsonResponse as? [String: Any] {
- if let response = jsonResponse["response"] as? [String: Any] {
- if let hits = response["hits"] as? [[String: Any]] {
- let filteredHits = hits.filter { $0["type"] as? String == "song" }
- if filteredHits.count > 0 {
- let firstHit = hits[0]
- 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
- }
- }
- }
- }
- }
- }
- }
- }
- }
-
- completionHandler(nil)
- })
- task.resume()
- }
-
- // Fetch the lyrics from the page and send it to the parser
- private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
-
- var pageRequest = URLRequest(url: url)
- pageRequest.httpMethod = "GET"
-
- let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, _, _ -> Void in
-
- // If the response is parseable JSON, and has a url, we'll look for
- // the lyrics in there
-
- if let data = data {
- if let htmlBody = String(data: data, encoding: String.Encoding.utf8) {
- self.parseHtmlBody(htmlBody, completionHandler: completionHandler)
- return
- }
- }
-
- completionHandler(nil)
- })
- task.resume()
- }
-
- // Parses the wiki to find the lyrics, decodes the lyrics object
- private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
-
- do {
- let document: Document = try SwiftSoup.parse(body)
- let lyricsBox = try document.select("div[data-lyrics-container=\"true\"]")
- try lyricsBox.select("br").after("\\n")
- let lyrics = try lyricsBox.text()
- completionHandler(lyrics.replacingOccurrences(of: "\\n", with: "\r\n"))
- } catch {
- completionHandler(nil)
- }
- }
-}