]> git.r.bdr.sh - rbdr/lyricli/blame - Sources/lyrics_engine.swift
Improve comments in code
[rbdr/lyricli] / Sources / lyrics_engine.swift
CommitLineData
85d0536f
BB
1import Foundation
2import HTMLEntities
3
d852b84e 4// Given a track, attempts to fetch the lyrics from lyricswiki
a968bff7
BB
5class 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
BB
38 fetchLyricsFromAPI(withURL: url, completionHandler: {lyricsResult -> Void in
39 if let lyricsResult = lyricsResult {
40 lyrics = lyricsResult
41 requestFinished = true
42 asyncLock.signal()
85d0536f 43 }
1263f62c
BB
44 })
45
46 while !requestFinished {
47 asyncLock.wait()
85d0536f 48 }
1263f62c 49 asyncLock.unlock()
85d0536f 50 }
a968bff7 51 }
a968bff7 52 }
1263f62c
BB
53
54 return lyrics
a968bff7
BB
55 }
56
d852b84e 57 // Initializes with a track
a968bff7
BB
58 init(withTrack targetTrack: Track) {
59
60 track = targetTrack
61 }
85d0536f 62
d852b84e
BB
63 // Fetch the lyrics URL from the API, triggers the request to fetch the
64 // lyrics page
85d0536f
BB
65 private func fetchLyricsFromAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
66
67 var apiRequest = URLRequest(url: url)
68 apiRequest.httpMethod = "GET"
69
1263f62c 70 let task = URLSession.shared.dataTask(with: apiRequest, completionHandler: {data, _, _ -> Void in
85d0536f
BB
71
72 // If the response is parseable JSON, and has a url, we'll look for
73 // the lyrics in there
74
75 if let data = data {
1263f62c
BB
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) {
80
81 // At this point we have a valid wiki url
82 self.fetchLyricsFromPage(withURL: lyricsUrl, completionHandler: completionHandler)
83 return
84 }
85d0536f
BB
85 }
86 }
87 }
88 }
89
90 completionHandler(nil)
91 })
92 task.resume()
93 }
94
d852b84e 95 // Fetch the lyrics from the page and send it to the parser
85d0536f
BB
96 private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
97
98 var pageRequest = URLRequest(url: url)
99 pageRequest.httpMethod = "GET"
100
1263f62c 101 let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, _, _ -> Void in
85d0536f
BB
102
103 // If the response is parseable JSON, and has a url, we'll look for
104 // the lyrics in there
105
106 if let data = data {
107 if let htmlBody = String(data: data, encoding: String.Encoding.utf8) {
108 self.parseHtmlBody(htmlBody, completionHandler: completionHandler)
109 return
110 }
111 }
112
113 completionHandler(nil)
114 })
115 task.resume()
116 }
117
d852b84e 118 // Parses the wiki to find the lyrics, decodes the lyrics object
85d0536f
BB
119 private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
120
d852b84e
BB
121 // Look for the lyrics lightbox
122
85d0536f
BB
123 if let regex = try? NSRegularExpression(pattern: lyricsMatcher) {
124 let matches = regex.matches(in: body, range: NSRange(location: 0, length: body.characters.count))
125
126 for match in matches {
127
128 let nsBody = body as NSString
129 let range = match.rangeAt(1)
130 let encodedLyrics = nsBody.substring(with: range)
131
132 let decodedLyrics = decodeLyrics(encodedLyrics)
133
134 completionHandler(decodedLyrics)
135 return
136 }
137 }
138
139 completionHandler(nil)
140 }
141
142 // Escapes the HTML entities
85d0536f
BB
143 private func decodeLyrics(_ lyrics: String) -> String {
144
145 let unescapedLyrics = lyrics.htmlUnescape()
146 return unescapedLyrics.replacingOccurrences(of: "<br />", with: "\n")
147 }
a968bff7 148}