Cotton code
251 lines · 11.9 KB · SwiftRaw
// Cotton Music's intake (4 Nov 2026, definition section 6): songs come in// through the share sheet, Plus › Add files and Plus › Add a folder, all into// one door. Each file's tags are read here (TagLib, `SongTagReader`), with a// `.lrc` beside it and its folder's cover read too, and the songs of one album// are handed to the core together (`music.capture`): one write per album, so// the album and its artist are made once and its songs gather under it.//// An album ZIP (a Bandcamp download) is one album (`bringZip`): the core// streams its entries out and names the album, as the Mac's import does.//// What a row says is the core's rule (`cotton_core::music`): tags first, the// folder and the file's name for what they left, the same bytes already here,// the better of two files of one song kept.import CottonValuesimport Foundation/// One file to bring in: where its bytes are, and the path it came in as/// (`Artist/Album (Year)/01 Title.flac` from a folder, its own name from the/// share sheet), which fills what its tags leave empty.public struct MusicFile: Sendable, Equatable {    public var url: URL    public var sourcePath: String    public init(url: URL, sourcePath: String) {        self.url = url        self.sourcePath = sourcePath    }}/// What one song came to (`music.capture`'s answer).public struct MusicOutcome: Decodable, Sendable, Equatable {    /// `added`, `here`, `better`, `worse` or `refused`.    public var outcome: String    public var id: String?    public var title: String?    public var line: String?    public var sourcePath: String?}/// What a whole intake came to.public struct MusicIntakeResult: Sendable, Equatable {    public var outcomes: [MusicOutcome]    /// What to tell the person, in the core's words.    public var said: String?    /// The one album an album ZIP came in as (`bringZip`).    public var album: String?    /// The song to open: the last one that came in, else the one already here.    public var landing: String? {        outcomes.last(where: { $0.outcome == "added" || $0.outcome == "better" })?.id            ?? outcomes.last(where: { $0.outcome == "here" || $0.outcome == "worse" })?.id    }}/// The extensions a song file ends in, as the intake picks them out of a folder.public let songFileExtensions: Set<String> = ["mp3", "m4a", "flac", "ogg", "oga", "opus", "wav", "aif", "aiff"]/// The names a folder's cover goes by, in the order they are looked for.let folderCoverNames = ["cover", "folder", "front", "album", "Cover", "Folder", "Front", "AlbumArt"]public actor MusicIntake {    private let core: any CottonCalling    /// How far it has got: files read and brought in, of all of them.    private let progress: @Sendable (_ done: Int, _ total: Int) -> Void    public init(core: any CottonCalling, progress: @escaping @Sendable (_ done: Int, _ total: Int) -> Void = { _, _ in }) {        self.core = core        self.progress = progress    }    struct Request: Encodable {        var songs: [Song]        var zip: Zip?        struct Song: Encodable {            var path: String            var sourcePath: String            var tags: SongTags            var coverPath: String?            /// The ZIP entry it came out of (`bringZip`).            var entry: String?        }        /// What an album ZIP brings beside its songs, as `music.zip` said it.        struct Zip: Encodable {            var name: String            var boughtOn: String?            var storeUrl: String?            var storeId: String?            var bookletPath: String?        }    }    private struct Answer: Decodable {        var songs: [MusicOutcome]        var said: String?        var album: String?    }    /// `music.zip`'s answer: the album's entries streamed out, or why the ZIP    /// is no album.    struct Unzipped: Decodable {        struct Song: Decodable {            var entry: String            var path: String            var sourcePath: String        }        var songs: [Song]?        var coverPath: String?        var bookletPath: String?        var storeUrl: String?        var storeId: String?        var boughtOn: String?        /// `no_songs`, `folders` or `unreadable`.        var refused: String?        var line: String?    }    /// What an album ZIP came to: one album, or refused in the core's words    /// (`noSongs` when it holds no song at all, so it stays what it was).    public enum ZipOutcome: Sendable, Equatable {        case album(MusicIntakeResult)        case refused(noSongs: Bool, said: String)    }    /// An album ZIP (Bandcamp into Music, 7 Nov 2026): the core streams out    /// the album its names make, entry by entry, never the whole archive;    /// each song is read here (TagLib) and the songs go in as one album in    /// one write, the ZIP's shop, day bought and booklet filling the album's    /// empty columns. `name` is the ZIP's own name, which names the album    /// when its songs' tags do not.    public func bringZip(_ url: URL, name: String) async throws -> ZipOutcome {        let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("music-zip-\(UUID().uuidString)", isDirectory: true)        try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true)        defer { try? FileManager.default.removeItem(at: scratch) }        progress(0, 1)        let opened = try await core.call(            CottonMethod.musicZip,            ["path": url.path(percentEncoded: false), "name": name, "into": scratch.appendingPathComponent("album", isDirectory: true).path(percentEncoded: false)],            as: Unzipped.self)        if let refused = opened.refused {            return .refused(noSongs: refused == "no_songs", said: opened.line ?? "")        }        let found = opened.songs ?? []        var songs: [Request.Song] = []        for (index, file) in found.enumerated() {            var song = Self.read(MusicFile(url: URL(fileURLWithPath: file.path), sourcePath: file.sourcePath), scratch: scratch)            song.entry = file.entry            // A song's own picture first, else the ZIP's cover wherever it sits.            if song.coverPath == nil { song.coverPath = opened.coverPath }            songs.append(song)            progress(index / 2, found.count)        }        let zip = Request.Zip(name: name, boughtOn: opened.boughtOn, storeUrl: opened.storeUrl, storeId: opened.storeId, bookletPath: opened.bookletPath)        let answer = try await core.call(CottonMethod.musicCapture, Request(songs: songs, zip: zip), as: Answer.self)        progress(found.count, found.count)        return .album(MusicIntakeResult(outcomes: answer.songs, said: answer.said, album: answer.album))    }    /// Bring `files` in: read, gathered by album, one write per album.    public func bring(_ files: [MusicFile]) async throws -> MusicIntakeResult {        let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("music-intake-\(UUID().uuidString)", isDirectory: true)        try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true)        defer { try? FileManager.default.removeItem(at: scratch) }        var albums: [String: [Request.Song]] = [:]        var order: [String] = []        for (index, file) in files.enumerated() {            let song = Self.read(file, scratch: scratch)            let key = Self.albumKey(song.tags, sourcePath: file.sourcePath)            if albums[key] == nil { order.append(key) }            albums[key, default: []].append(song)            progress(index / 2, files.count)        }        var outcomes: [MusicOutcome] = []        var said: String?        var done = 0        for key in order {            let songs = albums[key] ?? []            for chunk in stride(from: 0, to: songs.count, by: Self.mostInOne).map({ Array(songs[$0 ..< min($0 + Self.mostInOne, songs.count)]) }) {                let answer = try await core.call(CottonMethod.musicCapture, Request(songs: chunk, zip: nil), as: Answer.self)                outcomes += answer.songs                said = answer.said ?? said                done += chunk.count                progress(files.count / 2 + done / 2, files.count)            }        }        progress(files.count, files.count)        if order.count > 1 || files.count > Self.mostInOne {            let added = outcomes.filter { $0.outcome == "added" }.count            said = added > 0 ? MusicLines.addedMany(added) : said        }        return MusicIntakeResult(outcomes: outcomes, said: said)    }    /// The most songs one write takes: the core's own ceiling.    static let mostInOne = 400    /// One file read: its tags, a `.lrc` beside it, its folder's cover.    static func read(_ file: MusicFile, scratch: URL) -> Request.Song {        let read = SongTagReader.read(file.url, pictureInto: scratch)        var tags = read?.tags ?? SongTags()        let folder = file.url.deletingLastPathComponent()        if tags.syncedLyrics == nil {            let beside = file.url.deletingPathExtension().appendingPathExtension("lrc")            if let lrc = BoundedText.read(beside, most: LRC.mostBytes), LRC.looksTimed(lrc) {                tags.syncedLyrics = lrc                tags.lyricsBeside = true            }        }        var cover = read?.picture        if cover == nil {            cover = folderCoverNames.lazy.flatMap { name in ["jpg", "jpeg", "png"].map { folder.appendingPathComponent(name).appendingPathExtension($0) } }                .first { FileManager.default.fileExists(atPath: $0.path(percentEncoded: false)) }        }        return Request.Song(path: file.url.path(percentEncoded: false), sourcePath: file.sourcePath, tags: tags, coverPath: cover?.path(percentEncoded: false))    }    /// Which write a song goes in: its album artist and album, as near as the    /// tags and its folders say. The core keys the album itself; this only    /// keeps an album's songs together.    static func albumKey(_ tags: SongTags, sourcePath: String) -> String {        let folders = sourcePath.split(separator: "/").dropLast().map(String.init)        let album = tags.album ?? folders.last ?? ""        let artist = tags.albumArtist ?? (tags.compilation == true ? "various_artists" : nil) ?? tags.artist ?? folders.dropLast().last ?? ""        return "\(artist.lowercased())\u{1f}\(album.lowercased())"    }    /// Every song file under `folder`, deepest too, each named by its path    /// under `name` — what the folder is called where it came from (the    /// folder above it too, from a picker: `Artist/Album`), so    /// `Artist/Album (Year)/01 Title.flac` reads whichever was picked. The    /// caller holds the folder's security-scoped access while it brings them in.    public static func songs(in folder: URL, named name: String) -> [MusicFile] {        let root = folder.standardizedFileURL.path(percentEncoded: false)        guard let walk = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { return [] }        var found: [MusicFile] = []        for case let url as URL in walk where songFileExtensions.contains(url.pathExtension.lowercased()) {            let full = url.standardizedFileURL.path(percentEncoded: false)            let below = full.hasPrefix(root) ? String(full.dropFirst(root.count)) : url.lastPathComponent            let path = [name, below].map { $0.trimmingCharacters(in: CharacterSet(charactersIn: "/")) }.filter { !$0.isEmpty }.joined(separator: "/")            found.append(MusicFile(url: url, sourcePath: path))        }        return found.sorted { $0.sourcePath.localizedStandardCompare($1.sourcePath) == .orderedAscending }    }}/// The intake's words where the core says none: from the shell's music set.enum MusicLines {    static func addedMany(_ count: Int) -> String {        ShellLines.line("music", "intake.added_many", ["count": String(count)])    }}