]>
Commit | Line | Data |
---|---|---|
85d0536f BB |
1 | import Foundation |
2 | import HTMLEntities | |
3 | ||
d852b84e | 4 | // Given a track, attempts to fetch the lyrics from lyricswiki |
a968bff7 BB |
5 | class LyricsEngine { |
6 | ||
d852b84e | 7 | // URL of the API endpoint to use |
85d0536f | 8 | private let apiURL = "https://lyrics.wikia.com/api.php?action=lyrics&func=getSong&fmt=realjson" |
d852b84e BB |
9 | |
10 | // Method used to call the API | |
85d0536f | 11 | private let apiMethod = "GET" |
d852b84e BB |
12 | |
13 | // Regular expxression used to find the lyrics in the lyricswiki HTML | |
85d0536f BB |
14 | private let lyricsMatcher = "class='lyricbox'>(.+)<div" |
15 | ||
d852b84e | 16 | // The track we'll be looking for |
85d0536f BB |
17 | private let track: Track |
18 | ||
19 | // Fetches the lyrics and returns if found | |
a968bff7 | 20 | var lyrics: String? { |
d852b84e | 21 | |
1263f62c | 22 | var lyrics: String? |
85d0536f | 23 | |
d852b84e BB |
24 | // Encode the track artist and name and finish building the API call URL |
25 | ||
1263f62c BB |
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)") { | |
85d0536f | 29 | |
1263f62c | 30 | // We'll lock until the async call is finished |
85d0536f | 31 | |
1263f62c BB |
32 | var requestFinished = false |
33 | let asyncLock = NSCondition() | |
34 | asyncLock.lock() | |
85d0536f | 35 | |
1263f62c | 36 | // Call the API and unlock when you're done |
85d0536f | 37 | |
1263f62c | 38 | fetchLyricsFromAPI(withURL: url, completionHandler: {lyricsResult -> Void in |
d0705bff BB |
39 | lyrics = lyricsResult |
40 | requestFinished = true | |
41 | asyncLock.signal() | |
1263f62c BB |
42 | }) |
43 | ||
44 | while !requestFinished { | |
45 | asyncLock.wait() | |
85d0536f | 46 | } |
1263f62c | 47 | asyncLock.unlock() |
85d0536f | 48 | } |
a968bff7 | 49 | } |
a968bff7 | 50 | } |
1263f62c BB |
51 | |
52 | return lyrics | |
a968bff7 BB |
53 | } |
54 | ||
d852b84e | 55 | // Initializes with a track |
a968bff7 BB |
56 | init(withTrack targetTrack: Track) { |
57 | ||
58 | track = targetTrack | |
59 | } | |
85d0536f | 60 | |
d852b84e BB |
61 | // Fetch the lyrics URL from the API, triggers the request to fetch the |
62 | // lyrics page | |
85d0536f BB |
63 | private func fetchLyricsFromAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) { |
64 | ||
65 | var apiRequest = URLRequest(url: url) | |
66 | apiRequest.httpMethod = "GET" | |
67 | ||
1263f62c | 68 | let task = URLSession.shared.dataTask(with: apiRequest, completionHandler: {data, _, _ -> Void in |
85d0536f BB |
69 | |
70 | // If the response is parseable JSON, and has a url, we'll look for | |
71 | // the lyrics in there | |
72 | ||
73 | if let data = data { | |
1263f62c BB |
74 | if let jsonResponse = try? JSONSerialization.jsonObject(with: data) { |
75 | if let jsonResponse = jsonResponse as? [String: Any] { | |
76 | if let lyricsUrlString = jsonResponse["url"] as? String { | |
77 | if let lyricsUrl = URL(string: lyricsUrlString) { | |
78 | ||
79 | // At this point we have a valid wiki url | |
80 | self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler) | |
81 | return | |
82 | } | |
85d0536f BB |
83 | } |
84 | } | |
85 | } | |
86 | } | |
87 | ||
88 | completionHandler(nil) | |
89 | }) | |
90 | task.resume() | |
91 | } | |
92 | ||
d852b84e | 93 | // Fetch the lyrics from the page and send it to the parser |
85d0536f BB |
94 | private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) { |
95 | ||
96 | var pageRequest = URLRequest(url: url) | |
97 | pageRequest.httpMethod = "GET" | |
98 | ||
1263f62c | 99 | let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, _, _ -> Void in |
85d0536f BB |
100 | |
101 | // If the response is parseable JSON, and has a url, we'll look for | |
102 | // the lyrics in there | |
103 | ||
104 | if let data = data { | |
105 | if let htmlBody = String(data: data, encoding: String.Encoding.utf8) { | |
106 | self.parseHtmlBody(htmlBody, completionHandler: completionHandler) | |
107 | return | |
108 | } | |
109 | } | |
110 | ||
111 | completionHandler(nil) | |
112 | }) | |
113 | task.resume() | |
114 | } | |
115 | ||
d852b84e | 116 | // Parses the wiki to find the lyrics, decodes the lyrics object |
85d0536f BB |
117 | private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) { |
118 | ||
d852b84e BB |
119 | // Look for the lyrics lightbox |
120 | ||
85d0536f | 121 | if let regex = try? NSRegularExpression(pattern: lyricsMatcher) { |
fdafe0d4 | 122 | let matches = regex.matches(in: body, range: NSRange(location: 0, length: body.count)) |
85d0536f BB |
123 | |
124 | for match in matches { | |
125 | ||
126 | let nsBody = body as NSString | |
fdafe0d4 | 127 | let range = match.range(at: 1) |
85d0536f BB |
128 | let encodedLyrics = nsBody.substring(with: range) |
129 | ||
130 | let decodedLyrics = decodeLyrics(encodedLyrics) | |
131 | ||
132 | completionHandler(decodedLyrics) | |
133 | return | |
134 | } | |
135 | } | |
136 | ||
137 | completionHandler(nil) | |
138 | } | |
139 | ||
140 | // Escapes the HTML entities | |
85d0536f BB |
141 | private func decodeLyrics(_ lyrics: String) -> String { |
142 | ||
143 | let unescapedLyrics = lyrics.htmlUnescape() | |
144 | return unescapedLyrics.replacingOccurrences(of: "<br />", with: "\n") | |
145 | } | |
a968bff7 | 146 | } |