// 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.importCottonValuesimportFoundation/// 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.publicstructMusicFile: Sendable, Equatable {publicvar url: URLpublicvar sourcePath: Stringpublicinit(url: URL, sourcePath: String) {self.url = urlself.sourcePath = sourcePath }}/// What one song came to (`music.capture`'s answer).publicstructMusicOutcome: Decodable, Sendable, Equatable {/// `added`, `here`, `better`, `worse` or `refused`.publicvar outcome: Stringpublicvar id: String?publicvar title: String?publicvar line: String?publicvar sourcePath: String?}/// What a whole intake came to.publicstructMusicIntakeResult: Sendable, Equatable {publicvar outcomes: [MusicOutcome]/// What to tell the person, in the core's words.publicvar said: String?/// The one album an album ZIP came in as (`bringZip`).publicvar album: String?/// The song to open: the last one that came in, else the one already here.publicvar 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.publiclet 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 {privatelet core: any CottonCalling/// How far it has got: files read and brought in, of all of them.privatelet progress: @Sendable (_ done: Int, _ total: Int) -> Voidpublicinit(core: any CottonCalling, progress: @escaping @Sendable (_ done: Int, _ total: Int) -> Void = { _, _ in }) {self.core = coreself.progress = progress }structRequest: Encodable {var songs: [Song]var zip: Zip?structSong: Encodable {var path: Stringvar sourcePath: Stringvar tags: SongTagsvar 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.structZip: Encodable {var name: Stringvar boughtOn: String?var storeUrl: String?var storeId: String?var bookletPath: String? } }privatestructAnswer: 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.structUnzipped: Decodable {structSong: Decodable {var entry: Stringvar path: Stringvar 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).publicenumZipOutcome: 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.publicfunc bringZip(_ url: URL, name: String) asyncthrows -> ZipOutcome {let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("music-zip-\(UUID().uuidString)", isDirectory: true)tryFileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: scratch) } progress(0, 1)let opened = tryawait core.call(CottonMethod.musicZip, ["path": url.path(percentEncoded: false), "name": name, "into": scratch.appendingPathComponent("album", isDirectory: true).path(percentEncoded: false)],as: Unzipped.self)iflet 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 = tryawait 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.publicfunc bring(_ files: [MusicFile]) asyncthrows -> MusicIntakeResult {let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("music-intake-\(UUID().uuidString)", isDirectory: true)tryFileManager.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 = 0for 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 = tryawait 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 }returnMusicIntakeResult(outcomes: outcomes, said: said) }/// The most songs one write takes: the core's own ceiling.staticlet mostInOne = 400/// One file read: its tags, a `.lrc` beside it, its folder's cover.staticfunc 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")iflet lrc = BoundedText.read(beside, most: LRC.mostBytes), LRC.looksTimed(lrc) { tags.syncedLyrics = lrc tags.lyricsBeside = true } }var cover = read?.pictureif 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)) } }returnRequest.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.staticfunc 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.publicstaticfunc songs(in folder: URL, named name: String) -> [MusicFile] {let root = folder.standardizedFileURL.path(percentEncoded: false)guardlet walk = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { return [] }var found: [MusicFile] = []forcaselet 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.lastPathComponentlet 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.enumMusicLines {staticfunc addedMany(_ count: Int) -> String {ShellLines.line("music", "intake.added_many", ["count": String(count)]) }}