SPB Git

Repository Public

LibraryStore+Scripts.swift 15.9 KB 303 lines swift

1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXLibrary/LibraryStore+Scripts.swift3// Description: Automation scripts: optimistic saves, version history, unique names, .orixdj import/export and backups.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation910extension LibraryStore {11    /// File extension of exported scripts.12    public static let scriptFileExtension = "orixdj"13    private static let scriptHeaderMarker = "// ORIX DJ Script v1"14    private static let scriptHeaderEnd = "// ---"15    private static let scriptSelect = "SELECT id, name, source, tags, favorite, created_at, updated_at, origin FROM scripts"1617    private static func decodeScript(_ r: SQLiteRow) -> ScriptRecord {18        ScriptRecord(id: r.int64(0), name: r.string(1), source: r.string(2), tags: decodeJSON(r.string(3)),19                     favorite: r.bool(4), createdAt: r.date(5), updatedAt: r.date(6),20                     origin: ScriptRecord.Origin(rawValue: r.string(7)) ?? .user)21    }2223    private func loadScript(_ id: Int64, _ db: SQLiteDatabase) throws -> ScriptRecord {24        guard let record = try db.first(LibraryStore.scriptSelect + " WHERE id = ?", [.integer(id)], map: LibraryStore.decodeScript) else {25            throw LibraryError.notFound("script \(id)")26        }27        return record28    }2930    private func scriptSearchText(name: String, tags: [String], source: String) -> String {31        LibraryText.fold(name + " " + tags.joined(separator: " ") + " " + source)32    }3334    /// "Name", then "Name 2", "Name 3"… (case-insensitive), ignoring the script `excluding`.35    private func uniqueScriptName(_ desired: String, excluding id: Int64?, _ db: SQLiteDatabase) throws -> String {36        let trimmed = desired.trimmingCharacters(in: .whitespacesAndNewlines)37        let base = trimmed.isEmpty ? "Untitled" : trimmed38        var candidate = base39        var suffix = 240        while try db.scalarInt("SELECT COUNT(*) FROM scripts WHERE name = ? COLLATE NOCASE AND id <> ?",41                               [.text(candidate), .integer(id ?? -1)]) > 0 {42            candidate = "\(base) \(suffix)"43            suffix += 144        }45        return candidate46    }4748    /// A timestamp strictly after `previous`, so that `updatedAt` always changes on a stored modification.49    private func stamp(after previous: Date) -> Date {50        let now = Date()51        return now > previous ? now : previous.addingTimeInterval(0.001)52    }5354    private func appendVersion(_ scriptID: Int64, source: String, at date: Date, _ db: SQLiteDatabase) throws {55        let next = try db.scalarInt("SELECT IFNULL(MAX(version), 0) + 1 FROM script_versions WHERE script_id = ?", [.integer(scriptID)])56        try db.run("INSERT INTO script_versions (script_id, version, source, created_at) VALUES (?, ?, ?, ?)",57                   [.integer(scriptID), .integer(next), .text(source), .date(date)])58    }5960    private func insertScript(name: String, source: String, tags: [String], favorite: Bool, origin: ScriptRecord.Origin,61                              _ db: SQLiteDatabase) throws -> ScriptRecord {62        let name = try uniqueScriptName(name, excluding: nil, db)63        let tags = LibraryStore.normalisedTags(tags)64        let now = Date()65        try db.run("INSERT INTO scripts (name, source, tags, favorite, created_at, updated_at, origin, search_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",66                   [.text(name), .text(source), .text(LibraryStore.encodeJSON(tags)), .bool(favorite), .date(now), .date(now),67                    .text(origin.rawValue), .text(scriptSearchText(name: name, tags: tags, source: source))])68        let id = db.lastInsertRowID69        try appendVersion(id, source: source, at: now, db)70        return ScriptRecord(id: id, name: name, source: source, tags: tags, favorite: favorite, createdAt: now, updatedAt: now, origin: origin)71    }7273    // MARK: CRUD7475    /// Creates a script and its version 1. A taken name becomes "Name 2", "Name 3"…76    @discardableResult77    public func createScript(name: String, source: String, tags: [String] = [], favorite: Bool = false,78                             origin: ScriptRecord.Origin = .user) throws -> ScriptRecord {79        try write { try insertScript(name: name, source: source, tags: tags, favorite: favorite, origin: origin, $0) }80    }8182    public func script(id: Int64) throws -> ScriptRecord? {83        try read { try $0.first(LibraryStore.scriptSelect + " WHERE id = ?", [.integer(id)], map: LibraryStore.decodeScript) }84    }8586    public func script(named name: String) throws -> ScriptRecord? {87        try read { try $0.first(LibraryStore.scriptSelect + " WHERE name = ? COLLATE NOCASE", [.text(name)], map: LibraryStore.decodeScript) }88    }8990    /// Scripts by name. `search` words are AND-ed over name, tags and source (case- and diacritic-insensitive).91    public func scripts(search: String = "", origin: ScriptRecord.Origin? = nil, favoritesOnly: Bool = false) throws -> [ScriptRecord] {92        try read { db in93            var conditions: [String] = []94            var parameters: [SQLiteValue] = []95            for word in LibraryText.fold(search).split(whereSeparator: { $0.isWhitespace }) {96                conditions.append("search_text LIKE ? ESCAPE '\\'")97                parameters.append(.text("%" + LibraryText.likeEscaped(String(word)) + "%"))98            }99            if let origin {100                conditions.append("origin = ?")101                parameters.append(.text(origin.rawValue))102            }103            if favoritesOnly { conditions.append("favorite = 1") }104            var sql = LibraryStore.scriptSelect105            if !conditions.isEmpty { sql += " WHERE " + conditions.joined(separator: " AND ") }106            // Sorted here rather than in SQL so that accented names sort with their base letter.107            return LibraryStore.sortedByName(try db.query(sql, parameters, map: LibraryStore.decodeScript), name: \.name, id: \.id)108        }109    }110111    /// Optimistic save. Throws `LibraryError.conflict` — and stores nothing — when the script was modified since112    /// the caller read it (`expectedUpdatedAt` differs from the stored `updatedAt`). A save that changes the113    /// source appends a version; a save with an identical source is a no-op that returns the stored record.114    @discardableResult115    public func saveScript(id: Int64, source: String, expectedUpdatedAt: Date) throws -> ScriptRecord {116        try write { db in117            var record = try loadScript(id, db)118            guard record.updatedAt == expectedUpdatedAt else {119                throw LibraryError.conflict("script \"\(record.name)\" was modified elsewhere; reload it before saving")120            }121            guard record.source != source else { return record }122            record.source = source123            record.updatedAt = stamp(after: record.updatedAt)124            try db.run("UPDATE scripts SET source = ?, updated_at = ?, search_text = ? WHERE id = ?",125                       [.text(source), .date(record.updatedAt),126                        .text(scriptSearchText(name: record.name, tags: record.tags, source: source)), .integer(id)])127            try appendVersion(id, source: source, at: record.updatedAt, db)128            return record129        }130    }131132    /// Renames a script; a taken name becomes "Name 2", "Name 3"… Returns the record with its final name.133    @discardableResult134    public func renameScript(id: Int64, to name: String) throws -> ScriptRecord {135        try write { db in136            var record = try loadScript(id, db)137            let final = try uniqueScriptName(name, excluding: id, db)138            guard final != record.name else { return record }139            record.name = final140            record.updatedAt = stamp(after: record.updatedAt)141            try db.run("UPDATE scripts SET name = ?, updated_at = ?, search_text = ? WHERE id = ?",142                       [.text(final), .date(record.updatedAt),143                        .text(scriptSearchText(name: final, tags: record.tags, source: record.source)), .integer(id)])144            return record145        }146    }147148    /// Changes tags and/or the favorite flag (`nil` = keep).149    @discardableResult150    public func updateScript(id: Int64, tags: [String]? = nil, favorite: Bool? = nil) throws -> ScriptRecord {151        try write { db in152            var record = try loadScript(id, db)153            if let tags { record.tags = LibraryStore.normalisedTags(tags) }154            if let favorite { record.favorite = favorite }155            record.updatedAt = stamp(after: record.updatedAt)156            try db.run("UPDATE scripts SET tags = ?, favorite = ?, updated_at = ?, search_text = ? WHERE id = ?",157                       [.text(LibraryStore.encodeJSON(record.tags)), .bool(record.favorite), .date(record.updatedAt),158                        .text(scriptSearchText(name: record.name, tags: record.tags, source: record.source)), .integer(id)])159            return record160        }161    }162163    /// Copies a script (current source and tags, fresh history) under a unique name; the copy is a user script.164    @discardableResult165    public func duplicateScript(id: Int64) throws -> ScriptRecord {166        try write { db in167            let original = try loadScript(id, db)168            return try insertScript(name: original.name, source: original.source, tags: original.tags, favorite: false, origin: .user, db)169        }170    }171172    /// Deletes a script and its version history.173    public func deleteScript(id: Int64) throws {174        try write { db in175            guard try db.run("DELETE FROM scripts WHERE id = ?", [.integer(id)]) == 1 else { throw LibraryError.notFound("script \(id)") }176        }177    }178179    // MARK: Versions180181    /// Versions of a script, newest first.182    public func scriptVersions(scriptID: Int64) throws -> [ScriptVersion] {183        try read {184            try $0.query("SELECT id, script_id, version, source, created_at FROM script_versions WHERE script_id = ? ORDER BY version DESC",185                         [.integer(scriptID)]) {186                ScriptVersion(id: $0.int64(0), scriptID: $0.int64(1), version: $0.int(2), source: $0.string(3), createdAt: $0.date(4))187            }188        }189    }190191    /// Makes an old version the current source. History is never rewritten: the restore is appended as a new192    /// version (unless the source is already identical).193    @discardableResult194    public func restoreScriptVersion(scriptID: Int64, versionID: Int64) throws -> ScriptRecord {195        try write { db in196            let record = try loadScript(scriptID, db)197            guard let source = try db.first("SELECT source FROM script_versions WHERE id = ? AND script_id = ?",198                                            [.integer(versionID), .integer(scriptID)], map: { $0.string(0) }) else {199                throw LibraryError.notFound("version \(versionID) of script \(scriptID)")200            }201            return try saveScript(id: scriptID, source: source, expectedUpdatedAt: record.updatedAt)202        }203    }204205    // MARK: Files206207    private static func fileName(for name: String) -> String {208        let cleaned = name.map { "/:\\\0\n\r".contains($0) ? "-" : $0 }209        let text = String(cleaned).trimmingCharacters(in: CharacterSet(charactersIn: ". ").union(.whitespaces))210        return text.isEmpty ? "Untitled" : text211    }212213    /// The text of a `.orixdj` file: a comment header (name, tags, origin, favorite, dates) followed by the source.214    public static func scriptFileContents(_ record: ScriptRecord) -> String {215        func oneLine(_ text: String) -> String { text.replacingOccurrences(of: "\n", with: " ").replacingOccurrences(of: "\r", with: " ") }216        var lines = [scriptHeaderMarker]217        lines.append("// name: " + oneLine(record.name))218        lines.append("// tags: " + record.tags.map { oneLine($0).replacingOccurrences(of: ",", with: " ") }.joined(separator: ", "))219        lines.append("// origin: " + record.origin.rawValue)220        lines.append("// favorite: " + (record.favorite ? "true" : "false"))221        lines.append("// created: " + record.createdAt.formatted(.iso8601))222        lines.append("// updated: " + record.updatedAt.formatted(.iso8601))223        lines.append(scriptHeaderEnd)224        return lines.joined(separator: "\n") + "\n" + record.source225    }226227    /// Writes a script to a `.orixdj` text file (UTF-8, atomic).228    public func exportScript(id: Int64, to url: URL) throws {229        let record = try read { try loadScript(id, $0) }230        do {231            try Data(LibraryStore.scriptFileContents(record).utf8).write(to: url, options: .atomic)232        } catch {233            throw LibraryError.io("cannot write \(url.path): \(error.localizedDescription)")234        }235    }236237    /// Imports a `.orixdj` file as a new script (never overwrites: a taken name becomes "Name 2"…).238    /// A file without the ORIX header is imported whole, named after the file.239    @discardableResult240    public func importScript(from url: URL) throws -> ScriptRecord {241        let text: String242        do {243            text = String(decoding: try Data(contentsOf: url), as: UTF8.self)244        } catch {245            throw LibraryError.io("cannot read \(url.path): \(error.localizedDescription)")246        }247        var name = url.deletingPathExtension().lastPathComponent248        var tags: [String] = []249        var origin = ScriptRecord.Origin.user250        var favorite = false251        var source = text252        let normalised = text.replacingOccurrences(of: "\r\n", with: "\n")253        if normalised.hasPrefix(LibraryStore.scriptHeaderMarker + "\n"),254           let end = normalised.range(of: "\n" + LibraryStore.scriptHeaderEnd + "\n")255            ?? (normalised.hasSuffix("\n" + LibraryStore.scriptHeaderEnd) ? normalised.range(of: "\n" + LibraryStore.scriptHeaderEnd, options: .backwards) : nil) {256            let header = normalised[normalised.startIndex..<end.lowerBound]257            source = String(normalised[end.upperBound...])258            for line in header.split(separator: "\n").dropFirst() {259                guard line.hasPrefix("// "), let colon = line.firstIndex(of: ":") else { continue }260                let key = line[line.index(line.startIndex, offsetBy: 3)..<colon].trimmingCharacters(in: .whitespaces)261                let value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)262                switch key {263                case "name": if !value.isEmpty { name = value }264                case "tags": tags = value.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }265                case "origin": origin = ScriptRecord.Origin(rawValue: value) ?? .user266                case "favorite": favorite = value == "true"267                default: break268                }269            }270        }271        return try write { try insertScript(name: name, source: source, tags: tags, favorite: favorite, origin: origin, $0) }272    }273274    /// Writes every script as `<name>.orixdj` into `directory` (created if needed; existing files with the same275    /// names are replaced). Returns the written files.276    @discardableResult277    public func backupScripts(to directory: URL) throws -> [URL] {278        let records = try scripts()279        do {280            try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)281        } catch {282            throw LibraryError.io("cannot create \(directory.path): \(error.localizedDescription)")283        }284        var used = Set<String>()285        var written: [URL] = []286        for record in records {287            var base = LibraryStore.fileName(for: record.name)288            if !used.insert(base.lowercased()).inserted {289                base += " (\(record.id))"290                used.insert(base.lowercased())291            }292            let url = directory.appendingPathComponent(base).appendingPathExtension(LibraryStore.scriptFileExtension)293            do {294                try Data(LibraryStore.scriptFileContents(record).utf8).write(to: url, options: .atomic)295            } catch {296                throw LibraryError.io("cannot write \(url.path): \(error.localizedDescription)")297            }298            written.append(url)299        }300        return written301    }302}303
Files main
Menu

Theme