SPB Git

Repository Public

Models.swift 17.6 KB 450 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXLibrary/Models.swift3// Description: Value types of the music library: tracks, cues, crates, playlists, history, scripts, documents and errors.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation910// MARK: - Errors1112/// Every error thrown by `LibraryStore` and `MediaImporter`.13public enum LibraryError: Error, Equatable, Sendable, CustomStringConvertible {14    /// SQLite reported an error (`code` is the extended result code).15    case sqlite(code: Int32, message: String)16    /// The database was written by a newer version of the app.17    case unsupportedSchema(found: Int, supported: Int)18    /// The requested row does not exist.19    case notFound(String)20    /// Optimistic save refused: the stored record changed since it was read.21    case conflict(String)22    /// A caller-supplied value is not usable (bad rule, bad JSON, empty name…).23    case invalidArgument(String)24    /// File-system failure (export, import, backup, relocation).25    case io(String)26    /// The store was closed.27    case closed28    /// Importer: the file extension is not one of `MediaImporter.supportedExtensions`.29    case unsupportedFormat(path: String)30    /// Importer: the file has a length of zero bytes.31    case emptyFile(path: String)32    /// Importer: the file is DRM-protected and cannot be decoded.33    case protectedContent(path: String)34    /// Importer: the file does not exist, is not readable, or contains no decodable audio.35    case unreadableFile(path: String, reason: String)36    /// Importer: the operation was cancelled.37    case cancelled3839    public var description: String {40        switch self {41        case let .sqlite(code, message): return "Database error \(code): \(message)"42        case let .unsupportedSchema(found, supported):43            return "The library was created by a newer version (schema \(found), this build supports up to \(supported))."44        case let .notFound(what): return "Not found: \(what)"45        case let .conflict(what): return "Conflict: \(what)"46        case let .invalidArgument(what): return "Invalid argument: \(what)"47        case let .io(what): return "File error: \(what)"48        case .closed: return "The library is closed."49        case let .unsupportedFormat(path): return "Unsupported audio format: \(path)"50        case let .emptyFile(path): return "The file is empty: \(path)"51        case let .protectedContent(path): return "The file is DRM-protected and cannot be played: \(path)"52        case let .unreadableFile(path, reason): return "The file cannot be read (\(reason)): \(path)"53        case .cancelled: return "Cancelled."54        }55    }56}5758// MARK: - Track5960/// A hot cue. `index` is the pad number, 0...7.61public struct CuePoint: Codable, Sendable, Equatable, Identifiable {62    public var index: Int63    public var seconds: Double64    public var label: String65    public var colorHex: String66    public var id: Int { index }6768    public init(index: Int, seconds: Double, label: String = "", colorHex: String = "#FF9F0A") {69        self.index = index70        self.seconds = seconds71        self.label = label72        self.colorHex = colorHex73    }74}7576/// A loop saved with a track.77public struct SavedLoop: Codable, Sendable, Equatable {78    public var startSeconds: Double79    public var lengthBeats: Double80    public var label: String8182    public init(startSeconds: Double, lengthBeats: Double, label: String = "") {83        self.startSeconds = startSeconds84        self.lengthBeats = lengthBeats85        self.label = label86    }87}8889/// One audio file known to the library. The audio itself is never copied nor deleted by the library.90public struct Track: Codable, Sendable, Identifiable, Equatable {91    /// Row id; 0 for a track that was not stored yet.92    public var id: Int6493    /// Absolute file path (unique in the library).94    public var path: String95    /// Plain (non security-scoped) file bookmark used to follow moved or renamed files.96    public var bookmark: Data?97    public var title: String98    public var artist: String99    public var album: String100    public var genre: String101    /// 0 when unknown.102    public var year: Int103    public var comment: String104    /// Seconds.105    public var duration: Double106    public var sampleRate: Double107    public var channels: Int108    /// Bits per second, 0 when unknown.109    public var bitRate: Int110    /// Lower-case file extension.111    public var format: String112    /// Bytes.113    public var fileSize: Int64114    public var dateAdded: Date115    public var dateModified: Date116    public var lastPlayed: Date?117    public var playCount: Int118    /// 0...5.119    public var rating: Int120    public var favorite: Bool121    public var tags: [String]122    public var bpm: Double?123    public var bpmConfidence: Double?124    /// Seconds of the first beat of the beat grid.125    public var gridFirstBeat: Double?126    public var gridDownbeatIndex: Int?127    /// Short key name ("Am", "F#"…).128    public var key: String?129    /// Camelot code ("8A", "11B"…).130    public var camelot: String?131    public var keyConfidence: Double?132    public var loudnessLUFS: Double?133    public var peakDBFS: Double?134    public var gainDB: Double?135    /// 0 = not analysed.136    public var analysisVersion: Int137    public var missing: Bool138    public var cues: [CuePoint]139    public var savedLoops: [SavedLoop]140141    public var url: URL { URL(fileURLWithPath: path) }142    public var isAnalysed: Bool { analysisVersion > 0 }143144    public init(145        id: Int64 = 0, path: String, bookmark: Data? = nil,146        title: String = "", artist: String = "", album: String = "", genre: String = "",147        year: Int = 0, comment: String = "",148        duration: Double = 0, sampleRate: Double = 0, channels: Int = 0, bitRate: Int = 0,149        format: String = "", fileSize: Int64 = 0,150        dateAdded: Date = Date(), dateModified: Date = Date(), lastPlayed: Date? = nil,151        playCount: Int = 0, rating: Int = 0, favorite: Bool = false, tags: [String] = [],152        bpm: Double? = nil, bpmConfidence: Double? = nil,153        gridFirstBeat: Double? = nil, gridDownbeatIndex: Int? = nil,154        key: String? = nil, camelot: String? = nil, keyConfidence: Double? = nil,155        loudnessLUFS: Double? = nil, peakDBFS: Double? = nil, gainDB: Double? = nil,156        analysisVersion: Int = 0, missing: Bool = false,157        cues: [CuePoint] = [], savedLoops: [SavedLoop] = []158    ) {159        self.id = id; self.path = path; self.bookmark = bookmark160        self.title = title; self.artist = artist; self.album = album; self.genre = genre161        self.year = year; self.comment = comment162        self.duration = duration; self.sampleRate = sampleRate; self.channels = channels; self.bitRate = bitRate163        self.format = format; self.fileSize = fileSize164        self.dateAdded = dateAdded; self.dateModified = dateModified; self.lastPlayed = lastPlayed165        self.playCount = playCount; self.rating = rating; self.favorite = favorite; self.tags = tags166        self.bpm = bpm; self.bpmConfidence = bpmConfidence167        self.gridFirstBeat = gridFirstBeat; self.gridDownbeatIndex = gridDownbeatIndex168        self.key = key; self.camelot = camelot; self.keyConfidence = keyConfidence169        self.loudnessLUFS = loudnessLUFS; self.peakDBFS = peakDBFS; self.gainDB = gainDB170        self.analysisVersion = analysisVersion; self.missing = missing171        self.cues = cues; self.savedLoops = savedLoops172    }173}174175/// Result of an analysis pass, written with `LibraryStore.setAnalysis(trackID:_:)`.176public struct TrackAnalysis: Codable, Sendable, Equatable {177    public var bpm: Double?178    public var bpmConfidence: Double?179    public var gridFirstBeat: Double?180    public var gridDownbeatIndex: Int?181    public var key: String?182    public var camelot: String?183    public var keyConfidence: Double?184    public var loudnessLUFS: Double?185    public var peakDBFS: Double?186    public var gainDB: Double?187    /// Must be > 0 for the track to count as analysed.188    public var analysisVersion: Int189    /// Opaque analysis payload (waveform overview, beat list…); stored in its own table. `nil` leaves the stored blob untouched.190    public var data: Data?191192    public init(193        bpm: Double? = nil, bpmConfidence: Double? = nil,194        gridFirstBeat: Double? = nil, gridDownbeatIndex: Int? = nil,195        key: String? = nil, camelot: String? = nil, keyConfidence: Double? = nil,196        loudnessLUFS: Double? = nil, peakDBFS: Double? = nil, gainDB: Double? = nil,197        analysisVersion: Int = 1, data: Data? = nil198    ) {199        self.bpm = bpm; self.bpmConfidence = bpmConfidence200        self.gridFirstBeat = gridFirstBeat; self.gridDownbeatIndex = gridDownbeatIndex201        self.key = key; self.camelot = camelot; self.keyConfidence = keyConfidence202        self.loudnessLUFS = loudnessLUFS; self.peakDBFS = peakDBFS; self.gainDB = gainDB203        self.analysisVersion = analysisVersion; self.data = data204    }205}206207// MARK: - Query208209public struct TrackQuery: Sendable, Equatable {210    public enum Scope: Sendable, Equatable {211        case all212        case crate(Int64)213        /// Ordered by playlist position unless a sort key is given. A track present twice is returned twice.214        case playlist(Int64)215        case smartCrate(Int64)216        case favorites217        /// One row per play, newest first unless a sort key is given. `sessionID == nil` means every session.218        case history(sessionID: Int64?)219        case unanalysed220        case missing221    }222223    public enum SortKey: String, Sendable, Codable, CaseIterable {224        case title, artist, album, genre, bpm225        /// Harmonic order: Camelot number then letter (1A, 1B, 2A … 12B), falling back to the key name.226        case key227        case duration, rating, dateAdded, lastPlayed, playCount228    }229230    /// Free text; words are AND-ed and matched against title, artist, album, genre, tags and comment,231    /// ignoring case and diacritics.232    public var search: String233    public var scope: Scope234    /// `nil` = natural order of the scope (playlist position, history newest first, otherwise title).235    public var sort: SortKey?236    public var ascending: Bool237    public var limit: Int?238    public var offset: Int239240    public init(search: String = "", scope: Scope = .all, sort: SortKey? = nil, ascending: Bool = true,241                limit: Int? = nil, offset: Int = 0) {242        self.search = search243        self.scope = scope244        self.sort = sort245        self.ascending = ascending246        self.limit = limit247        self.offset = offset248    }249}250251// MARK: - Collections252253public struct Crate: Codable, Sendable, Identifiable, Equatable {254    public var id: Int64255    public var name: String256    public var sortIndex: Int257    public var trackCount: Int258259    public init(id: Int64 = 0, name: String, sortIndex: Int = 0, trackCount: Int = 0) {260        self.id = id; self.name = name; self.sortIndex = sortIndex; self.trackCount = trackCount261    }262}263264public struct Playlist: Codable, Sendable, Identifiable, Equatable {265    public var id: Int64266    public var name: String267    public var sortIndex: Int268    public var trackCount: Int269270    public init(id: Int64 = 0, name: String, sortIndex: Int = 0, trackCount: Int = 0) {271        self.id = id; self.name = name; self.sortIndex = sortIndex; self.trackCount = trackCount272    }273}274275/// One slot of a playlist. `id` is stable across reorders; `position` is the dense 0-based index.276public struct PlaylistEntry: Codable, Sendable, Identifiable, Equatable {277    public var id: Int64278    public var playlistID: Int64279    public var trackID: Int64280    public var position: Int281282283    public init(id: Int64, playlistID: Int64, trackID: Int64, position: Int) {284        self.id = id; self.playlistID = playlistID; self.trackID = trackID; self.position = position285    }286}287288public struct SmartRule: Codable, Sendable, Equatable {289    public enum Field: String, Codable, Sendable, CaseIterable {290        case bpm, key, camelot, genre, artist, title, album, rating, favorite, tag, year, duration291        /// The value is an age in days ("added more than 30 days ago" = `.greaterThan`, "30").292        case dateAdded293        case playCount, analysed, format294    }295296    public enum Comparison: String, Codable, Sendable, CaseIterable {297        case equals, notEquals, contains, greaterThan, lessThan298        /// Inclusive on both ends; uses `value` and `upperValue`.299        case between300    }301302    public var field: Field303    public var comparison: Comparison304    /// Text, a number ("128", "7.5") or a boolean ("true"/"false", "yes"/"no", "1"/"0") depending on the field.305    public var value: String306    /// Upper bound, only for `.between`.307    public var upperValue: String?308309    public init(field: Field, comparison: Comparison, value: String, upperValue: String? = nil) {310        self.field = field; self.comparison = comparison; self.value = value; self.upperValue = upperValue311    }312313    public init(_ field: Field, _ comparison: Comparison, _ value: Double, _ upperValue: Double? = nil) {314        self.init(field: field, comparison: comparison, value: SmartRule.format(value),315                  upperValue: upperValue.map(SmartRule.format))316    }317318    public init(_ field: Field, is flag: Bool) {319        self.init(field: field, comparison: .equals, value: flag ? "true" : "false")320    }321322    static func format(_ number: Double) -> String {323        number == number.rounded() && abs(number) < 1e15 ? String(Int64(number)) : String(number)324    }325}326327public struct SmartCrate: Codable, Sendable, Identifiable, Equatable {328    public enum Match: String, Codable, Sendable { case all, any }329330    public var id: Int64331    public var name: String332    public var sortIndex: Int333    public var match: Match334    public var rules: [SmartRule]335336    public init(id: Int64 = 0, name: String, sortIndex: Int = 0, match: Match = .all, rules: [SmartRule] = []) {337        self.id = id; self.name = name; self.sortIndex = sortIndex; self.match = match; self.rules = rules338    }339}340341// MARK: - History342343public struct HistorySession: Codable, Sendable, Identifiable, Equatable {344    public var id: Int64345    public var name: String346    public var startedAt: Date347    public var endedAt: Date?348    public var entryCount: Int349350351    public init(id: Int64, name: String, startedAt: Date, endedAt: Date? = nil, entryCount: Int = 0) {352        self.id = id; self.name = name; self.startedAt = startedAt; self.endedAt = endedAt; self.entryCount = entryCount353    }354}355356public struct HistoryEntry: Codable, Sendable, Identifiable, Equatable {357    public var id: Int64358    public var trackID: Int64359    public var playedAt: Date360    /// Deck label ("A", "B", "C", "D", "sampler"…).361    public var deck: String362    public var sessionID: Int64?363364365    public init(id: Int64, trackID: Int64, playedAt: Date, deck: String = "", sessionID: Int64? = nil) {366        self.id = id; self.trackID = trackID; self.playedAt = playedAt; self.deck = deck; self.sessionID = sessionID367    }368}369370// MARK: - Scripts371372public struct ScriptRecord: Codable, Sendable, Identifiable, Equatable {373    public enum Origin: String, Codable, Sendable, CaseIterable { case user, preset, ai }374375    public var id: Int64376    public var name: String377    public var source: String378    public var tags: [String]379    public var favorite: Bool380    public var createdAt: Date381    /// Changes on every stored modification; pass it back to `saveScript(id:source:expectedUpdatedAt:)`.382    public var updatedAt: Date383    public var origin: Origin384385386    public init(id: Int64, name: String, source: String, tags: [String] = [], favorite: Bool = false,387                createdAt: Date = Date(), updatedAt: Date = Date(), origin: Origin = .user) {388        self.id = id; self.name = name; self.source = source; self.tags = tags; self.favorite = favorite389        self.createdAt = createdAt; self.updatedAt = updatedAt; self.origin = origin390    }391}392393public struct ScriptVersion: Codable, Sendable, Identifiable, Equatable {394    public var id: Int64395    public var scriptID: Int64396    /// 1-based, increasing.397    public var version: Int398    public var source: String399    public var createdAt: Date400401402    public init(id: Int64, scriptID: Int64, version: Int, source: String, createdAt: Date) {403        self.id = id; self.scriptID = scriptID; self.version = version; self.source = source; self.createdAt = createdAt404    }405}406407// MARK: - Documents408409/// A named JSON document (effect-chain preset, MIDI mapping profile, visual-builder graph, session recovery…).410public struct LibraryDocument: Codable, Sendable, Identifiable, Equatable {411    public var id: Int64412    public var kind: String413    public var name: String414    public var json: String415    public var updatedAt: Date416417418    public init(id: Int64, kind: String, name: String, json: String, updatedAt: Date) {419        self.id = id; self.kind = kind; self.name = name; self.json = json; self.updatedAt = updatedAt420    }421}422423/// Well-known values for `LibraryDocument.kind`. Any other string is accepted too.424public enum DocumentKind {425    public static let effectChainPreset = "effect-chain"426    public static let midiMapping = "midi-mapping"427    public static let visualGraph = "visual-graph"428    public static let sessionRecovery = "session-recovery"429}430431// MARK: - Text folding432433public enum LibraryText {434    /// Lower-cased, diacritic- and width-insensitive form used for search and sorting ("Beyoncé" → "beyonce").435    public static func fold(_ text: String) -> String {436        text.folding(options: [.diacriticInsensitive, .caseInsensitive, .widthInsensitive], locale: nil).lowercased()437    }438439    /// Escapes `%`, `_` and `\` for a `LIKE … ESCAPE '\'` pattern.440    static func likeEscaped(_ text: String) -> String {441        var out = ""442        out.reserveCapacity(text.count)443        for ch in text {444            if ch == "%" || ch == "_" || ch == "\\" { out.append("\\") }445            out.append(ch)446        }447        return out448    }449}450
Files main
Menu

Theme