import Foundation struct LyricsLine: Identifiable, Hashable { let id: Int /// Start time in seconds, or nil when the track only has plain text. let time: Double? let text: String var isBlank: Bool { text.trimmingCharacters(in: .whitespaces).isEmpty } } struct Lyrics: Equatable { let lines: [LyricsLine] let synced: Bool let writers: [String] static func == (lhs: Lyrics, rhs: Lyrics) -> Bool { lhs.synced == rhs.synced && lhs.lines == rhs.lines } /// Index of the line that should be highlighted at `time`. func activeIndex(at time: Double) -> Int? { guard synced else { return nil } var result: Int? for line in lines { guard let start = line.time else { continue } if start <= time + 0.15 { result = line.id } else { break } } return result } } enum LyricsService { /// Signing key taken from the Android client; unrelated to the web player key. private static let signKey = "p93jhgh689SBReK6ghtw62" /// Timed LRC only. A track whose lyrics carry no timestamps is treated as /// having none. static func load(trackID: String) async throws -> Lyrics { let lyrics = try await fetch(trackID: trackID, format: "LRC") guard lyrics.synced else { throw YMError.message("lyrics are not timed") } return lyrics } private static func fetch(trackID: String, format: String) async throws -> Lyrics { // The signature uses the bare numeric id, without any ":album" suffix. let numericID = trackID.split(separator: ":").first.map(String.init) ?? trackID let timestamp = String(Int(Date().timeIntervalSince1970)) let sign = Crypto.hmacSHA256Base64( message: numericID + timestamp, key: signKey, stripPadding: false ) let meta = try await YMClient.shared.lyrics( trackID: numericID, query: ["format": format, "timeStamp": timestamp, "sign": sign] ) guard let urlString = meta.downloadUrl, let url = URL(string: urlString) else { throw YMError.message("У трека нет текста") } let data = try await YMClient.shared.fetchPlain(url) guard let text = String(data: data, encoding: .utf8), !text.isEmpty else { throw YMError.message("Пустой текст") } return parse(text, writers: meta.writers ?? []) } static func parse(_ raw: String, writers: [String]) -> Lyrics { var timed: [(Double, String)] = [] var plain: [String] = [] for rawLine in raw.components(separatedBy: .newlines) { let line = rawLine.trimmingCharacters(in: .whitespaces) if line.isEmpty { plain.append("") continue } let stamps = timestamps(in: line) if stamps.isEmpty { // Skip LRC metadata tags like [ar:...] but keep real lyric lines. if line.hasPrefix("["), line.hasSuffix("]"), line.contains(":") { continue } plain.append(line) } else { let text = line.replacingOccurrences( of: "\\[\\d+:\\d+(?:[.:]\\d+)?\\]", with: "", options: .regularExpression ).trimmingCharacters(in: .whitespaces) for stamp in stamps { timed.append((stamp, text)) } } } if !timed.isEmpty { let sorted = timed.sorted { $0.0 < $1.0 } return Lyrics( lines: sorted.enumerated().map { LyricsLine(id: $0.offset, time: $0.element.0, text: $0.element.1) }, synced: true, writers: writers ) } // Collapse runs of blank lines so plain text does not sprawl. var compact: [String] = [] for line in plain where !(line.isEmpty && compact.last?.isEmpty == true) { compact.append(line) } return Lyrics( lines: compact.enumerated().map { LyricsLine(id: $0.offset, time: nil, text: $0.element) }, synced: false, writers: writers ) } private static func timestamps(in line: String) -> [Double] { let pattern = try! NSRegularExpression(pattern: "\\[(\\d+):(\\d+)(?:[.:](\\d+))?\\]") let range = NSRange(line.startIndex ..< line.endIndex, in: line) return pattern.matches(in: line, range: range).compactMap { match in func group(_ index: Int) -> Double? { guard let r = Range(match.range(at: index), in: line) else { return nil } return Double(line[r]) } guard let minutes = group(1), let seconds = group(2) else { return nil } var total = minutes * 60 + seconds if let fraction = group(3) { let digits = String(Int(fraction)).count total += fraction / pow(10, Double(max(digits, 1))) } return total } } }