]> git.r.bdr.sh - rbdr/lyricli/blob - Sources/lyricli/lyrics_engine.swift
e0752d77ebb20de9c0f7e2896ff5c57a55565b5e
[rbdr/lyricli] / Sources / lyricli / lyrics_engine.swift
1 import Foundation
2 import SwiftSoup
3
4 // Given a track, attempts to fetch the lyrics from lyricswiki
5 class LyricsEngine {
6
7 private let clientToken = <GENIUS_CLIENT_TOKEN>
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 // The track we'll be looking for
16 private let track: Track
17
18 // Fetches the lyrics and returns if found
19 var lyrics: String? {
20
21 var lyrics: String?
22
23 // Encode the track artist and name and finish building the API call URL
24
25 if let artist = track.artist.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
26 if let name = track.name.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
27
28 if let url = URL(string: "\(apiURL)?access_token=\(clientToken)&q=\(artist)%20\(name)") {
29
30 // We'll lock until the async call is finished
31
32 var requestFinished = false
33 let asyncLock = NSCondition()
34 asyncLock.lock()
35
36 // Call the API and unlock when you're done
37
38 searchLyricsUsingAPI(withURL: url, completionHandler: {lyricsResult -> Void in
39 lyrics = lyricsResult
40 requestFinished = true
41 asyncLock.signal()
42 })
43
44 while !requestFinished {
45 asyncLock.wait()
46 }
47 asyncLock.unlock()
48 }
49 }
50 }
51
52 return lyrics
53 }
54
55 // Initializes with a track
56 init(withTrack targetTrack: Track) {
57
58 track = targetTrack
59 }
60
61 // Fetch the lyrics URL from the API, triggers the request to fetch the
62 // lyrics page
63 private func searchLyricsUsingAPI(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
64
65 var apiRequest = URLRequest(url: url)
66 apiRequest.httpMethod = "GET"
67
68 let task = URLSession.shared.dataTask(with: apiRequest, completionHandler: {data, _, _ -> Void in
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 {
74 if let jsonResponse = try? JSONSerialization.jsonObject(with: data) {
75 if let jsonResponse = jsonResponse as? [String: Any] {
76 if let response = jsonResponse["response"] as? [String: Any] {
77 if let hits = response["hits"] as? [[String: Any]] {
78 let filteredHits = hits.filter { $0["type"] as? String == "song" }
79 if filteredHits.count > 0 {
80 let firstHit = hits[0]
81 if let firstHitData = firstHit["result"] as? [String: Any] {
82 if let lyricsUrlString = firstHitData["url"] as? String {
83 if let lyricsUrl = URL(string: lyricsUrlString) {
84
85 // At this point we have a valid wiki url
86 self.fetchLyricsFromPage(
87 withURL: lyricsUrl,
88 completionHandler: completionHandler
89 )
90 return
91 }
92 }
93 }
94 }
95 }
96 }
97 }
98 }
99 }
100
101 completionHandler(nil)
102 })
103 task.resume()
104 }
105
106 // Fetch the lyrics from the page and send it to the parser
107 private func fetchLyricsFromPage(withURL url: URL, completionHandler: @escaping (String?) -> Void) {
108
109 var pageRequest = URLRequest(url: url)
110 pageRequest.httpMethod = "GET"
111
112 let task = URLSession.shared.dataTask(with: pageRequest, completionHandler: {data, _, _ -> Void in
113
114 // If the response is parseable JSON, and has a url, we'll look for
115 // the lyrics in there
116
117 if let data = data {
118 if let htmlBody = String(data: data, encoding: String.Encoding.utf8) {
119 self.parseHtmlBody(htmlBody, completionHandler: completionHandler)
120 return
121 }
122 }
123
124 completionHandler(nil)
125 })
126 task.resume()
127 }
128
129 // Parses the wiki to find the lyrics, decodes the lyrics object
130 private func parseHtmlBody(_ body: String, completionHandler: @escaping (String?) -> Void) {
131
132 do {
133 let document: Document = try SwiftSoup.parse(body)
134 let lyricsBox = try document.select("div[data-lyrics-container=\"true\"]")
135 try lyricsBox.select("br").after("\\n")
136 let lyrics = try lyricsBox.text()
137 completionHandler(lyrics.replacingOccurrences(of: "\\n", with: "\r\n"))
138 } catch {
139 completionHandler(nil)
140 }
141 }
142 }