4 /// Looks for lyrics on the internet
7 private let apiURL = "https://lyrics.wikia.com/api.php?action=lyrics&func=getSong&fmt=realjson"
8 private let apiMethod = "GET"
9 private let lyricsMatcher = "class='lyricbox'>(.+)<div"
11 private let track: Track
13 // Fetches the lyrics and returns if found
20 if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
21 if let name: String = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
22 if let url = URL(string: "\(apiURL)&artist=\(artist)&song=\(name)") {
24 // We'll lock until the async call is finished
26 var requestFinished = false
27 let asyncLock = NSCondition()
30 // Call the API and unlock when you're done
32 fetchLyricsFromAPI(withURL: url, completionHandler: {lyricsResult -> Void in
33 if let lyricsResult = lyricsResult {
35 requestFinished = true
40 while(!requestFinished) {
52 init(withTrack targetTrack: Track) {
57 // Fetch the lyrics from the API and request / parse the page
59 private func fetchLyricsFromAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
61 var apiRequest = URLRequest(url: url)
62 apiRequest.httpMethod = "GET"
64 let task = URLSession.shared.dataTask(with: apiRequest, completionHandler: {data, response, error -> Void in
66 // If the response is parseable JSON, and has a url, we'll look for
67 // the lyrics in there
70 let jsonResponse = try? JSONSerialization.jsonObject(with: data) as! [String: Any]
71 if let jsonResponse = jsonResponse {
72 if let lyricsUrlString = jsonResponse["url"] as? String {
73 if let lyricsUrl = URL(string: lyricsUrlString) {
75 // At this point we have a valid wiki url
76 self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler)
83 completionHandler(nil)
88 // Fetch the lyrics from the page and parse the page
90 private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
92 var pageRequest = URLRequest(url: url)
93 pageRequest.httpMethod = "GET"
95 let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, response, error -> Void in
97 // If the response is parseable JSON, and has a url, we'll look for
98 // the lyrics in there
101 if let htmlBody = String(data: data, encoding: String.Encoding.utf8) {
102 self.parseHtmlBody(htmlBody, completionHandler: completionHandler)
107 completionHandler(nil)
112 // Parses the wiki to obtain the lyrics
114 private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
116 if let regex = try? NSRegularExpression(pattern: lyricsMatcher) {
117 let matches = regex.matches(in: body, range: NSRange(location: 0, length: body.characters.count))
119 for match in matches {
121 let nsBody = body as NSString
122 let range = match.rangeAt(1)
123 let encodedLyrics = nsBody.substring(with: range)
125 let decodedLyrics = decodeLyrics(encodedLyrics)
127 completionHandler(decodedLyrics)
132 completionHandler(nil)
135 // Escapes the HTML entities
137 private func decodeLyrics(_ lyrics: String) -> String {
139 let unescapedLyrics = lyrics.htmlUnescape()
140 return unescapedLyrics.replacingOccurrences(of: "<br />", with: "\n")