Cotton code
231 lines · 10.8 KB · SwiftRaw
// An album's Find details (Cotton Music, 4 Nov 2026, definition section 6):// the lookups the phone runs, each filling only what is empty and stamping// where it came from (`music.fill`, the core's rule).//// 1. MusicBrainz, from the phone, one request a second under an identified//    User-Agent: by the release id the tags carried, else by a song's ISRC,//    else a search on the album's title and artist (a match only at score//    90 or more and the same title). It fills the release ids and the year.// 2. The cover, when the album has none (the file's own picture and the//    folder's were taken at intake): the object's `fetch_cover` (the Cover//    Art Archive, then Deezer), then the iTunes Search API from the phone,//    which refuses the object's network.import CottonValuesimport Foundationpublic actor AlbumLookup {    /// One GET out to a lookup service (`LookupFetch`), its answer back.    public typealias Fetch = LookupFetch.Get    public static let musicBrainz = URL(string: "https://musicbrainz.org/ws/2")!    public static let iTunesSearch = URL(string: "https://itunes.apple.com/search")!    /// MusicBrainz asks every client to say who it is, with a way to reach them.    /// The product and its contact, as the header joins them (no person reads it).    public static let userAgent = ["CottonMusic/1.0", "(https://cottondb.com)"].joined(separator: " ")    /// The least score a MusicBrainz search answer is taken at.    public static let leastScore = 90    private let core: any CottonCalling    private let fetch: Fetch    private let pause: Duration    private var lastAsked: ContinuousClock.Instant?    public init(core: any CottonCalling, pause: Duration = .milliseconds(1100),                fetch: @escaping Fetch = LookupFetch.live) {        self.core = core        self.fetch = fetch        self.pause = pause    }    /// What a Find details came to: the columns filled, and the album's name.    public struct Found: Sendable, Equatable {        public var filled: [String]        public var name: String    }    struct Album: Sendable, Equatable {        var id: String        var title: String        var artist: String        var mbRelease: String?        var hasCover: Bool        var isrcs: [String]    }    public func findDetails(album id: String) async throws -> Found {        let album = try await read(id)        var filled: [String] = []        if let release = try? await release(for: album) {            var fields: [String: JSONValue] = ["mb_release": .string(release.id)]            if let group = release.group { fields["mb_release_group"] = .string(group) }            if let year = release.year { fields["year"] = .string(year) }            filled += try await fill(id, from: "musicbrainz", fields: fields)        }        if !album.hasCover {            filled += try await cover(for: album)        }        return Found(filled: filled, name: album.title)    }    // MARK: The album    /// The album's title, for the words said while it is looked up.    public func name(of id: String) async -> String {        (try? await read(id).title) ?? ""    }    private func read(_ id: String) async throws -> Album {        struct Read: Decodable { let data: [String: RecordValue] }        let read = try await core.call(CottonMethod.recordsGet, ["table": RecordValue.text("music_album"), "id": .text(id)], as: Read.self)        struct Page: Decodable { let records: [Read] }        let songs = try? await core.call(CottonMethod.recordsList, ["table": RecordValue.text("song"), "where": .object(["album": .text(id)])], as: Page.self)        let isrcs = (songs?.records ?? []).compactMap { $0.data["isrc"]?.text }.filter { !$0.isEmpty }        let text = { (key: String) in read.data[key]?.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" }        return Album(id: id, title: text("title"), artist: text("artist_name"),                     mbRelease: text("mb_release").isEmpty ? nil : text("mb_release"),                     hasCover: !text("cover").isEmpty, isrcs: isrcs)    }    @discardableResult    private func fill(_ id: String, from: String, fields: [String: JSONValue], coverPath: String? = nil) async throws -> [String] {        struct Filled: Decodable { let filled: [String] }        var request: [String: JSONValue] = ["table": .string("music_album"), "id": .string(id), "from": .string(from), "fields": .object(fields)]        if let coverPath { request["coverPath"] = .string(coverPath) }        return try await core.call(CottonMethod.musicFill, request, as: Filled.self).filled    }    // MARK: MusicBrainz    struct Release: Sendable, Equatable {        var id: String        var group: String?        var year: String?    }    struct MBRelease: Decodable {        let id: String        let title: String?        let date: String?        let score: Int?        let releaseGroup: Group?        struct Group: Decodable { let id: String }        enum CodingKeys: String, CodingKey {            case id, title, date, score            case releaseGroup = "release-group"        }        var release: Release {            let year = date.map { String($0.prefix(4)) }.flatMap { $0.count == 4 ? $0 : nil }            return Release(id: id, group: releaseGroup?.id, year: year)        }    }    /// The album's release: by its id, else a song's ISRC, else a search.    func release(for album: Album) async throws -> Release? {        if let id = album.mbRelease {            return try await musicBrainz("release/\(id)", ["inc": "release-groups"], as: MBRelease.self).release        }        struct ISRC: Decodable {            let recordings: [Recording]            struct Recording: Decodable { let releases: [MBRelease]? }        }        for isrc in album.isrcs.prefix(1) {            if let found = try? await musicBrainz("isrc/\(isrc)", ["inc": "releases"], as: ISRC.self),               let picked = Self.pick(found.recordings.flatMap { $0.releases ?? [] }, title: album.title, scored: false) {                return try await musicBrainz("release/\(picked.id)", ["inc": "release-groups"], as: MBRelease.self).release            }        }        guard !album.title.isEmpty else { return nil }        struct Search: Decodable { let releases: [MBRelease] }        var query = "release:\"\(Self.quoted(album.title))\""        if !album.artist.isEmpty { query += " && artist:\"\(Self.quoted(album.artist))\"" }        let found = try await musicBrainz("release", ["query": query, "limit": "5"], as: Search.self)        return Self.pick(found.releases, title: album.title, scored: true)?.release    }    /// The first answer with the album's own title (and, from a search, a    /// score high enough).    static func pick(_ releases: [MBRelease], title: String, scored: Bool) -> MBRelease? {        releases.first { release in            (!scored || (release.score ?? 0) >= leastScore) && fold(release.title ?? "") == fold(title)        }    }    private func musicBrainz<T: Decodable>(_ path: String, _ query: [String: String], as: T.Type) async throws -> T {        var parts = URLComponents(url: Self.musicBrainz.appendingPathComponent(path), resolvingAgainstBaseURL: false)!        parts.queryItems = query.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } + [URLQueryItem(name: "fmt", value: "json")]        // One request a second: MusicBrainz's own rule.        if let lastAsked {            let wait = pause - (ContinuousClock.now - lastAsked)            if wait > .zero { try await Task.sleep(for: wait) }        }        lastAsked = ContinuousClock.now        return try await json(parts.url!, as: T.self)    }    private func json<T: Decodable>(_ url: URL, as: T.Type) async throws -> T {        let (data, status) = try await fetch(url, ["User-Agent": Self.userAgent, "Accept": "application/json"])        guard (200..<300).contains(status) else { throw URLError(.badServerResponse) }        return try JSONDecoder().decode(T.self, from: data)    }    // MARK: The cover    private func cover(for album: Album) async throws -> [String] {        struct Covered: Decodable { let filled: [String]? }        let request: [String: JSONValue] = ["act": .string("fetch_cover"), "args": .object(["album": .string(album.id)])]        if let covered = try? await core.call(CottonMethod.objectAct, request, as: Covered.self), covered.filled?.contains("cover") == true {            return ["cover"]        }        guard let art = try? await iTunesArtwork(for: album) else { return [] }        let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("cover-\(UUID().uuidString).jpg")        defer { try? FileManager.default.removeItem(at: scratch) }        let (data, status) = try await fetch(art, ["User-Agent": Self.userAgent])        guard (200..<300).contains(status), !data.isEmpty else { return [] }        try data.write(to: scratch)        return try await fill(album.id, from: "itunes", fields: [:], coverPath: scratch.path(percentEncoded: false))    }    struct ITunes: Decodable {        let results: [Album]        struct Album: Decodable, Equatable {            let collectionName: String?            let artistName: String?            let artworkUrl100: String?        }    }    private func iTunesArtwork(for album: Album) async throws -> URL? {        guard !album.title.isEmpty else { return nil }        var parts = URLComponents(url: Self.iTunesSearch, resolvingAgainstBaseURL: false)!        parts.queryItems = [            URLQueryItem(name: "term", value: [album.artist, album.title].filter { !$0.isEmpty }.joined(separator: " ")),            URLQueryItem(name: "entity", value: "album"),            URLQueryItem(name: "limit", value: "10"),        ]        let found = try await json(parts.url!, as: ITunes.self)        return Self.artwork(found.results, album: album)    }    /// The artwork of the answer with the album's title and artist, at 600 px.    static func artwork(_ results: [ITunes.Album], album: Album) -> URL? {        let hit = results.first { result in            fold(result.collectionName ?? "") == fold(album.title)                && (album.artist.isEmpty || fold(result.artistName ?? "") == fold(album.artist))        }        guard let small = hit?.artworkUrl100 else { return nil }        return URL(string: small.replacingOccurrences(of: "100x100bb", with: "600x600bb"))    }    // MARK: Words    /// Compared as words: case, accents and the ends' spaces folded away.    static func fold(_ text: String) -> String {        text.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil).trimmingCharacters(in: .whitespacesAndNewlines)    }    /// Lucene's quote and backslash, escaped inside a quoted phrase.    static func quoted(_ text: String) -> String {        text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")    }}