// Books' Add a folder (the coordinator, 7 Nov 2026): a picked tree — a // Calibre library, or a folder of EPUBs and PDFs — handed WHOLE to the core's // `books.folder`, which reads it (a Calibre book from its metadata.opf and // cover.jpg first, its EPUB second; a bare PDF a book by its name) and lands // each book through capture.media's one writer. The shell only lists the // files: every one in the tree, by where it is staged and its path below the // folder; what is a book, and every word said of it, is the core's. import Foundation /// One file of the picked tree, as `books.folder` takes it. public struct BookFolderFile: Encodable, Equatable, Sendable { /// Where the file is staged on this phone. public var path: String /// Its path below the picked folder, `/` between parts. public var name: String public init(path: String, name: String) { self.path = path self.name = name } } /// What `books.folder` answered: each book and how it came in, and its words. public struct BookFolderAnswer: Decodable, Equatable, Sendable { public struct Book: Decodable, Equatable, Sendable { public var id: String? public var title: String /// `added`, `already` (the same file is a book here) or `refused`. public var outcome: String /// Why a refused book was refused, in the core's words. public var why: String? } public var books: [Book] public var words: String /// The book the app stands on: the first that is a book here now. public var landing: String? { books.lazy.compactMap(\.id).first { !$0.isEmpty } } /// What is said: the core's words, and each refused book's own why. public var said: String { ([words] + books.compactMap { book in book.why.map { "\(book.title): \($0)" } }).joined(separator: "\n") } } public enum BookFolder { /// Every file below `folder`, hidden ones aside, named by its path below /// it; in name order. public static func files(in folder: URL) -> [BookFolderFile] { let root = folder.standardizedFileURL.path(percentEncoded: false) guard let walk = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { return [] } var found: [BookFolderFile] = [] for case let url as URL in walk where (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true { let full = url.standardizedFileURL.path(percentEncoded: false) let below = full.hasPrefix(root) ? String(full.dropFirst(root.count)) : url.lastPathComponent found.append(BookFolderFile(path: full, name: below.trimmingCharacters(in: CharacterSet(charactersIn: "/")))) } return found.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } /// The tree through `books.folder`. public static func bring(_ files: [BookFolderFile], core: any CottonCalling) async throws -> BookFolderAnswer { struct Request: Encodable { let files: [BookFolderFile] } return try await core.call(CottonMethod.booksFolder, Request(files: files), as: BookFolderAnswer.self) } }