import Foundation
import HTMLEntities
-/// Looks for lyrics on the internet
+// Given a track, attempts to fetch the lyrics from lyricswiki
class LyricsEngine {
+ // URL of the API endpoint to use
private let apiURL = "https://lyrics.wikia.com/api.php?action=lyrics&func=getSong&fmt=realjson"
+
+ // Method used to call the API
private let apiMethod = "GET"
+
+ // Regular expxression used to find the lyrics in the lyricswiki HTML
private let lyricsMatcher = "class='lyricbox'>(.+)<div"
+ // The track we'll be looking for
private let track: Track
// Fetches the lyrics and returns if found
-
var lyrics: String? {
+
var lyrics: String?
+ // Encode the track artist and name and finish building the API call URL
+
if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
if let name: String = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
if let url = URL(string: "\(apiURL)&artist=\(artist)&song=\(name)") {
return lyrics
}
+ // Initializes with a track
init(withTrack targetTrack: Track) {
track = targetTrack
}
- // Fetch the lyrics from the API and request / parse the page
-
+ // Fetch the lyrics URL from the API, triggers the request to fetch the
+ // lyrics page
private func fetchLyricsFromAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
var apiRequest = URLRequest(url: url)
task.resume()
}
- // Fetch the lyrics from the page and parse the page
-
+ // Fetch the lyrics from the page and send it to the parser
private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
var pageRequest = URLRequest(url: url)
task.resume()
}
- // Parses the wiki to obtain the lyrics
-
+ // Parses the wiki to find the lyrics, decodes the lyrics object
private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
+ // Look for the lyrics lightbox
+
if let regex = try? NSRegularExpression(pattern: lyricsMatcher) {
let matches = regex.matches(in: body, range: NSRange(location: 0, length: body.characters.count))
}
// Escapes the HTML entities
-
private func decodeLyrics(_ lyrics: String) -> String {
let unescapedLyrics = lyrics.htmlUnescape()