Cotton code
120 lines · 5.4 KB · SwiftRaw
// Putting a shared book on the shelf, and handing a Goodreads library to the// object — the two things the share drain's book branches ask of the core.//// A seam (`BookShelving`) for `MediaCapturing`'s reason: a drain test drives// both branches with no core, no file on disk and no object.import Foundation/// What the drain's book branches need.public protocol BookShelving: Sendable {    /// The book file at `url` read for what it says about itself, kept, and    /// written as a new `book` row — or, `into` a book with no file (its Add    /// file), given to that book; answers that row's id. Blocking work: call    /// it off the main actor.    func shelve(_ url: URL, format: BookFormat, fileName: String?, into book: String?) async throws -> String    /// A Goodreads library export's text, handed to the object's    /// `import_goodreads`: the object makes or brings up to date one book per    /// row and the phone takes them by sync. Answers the book the phone lands    /// on (the answer's `first`: the first the import made, else the first it    /// found again); nil for an export of no books.    func importGoodreads(_ text: String) async throws -> String?}/// The shipping shelf: `capture.media` as a book — an EPUB with its format/// alone, the core reading what it says; a PDF read here (`BookFile`), its/// cover beside it — so the book row is made with its bytes in the store/// before the app opens it.public struct CoreBookShelf: BookShelving {    private let core: any CottonCalling    public init(core: any CottonCalling) {        self.core = core    }    public func shelve(_ url: URL, format: BookFormat, fileName: String?, into book: String?) async throws -> String {        // An EPUB is read by the core, its OPF and its cover, as Android's is.        guard format == .pdf else {            let kept = try await core.call(                CottonMethod.captureMedia,                BookCaptureRequest(epub: url.path(percentEncoded: false), filename: fileName, into: book),                as: MediaCaptured.self)            return kept.recordId        }        let facts = try BookFile.read(url, fileName: fileName)        let scratch = MediaTiers.scratchDirectory()        defer { MediaTiers.discard(scratch) }        var coverPath: String?        if let cover = facts.cover {            let file = scratch.appendingPathComponent("cover").appendingPathExtension(facts.coverExtension ?? "jpg")            try cover.write(to: file)            coverPath = file.path(percentEncoded: false)        }        let kept = try await core.call(            CottonMethod.captureMedia,            BookCaptureRequest(path: url.path(percentEncoded: false), facts: facts, filename: fileName, coverPath: coverPath, into: book),            as: MediaCaptured.self)        return kept.recordId    }    public func importGoodreads(_ text: String) async throws -> String? {        let request: [String: JSONValue] = ["act": .string(BookActs.importGoodreads), "args": .object(["file": .string(text)])]        let answer = try await core.callJSON(CottonMethod.objectAct, request)        return answer[BookActs.importedFirst]?.string.flatMap { $0.isEmpty ? nil : $0 }    }}/// The object's acts the books ask for by name (`object.act`).enum BookActs {    public static let importGoodreads = "import_goodreads"    /// The key of `import_goodreads`' answer naming the book to land on.    public static let importedFirst = "first"}/// `capture.media` for a book: the file, what it says about itself, and its/// cover's path in this call's scratch folder. The core keeps the file under/// the book media kind (`<database>/books/<sha256>.<ext>`), writes the cover/// as the row's picture and makes the `book` row: `file`, `format`, `source`/// file, `status` want_to_read, `added_on` today and these facts.struct BookCaptureRequest: Encodable, Sendable, Equatable {    public var path: String    public var mime: String    public var kind = "book"    public var filename: String?    public var book: Facts    public var coverPath: String?    /// The book this file is for (its Add file); absent, a book of its own.    public var into: String?    /// The facts as the row takes them; an absent one is left out.    public struct Facts: Encodable, Sendable, Equatable {        public var format: String        /// A PDF's; an EPUB's title is the core's to read.        public var title: String?        public var author: String?        public var language: String?        public var isbn: String?        public var pages: Int?    }    public init(path: String, facts: BookFacts, filename: String?, coverPath: String?, into: String? = nil) {        self.path = path        self.mime = facts.format.mime        self.filename = filename        self.book = Facts(format: facts.format.rawValue, title: facts.title, author: facts.author,                          language: facts.language, isbn: facts.isbn, pages: facts.pages)        self.coverPath = coverPath        self.into = into    }    /// An EPUB, sent with its format alone: the core reads its OPF (title,    /// first creator, language, ISBN) and its cover.    public init(epub path: String, filename: String?, into: String? = nil) {        self.path = path        self.mime = BookFormat.epub.mime        self.filename = filename        self.book = Facts(format: BookFormat.epub.rawValue)        self.into = into    }}