4 // Given a track, attempts to fetch the lyrics from lyricswiki
7 // URL of the API endpoint to use
8 private let apiURL = "https://lyrics.wikia.com/api.php?action=lyrics&func=getSong&fmt=realjson"
10 // Method used to call the API
11 private let apiMethod = "GET"
13 // Regular expxression used to find the lyrics in the lyricswiki HTML
14 private let lyricsMatcher = "class='lyricbox'>(.+)<div"
16 // The track we'll be looking for
17 private let track: Track
19 // Fetches the lyrics and returns if found
24 // Encode the track artist and name and finish building the API call URL
26 if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
27 if let name: String = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
28 if let url = URL(string: "\(apiURL)&artist=\(artist)&song=\(name)") {
30 // We'll lock until the async call is finished
32 var requestFinished = false
33 let asyncLock = NSCondition()
36 // Call the API and unlock when you're done
38 fetchLyricsFromAPI(withURL: url, completionHandler: {lyricsResult -> Void in
39 if let lyricsResult = lyricsResult {
41 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 fetchLyricsFromAPI(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 lyricsUrlString = jsonResponse["url"] as? String {
79 if let lyricsUrl = URL(string: lyricsUrlString) {
81 // At this point we have a valid wiki url
82 self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler)
90 completionHandler(nil)
95 // Fetch the lyrics from the page and send it to the parser
96 private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
98 var pageRequest = URLRequest(url: url)
99 pageRequest.httpMethod = "GET"
101 let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, _, _ -> Void in
103 // If the response is parseable JSON, and has a url, we'll look for
104 // the lyrics in there
107 if let htmlBody = String(data: data, encoding: String.Encoding.utf8) {
108 self.parseHtmlBody(htmlBody, completionHandler: completionHandler)
113 completionHandler(nil)
118 // Parses the wiki to find the lyrics, decodes the lyrics object
119 private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
121 // Look for the lyrics lightbox
123 if let regex = try? NSRegularExpression(pattern: lyricsMatcher) {
124 let matches = regex.matches(in: body, range: NSRange(location: 0, length: body.characters.count))
126 for match in matches {
128 let nsBody = body as NSString
129 let range = match.rangeAt(1)
130 let encodedLyrics = nsBody.substring(with: range)
132 let decodedLyrics = decodeLyrics(encodedLyrics)
134 completionHandler(decodedLyrics)
139 completionHandler(nil)
142 // Escapes the HTML entities
143 private func decodeLyrics(_ lyrics: String) -> String {
145 let unescapedLyrics = lyrics.htmlUnescape()
146 return unescapedLyrics.replacingOccurrences(of: "<br />", with: "\n")