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