Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Metadata/Models.swift3// Description: Value types shared by every layer: artists, albums, tracks, playlists, lyrics, formatting helpers.4import Foundation56// Value types shared by every layer. Identifiers are the server's UUIDs, lower-cased, kept as strings.78public struct Artist: Identifiable, Hashable, Sendable {9 public var id: String10 public var name: String11 public var albumCount: Int12 public var trackCount: Int13 public var artworkID: String?14}1516public struct Album: Identifiable, Hashable, Sendable {17 public var id: String18 public var title: String19 public var year: Int?20 public var artworkID: String?21 public var artistID: String22 public var artistName: String23 public var genre: String?24 public var createdAt: Date25 public var trackCount: Int26 public var durationMs: Int27 public var favorite: Bool28 /// Number of the album's tracks whose file is on this Mac.29 public var downloadedCount: Int30 public var isFullyDownloaded: Bool { trackCount > 0 && downloadedCount >= trackCount }31}3233public enum DownloadState: String, Sendable, Codable {34 case queued, downloading, paused, failed, done35}3637public struct Track: Identifiable, Hashable, Sendable {38 public var id: String39 public var title: String40 public var trackNo: Int?41 public var discNo: Int42 public var durationMs: Int43 public var year: Int?44 public var codec: String45 public var container: String46 public var sampleRate: Int?47 public var bitDepth: Int?48 public var channels: Int?49 public var bitrate: Int?50 public var artistID: String51 public var artistName: String52 public var albumID: String53 public var albumTitle: String54 public var albumArtistName: String55 public var artworkID: String?56 public var genre: String?57 public var lyricsState: String?58 /// The original file on the cluster: identity (changes when the file is replaced), checksum, size.59 public var assetID: String?60 public var sha256: String?61 public var sizeBytes: Int6462 public var mime: String?63 public var hasCompatRendition: Bool64 /// Size of the AAC rendition the cluster keeps for codecs Core Audio cannot decode (Ogg, DSD); nil when there is none.65 public var compatSizeBytes: Int64?66 public var favorite: Bool67 public var downloadState: DownloadState?68 /// Path of the downloaded file relative to the library folder; set when `downloadState == .done`.69 public var localRelativePath: String?70 /// The track no longer exists on the cluster but its downloaded file was kept.71 public var removedRemotely: Bool72 /// A file opened from disk, outside the library (Open With, drag and drop).73 public var externalFileURL: URL?7475 /// Codecs Core Audio does not decode: these are streamed through the cluster's AAC rendition.76 public var needsCompatRendition: Bool { let c = codec.lowercased(); return c == "vorbis" || c == "opus" || c.hasPrefix("dsd") }77 public var isDownloaded: Bool { downloadState == .done && localRelativePath != nil }7879 public init(id: String, title: String, trackNo: Int? = nil, discNo: Int = 1, durationMs: Int = 0, year: Int? = nil, codec: String = "", container: String = "",80 sampleRate: Int? = nil, bitDepth: Int? = nil, channels: Int? = nil, bitrate: Int? = nil, artistID: String = "", artistName: String = "",81 albumID: String = "", albumTitle: String = "", albumArtistName: String = "", artworkID: String? = nil, genre: String? = nil, lyricsState: String? = nil,82 assetID: String? = nil, sha256: String? = nil, sizeBytes: Int64 = 0, mime: String? = nil, hasCompatRendition: Bool = false, compatSizeBytes: Int64? = nil, favorite: Bool = false,83 downloadState: DownloadState? = nil, localRelativePath: String? = nil, removedRemotely: Bool = false, externalFileURL: URL? = nil) {84 self.id = id; self.title = title; self.trackNo = trackNo; self.discNo = discNo; self.durationMs = durationMs; self.year = year; self.codec = codec; self.container = container85 self.sampleRate = sampleRate; self.bitDepth = bitDepth; self.channels = channels; self.bitrate = bitrate; self.artistID = artistID; self.artistName = artistName86 self.albumID = albumID; self.albumTitle = albumTitle; self.albumArtistName = albumArtistName; self.artworkID = artworkID; self.genre = genre; self.lyricsState = lyricsState87 self.assetID = assetID; self.sha256 = sha256; self.sizeBytes = sizeBytes; self.mime = mime; self.hasCompatRendition = hasCompatRendition; self.compatSizeBytes = compatSizeBytes; self.favorite = favorite88 self.downloadState = downloadState; self.localRelativePath = localRelativePath; self.removedRemotely = removedRemotely; self.externalFileURL = externalFileURL89 }90}9192public struct Playlist: Identifiable, Hashable, Sendable {93 public var id: String94 public var name: String95 public var updatedAt: Date96 public var trackCount: Int97 public var artworkIDs: [String]98 public var downloadedCount: Int99 /// Created on this Mac and not yet known to the cluster.100 public var pendingCreation: Bool101 /// Kept offline: tracks added to it later are downloaded too.102 public var pinned: Bool103}104105public struct PlaylistEntry: Identifiable, Hashable, Sendable {106 public var id: String // entry id (server's, or "local-…" until synchronised)107 public var track: Track108}109110public struct Account: Codable, Hashable, Sendable {111 public var id: String112 public var email: String113 public var displayName: String114 public var role: String115 public var isOwner: Bool116 public var isAdmin: Bool { role == "admin" }117 public init(id: String, email: String, displayName: String, role: String, isOwner: Bool) { self.id = id; self.email = email; self.displayName = displayName; self.role = role; self.isOwner = isOwner }118}119120public struct LyricLine: Codable, Hashable, Sendable {121 public var t: Int122 public var e: Int123 public var text: String124 public var words: [Word]?125 public struct Word: Hashable, Sendable { public var start: Int; public var end: Int; public var text: String }126127 enum CodingKeys: String, CodingKey { case t, e, text, w }128 public init(t: Int, e: Int, text: String, words: [Word]? = nil) { self.t = t; self.e = e; self.text = text; self.words = words }129 public init(from decoder: Decoder) throws {130 let c = try decoder.container(keyedBy: CodingKeys.self)131 t = try c.decode(Int.self, forKey: .t); e = try c.decode(Int.self, forKey: .e); text = try c.decode(String.self, forKey: .text)132 if var arr = try? c.nestedUnkeyedContainer(forKey: .w) {133 var out: [Word] = []134 while !arr.isAtEnd {135 var w = try arr.nestedUnkeyedContainer()136 let s = try w.decode(Int.self), en = try w.decode(Int.self), tx = try w.decode(String.self)137 out.append(Word(start: s, end: en, text: tx))138 }139 words = out140 } else { words = nil }141 }142 public func encode(to encoder: Encoder) throws {143 var c = encoder.container(keyedBy: CodingKeys.self)144 try c.encode(t, forKey: .t); try c.encode(e, forKey: .e); try c.encode(text, forKey: .text)145 if let words {146 var arr = c.nestedUnkeyedContainer(forKey: .w)147 for w in words { var one = arr.nestedUnkeyedContainer(); try one.encode(w.start); try one.encode(w.end); try one.encode(w.text) }148 }149 }150}151152public struct Lyrics: Codable, Hashable, Sendable {153 public var state: String154 public var language: String?155 public var lines: [LyricLine]156}157158public struct PlayRecord: Hashable, Sendable, Codable {159 public var id: String160 public var trackID: String161 public var playedAt: Date162 public var listenedMs: Int163 public var completed: Bool164 public var source: String // "stream" | "local"165 public init(id: String, trackID: String, playedAt: Date, listenedMs: Int, completed: Bool, source: String) { self.id = id; self.trackID = trackID; self.playedAt = playedAt; self.listenedMs = listenedMs; self.completed = completed; self.source = source }166}167168public enum TextNorm {169 /// Lower-cased, accent-free form used for sorting and matching (same idea as the server's *_norm columns).170 public static func norm(_ s: String) -> String {171 s.folding(options: [.diacriticInsensitive, .caseInsensitive, .widthInsensitive], locale: Locale(identifier: "en_US_POSIX")).lowercased()172 .trimmingCharacters(in: .whitespacesAndNewlines)173 }174}175176public enum Format {177 public static func duration(ms: Int) -> String { duration(seconds: Double(ms) / 1000) }178 public static func duration(seconds: Double) -> String {179 guard seconds.isFinite, seconds >= 0 else { return "–:––" }180 let s = Int(seconds.rounded(.down)); let h = s / 3600, m = (s % 3600) / 60, sec = s % 60181 return h > 0 ? String(format: "%d:%02d:%02d", h, m, sec) : String(format: "%d:%02d", m, sec)182 }183 public static func longDuration(ms: Int) -> String {184 let minutes = ms / 60000; let h = minutes / 60, m = minutes % 60185 return h > 0 ? "\(h) h \(m) min" : "\(max(m, 1)) min"186 }187 public static func bytes(_ n: Int64) -> String {188 let f = ByteCountFormatter(); f.countStyle = .file; f.allowedUnits = [.useKB, .useMB, .useGB, .useTB]189 return f.string(fromByteCount: n)190 }191 public static func codecName(_ codec: String, container: String = "") -> String {192 switch codec.lowercased() {193 case "flac": return "FLAC"194 case "alac": return "ALAC"195 case "mp3": return "MP3"196 case "aac": return "AAC"197 case "vorbis": return "Vorbis"198 case "opus": return "Opus"199 case let c where c.hasPrefix("pcm"): return container.lowercased().contains("aif") ? "AIFF" : "WAV"200 case let c where c.hasPrefix("dsd"): return "DSD"201 default: return codec.uppercased()202 }203 }204 public static func sampleRate(_ hz: Int) -> String {205 let k = Double(hz) / 1000206 return (k == k.rounded() ? String(format: "%.0f", k) : String(format: "%.1f", k).replacingOccurrences(of: ".", with: ",")) + " kHz"207 }208 /// "FLAC · 16 bits / 44,1 kHz" for lossless, "MP3 · 320 kb/s" for lossy.209 public static func quality(of t: Track) -> String {210 let name = codecName(t.codec, container: t.container)211 let lossless = ["FLAC", "ALAC", "WAV", "AIFF"].contains(name)212 var parts: [String] = []213 if lossless {214 if let b = t.bitDepth, b > 0 { parts.append("\(b) bits") }215 if let r = t.sampleRate { parts.append(sampleRate(r)) }216 } else if let br = t.bitrate, br > 0 {217 parts.append("\(Int((Double(br) / 1000).rounded())) kb/s")218 } else if let r = t.sampleRate { parts.append(sampleRate(r)) }219 return parts.isEmpty ? name : name + " · " + parts.joined(separator: " / ")220 }221 public static func isLossless(_ t: Track) -> Bool { ["FLAC", "ALAC", "WAV", "AIFF"].contains(codecName(t.codec, container: t.container)) }222 public static func isHiRes(_ t: Track) -> Bool { isLossless(t) && ((t.bitDepth ?? 16) > 16 || (t.sampleRate ?? 44100) > 48000) }223}224