From 3a398bc031f1a1659073208e83d778a357a8243a Mon Sep 17 00:00:00 2001 From: Ruben Beltran del Rio Date: Mon, 10 Apr 2023 15:00:55 +0200 Subject: Use swiftsoup for parsing --- Sources/lyricli/lyrics_engine.swift | 67 ++++++++++++++----------------------- 1 file changed, 26 insertions(+), 41 deletions(-) (limited to 'Sources') diff --git a/Sources/lyricli/lyrics_engine.swift b/Sources/lyricli/lyrics_engine.swift index f0a02db..620e521 100644 --- a/Sources/lyricli/lyrics_engine.swift +++ b/Sources/lyricli/lyrics_engine.swift @@ -1,4 +1,5 @@ import Foundation +import SwiftSoup // Given a track, attempts to fetch the lyrics from lyricswiki class LyricsEngine { @@ -11,9 +12,6 @@ class LyricsEngine { // 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'>(.+) 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.count)) - - for match in matches { - - let nsBody = body as NSString - let range = match.range(at: 1) - let encodedLyrics = nsBody.substring(with: range) - - let decodedLyrics = decodeLyrics(encodedLyrics) - - completionHandler(decodedLyrics) - return - } + do { + let document: Document = try SwiftSoup.parse(body) + let lyricsBox = try document.select("div[data-lyrics-container=\"true\"]") + try lyricsBox.select("br").after("\\n") + let lyrics = try lyricsBox.text() + completionHandler(lyrics.replacingOccurrences(of: "\\n", with: "\r\n")) + } catch { + completionHandler(nil) } - - completionHandler(nil) - } - - // Escapes the HTML entities and HTML - private func decodeLyrics(_ lyrics: String) -> String { - - return lyrics } } -- cgit