4 // Given a track, attempts to fetch the lyrics from lyricswiki
7 private let clientToken = "_-P6qiz2dPDMaRUih-VxSS--PBYA4OtWrHiTgVY7Qd3lMss_oewL04FX8lmh37ma"
9 // URL of the API endpoint to use
10 private let apiURL = "https://api.genius.com/search"
12 // Method used to call the API
13 private let apiMethod = "GET"
15 // Regular expxression used to find the lyrics in the lyricswiki HTML
16 private let lyricsMatcher = "class='lyricbox'>(.+)<div"
18 // The track we'll be looking for
19 private let track: Track
21 // Fetches the lyrics and returns if found
26 // Encode the track artist and name and finish building the API call URL
28 if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
29 if let name: String = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
30 if let url = URL(string: "\(apiURL)&q=\(artist) \(name)") {
32 // We'll lock until the async call is finished
34 var requestFinished = false
35 let asyncLock = NSCondition()
38 // Call the API and unlock when you're done
40 searchLyricsUsingAPI(withURL: url, completionHandler: {lyricsResult -> Void in
42 requestFinished = true
46 while !requestFinished {
57 // Initializes with a track
58 init(withTrack targetTrack: Track) {
63 // Fetch the lyrics URL from the API, triggers the request to fetch the
65 private func searchLyricsUsingAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
67 var apiRequest = URLRequest(url: url)
68 apiRequest.httpMethod = "GET"
70 let task = URLSession.shared.dataTask(with: apiRequest, completionHandler: {data, _, _ -> Void in
72 // If the response is parseable JSON, and has a url, we'll look for
73 // the lyrics in there
76 if let jsonResponse = try? JSONSerialization.jsonObject(with: data) {
77 if let jsonResponse = jsonResponse as? [String: Any] {
78 if let hits = jsonResponse["hits"] as? [Any] {
79 if let firstHit = hits[0] as? [String: Any] {
80 if let firstHitData = firstHit["result"] as? [String: Any] {
81 if let lyricsUrlString = firstHitData["url"] as? String {
82 if let lyricsUrl = URL(string: lyricsUrlString) {
84 // At this point we have a valid wiki url
85 self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler)
96 completionHandler(nil)
101 // Fetch the lyrics from the page and send it to the parser
102 private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
104 var pageRequest = URLRequest(url: url)
105 pageRequest.httpMethod = "GET"
107 let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, _, _ -> Void in
109 // If the response is parseable JSON, and has a url, we'll look for
110 // the lyrics in there
113 if let htmlBody = String(data: data, encoding: String.Encoding.utf8) {
114 self.parseHtmlBody(htmlBody, completionHandler: completionHandler)
119 completionHandler(nil)
124 // Parses the wiki to find the lyrics, decodes the lyrics object
125 private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
127 // Look for the lyrics lightbox
129 if let regex = try? NSRegularExpression(pattern: lyricsMatcher) {
130 let matches = regex.matches(in: body, range: NSRange(location: 0, length: body.count))
132 for match in matches {
134 let nsBody = body as NSString
135 let range = match.range(at: 1)
136 let encodedLyrics = nsBody.substring(with: range)
138 let decodedLyrics = decodeLyrics(encodedLyrics)
140 completionHandler(decodedLyrics)
145 completionHandler(nil)
148 // Escapes the HTML entities
149 private func decodeLyrics(_ lyrics: String) -> String {
151 let unescapedLyrics = lyrics.htmlUnescape()
152 return unescapedLyrics.replacingOccurrences(of: "<br />", with: "\n")