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