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
18 if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
19 if let name: String = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
20 if let url = URL(string: "\(apiURL)&artist=\(artist)&song=\(name)") {
22 // We'll lock until the async call is finished
24 var requestFinished = false
25 let asyncLock = NSCondition()
28 // Call the API and unlock when you're done
30 fetchLyricsFromAPI(withURL: url, completionHandler: {lyricsResult -> Void in
31 if let lyricsResult = lyricsResult {
33 requestFinished = true
38 while !requestFinished {
49 init(withTrack targetTrack: Track) {
54 // Fetch the lyrics from the API and request / parse the page
56 private func fetchLyricsFromAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
58 var apiRequest = URLRequest(url: url)
59 apiRequest.httpMethod = "GET"
61 let task = URLSession.shared.dataTask(with: apiRequest, completionHandler: {data, _, _ -> Void in
63 // If the response is parseable JSON, and has a url, we'll look for
64 // the lyrics in there
67 if let jsonResponse = try? JSONSerialization.jsonObject(with: data) {
68 if let jsonResponse = jsonResponse as? [String: Any] {
69 if let lyricsUrlString = jsonResponse["url"] as? String {
70 if let lyricsUrl = URL(string: lyricsUrlString) {
72 // At this point we have a valid wiki url
73 self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler)
81 completionHandler(nil)
86 // Fetch the lyrics from the page and parse the page
88 private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
90 var pageRequest = URLRequest(url: url)
91 pageRequest.httpMethod = "GET"
93 let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, _, _ -> Void in
95 // If the response is parseable JSON, and has a url, we'll look for
96 // the lyrics in there
99 if let htmlBody = String(data: data, encoding: String.Encoding.utf8) {
100 self.parseHtmlBody(htmlBody, completionHandler: completionHandler)
105 completionHandler(nil)
110 // Parses the wiki to obtain the lyrics
112 private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
114 if let regex = try? NSRegularExpression(pattern: lyricsMatcher) {
115 let matches = regex.matches(in: body, range: NSRange(location: 0, length: body.characters.count))
117 for match in matches {
119 let nsBody = body as NSString
120 let range = match.rangeAt(1)
121 let encodedLyrics = nsBody.substring(with: range)
123 let decodedLyrics = decodeLyrics(encodedLyrics)
125 completionHandler(decodedLyrics)
130 completionHandler(nil)
133 // Escapes the HTML entities
135 private func decodeLyrics(_ lyrics: String) -> String {
137 let unescapedLyrics = lyrics.htmlUnescape()
138 return unescapedLyrics.replacingOccurrences(of: "<br />", with: "\n")