Commit 6c26f454 authored by Kourser's avatar Kourser
Browse files

feat: un livre Calibre téléchargé se voit, et se range avec les autres

Signalé : après « Télécharger et lire », le bouton passe à « Lire » et
c'est le seul indice. Rien dans la grille ne dit ce qui est déjà là, et
l'onglet « Sur l'appareil » l'ignore.

La cause est que le téléchargement n'écrivait que le fichier,
Books/7407.epub, et rien d'autre. Sans le serveur, ce livre n'a plus de
titre, plus d'auteur, plus de couverture — donc rien à afficher dans
l'onglet qui répond précisément à « que puis-je lire sans réseau ? ».

DownloadedBookStore note les quelques champs nécessaires au moment où le
téléchargement aboutit, pendant que la fiche du catalogue est encore
sous la main. Le livre garde son identifiant Calibre, positif : ce n'est
pas une copie, c'est le même livre, ici — position de lecture, résumés
et annotations restent sur la même clé.

Et autour : une pastille sur la couverture côté Calibre pour dire ce qui
est déjà descendu, absente de « Sur l'appareil » où elle ne
distinguerait rien ; « Retirer de l'appareil » qui efface aussi le
fichier, parce que retirer doit rendre la place ; une entrée dont le
fichier a disparu qui est écartée à la relecture, parce qu'afficher un
livre qu'on ne peut pas ouvrir est pire que ne rien afficher ; et
l'adoption des fichiers téléchargés avant ce catalogue, dès que Calibre
peut les nommer.

Un défaut trouvé en chemin : BookPreparation prenait `formats.first`
pour le format du fichier déjà présent. Un livre listant AZW3 et EPUB
donnait « AZW3 » pour un fichier qui était un EPUB. Le format vient
maintenant de l'extension du fichier.

Vérifié dans le simulateur contre scripts/fake-calibre.py, qui sert
désormais un vrai EPUB sur /get/ : téléchargement, pastille verte dans
l'onglet Calibre, puis « 3 livres sur l'appareil » avec le titre et
l'auteur.

Co-Authored-By: default avatarClaude Opus 5 <noreply@anthropic.com>
parent 3bd11d70
Loading
Loading
Loading
Loading
+16 −0
Changes for CHANGELOG.md: 16 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -7,6 +7,22 @@ adopte le [versionnage sémantique](https://semver.org/lang/fr/).

## [Non publié]

### Ajouté
- Un livre Calibre téléchargé apparaît dans « Sur l'appareil », avec son titre
  et son auteur. Le téléchargement n'écrivait que le fichier : sans le serveur,
  ce livre n'avait plus de nom et n'avait nulle part où s'afficher. Les
  quelques champs nécessaires sont maintenant notés au moment du
  téléchargement, pendant que le catalogue est encore sous la main. Il garde
  son identifiant Calibre, donc sa position de lecture, ses résumés et ses
  annotations restent sur la même clé.
- Une pastille sur la couverture, dans l'onglet Calibre, dit ce qui est déjà
  sur l'appareil — sans avoir à ouvrir chaque livre pour le découvrir. Elle ne
  s'affiche pas dans « Sur l'appareil », où elle ne distinguerait rien.
- « Retirer de l'appareil » marche aussi pour un livre Calibre téléchargé : le
  fichier part, la place revient, et le livre reste dans l'onglet Calibre.
- Les fichiers téléchargés avant ce catalogue sont adoptés dès que le
  catalogue Calibre peut les nommer : rien à retélécharger.

### Ajouté
- Les notes de lecture prises bloc par bloc sont gardées sur disque pendant la
  génération d'un résumé, indexées par le contenu du bloc. Un échec en cours de
+162 −0
Changes for Packages/Core/Sources/PodbookUI/Library/DownloadedBookStore.swift: 162 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation
import Observation

/// A Calibre book whose file now sits on this device.
///
/// The file alone is not enough. Downloading used to write
/// `Books/7407.epub` and nothing else, so with the server unreachable that
/// book had no title, no author and no place in « Sur l'appareil » — which is
/// precisely where someone looks for what they can read on the train. The few
/// fields the grid and the detail sheet need are therefore written down beside
/// the file, at download time, while the catalogue is still in hand.
public struct DownloadedBook: Codable, Sendable, Hashable, Identifiable {
    /// The Calibre id, positive — the same one the reading position, the
    /// digests and the annotations are keyed on. A downloaded book is not a
    /// copy of a Calibre book, it is that book, here.
    public var id: Int
    public var title: String
    public var authors: [String]
    public var format: String
    public var byteCount: Int
    public var downloadedOn: Date

    public init(
        id: Int,
        title: String,
        authors: [String] = [],
        format: String,
        byteCount: Int = 0,
        downloadedOn: Date = .now
    ) {
        self.id = id
        self.title = title
        self.authors = authors
        self.format = format.uppercased()
        self.byteCount = byteCount
        self.downloadedOn = downloadedOn
    }
}

/// What has been pulled down from Calibre and kept.
@MainActor
@Observable
public final class DownloadedBookStore {
    public private(set) var books: [DownloadedBook] = []

    private let root: URL
    private let files: BookFileStore

    public init(files: BookFileStore = BookFileStore(), root: URL? = nil) {
        self.files = files
        if let root {
            self.root = root
        } else {
            let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
                ?? FileManager.default.temporaryDirectory
            self.root = base.appendingPathComponent("Podbook/Downloaded", isDirectory: true)
        }
        try? FileManager.default.createDirectory(at: self.root, withIntermediateDirectories: true)
        reload()
    }

    /// Reads the catalogue back, dropping anything whose file has gone.
    ///
    /// The list and the files on disk are two records of the same fact, and
    /// they can drift — a container wiped by a reinstall takes the files and
    /// leaves the catalogue. Showing a book that cannot be opened is worse
    /// than not showing it.
    public func reload() {
        let stored = (try? Data(contentsOf: catalogURL))
            .flatMap { try? JSONDecoder().decode([DownloadedBook].self, from: $0) }
            ?? []
        let present = stored.filter { files.existingFile(bookID: $0.id, format: $0.format) != nil }
        books = present.sorted { $0.downloadedOn > $1.downloadedOn }
        if present.count != stored.count { persist() }
    }

    public func contains(_ bookID: Int) -> Bool {
        books.contains { $0.id == bookID }
    }

    public func book(id: Int) -> DownloadedBook? {
        books.first { $0.id == id }
    }

    public func fileURL(for bookID: Int) -> URL? {
        guard let book = book(id: bookID) else { return nil }
        return files.existingFile(bookID: book.id, format: book.format)
    }

    /// Called the moment a download lands, because that is the only moment the
    /// metadata is guaranteed to be available.
    public func record(_ book: LibraryBook, format: String) {
        let url = files.existingFile(bookID: book.id, format: format)
        let bytes = url
            .flatMap { try? FileManager.default.attributesOfItem(atPath: $0.path)[.size] as? Int }
            ?? book.formatSizes[format.uppercased()]
            ?? 0
        let entry = DownloadedBook(
            id: book.id,
            title: book.title,
            authors: book.authors,
            format: format,
            byteCount: bytes
        )
        books.removeAll { $0.id == entry.id }
        books.insert(entry, at: 0)
        persist()
    }

    /// Removes the file as well: « retirer de l'appareil » means the space
    /// comes back, not that the row disappears while the bytes stay.
    public func forget(_ bookID: Int) {
        guard let book = book(id: bookID) else { return }
        files.remove(bookID: book.id, format: book.format)
        books.removeAll { $0.id == bookID }
        persist()
    }

    /// Picks up files downloaded before this catalogue existed.
    ///
    /// The bytes were already on disk, only their title was missing. As soon
    /// as the Calibre catalogue is in hand again, it supplies it — so a book
    /// pulled down last week stops being invisible in « Sur l'appareil »
    /// without having to be downloaded a second time.
    public func adoptOrphans(from catalogue: [LibraryBook]) {
        var adopted = false
        for book in catalogue where !contains(book.id) {
            for format in book.directlyReadableFormats
            where files.existingFile(bookID: book.id, format: format) != nil {
                record(book, format: format)
                adopted = true
                break
            }
        }
        if adopted { books.sort { $0.downloadedOn > $1.downloadedOn } }
    }

    public var libraryBooks: [LibraryBook] {
        books.map(LibraryBook.init)
    }

    private func persist() {
        guard let data = try? JSONEncoder().encode(books) else { return }
        try? data.write(to: catalogURL, options: .atomic)
    }

    private var catalogURL: URL { root.appendingPathComponent("catalog.json") }
}

public extension LibraryBook {
    init(_ book: DownloadedBook) {
        self.init(
            id: book.id,
            origin: .calibre,
            title: book.title,
            authors: book.authors,
            formats: [book.format],
            formatSizes: [book.format: book.byteCount],
            addedOn: book.downloadedOn
        )
    }
}
+54 −7
Changes for Packages/Core/Sources/PodbookUI/Library/UnifiedLibrary.swift: 54 added lines, 7 removed lines.
Original line number Diff line number Diff line
@@ -25,6 +25,10 @@ public final class UnifiedLibrary {
    }

    public let local: LocalLibraryStore
    /// Calibre books already pulled down. They belong in « Sur l'appareil »
    /// just as much as an imported file: what the tab answers is « que puis-je
    /// lire sans réseau ? », not « d'où vient ce livre ? ».
    public let downloads: DownloadedBookStore
    public private(set) var calibre: LibraryStore?

    public var source: Source {
@@ -44,12 +48,18 @@ public final class UnifiedLibrary {

    public private(set) var importFailure: String?

    public init(local: LocalLibraryStore, calibre: LibraryStore? = nil) {
    public init(
        local: LocalLibraryStore,
        downloads: DownloadedBookStore = DownloadedBookStore(),
        calibre: LibraryStore? = nil
    ) {
        self.local = local
        self.downloads = downloads
        self.calibre = calibre
        // Opens on whichever source has something to show, so a first launch
        // with an empty device library lands on Calibre rather than on a void.
        source = (calibre != nil && local.books.isEmpty) ? .calibre : .onDevice
        let deviceIsEmpty = local.books.isEmpty && downloads.books.isEmpty
        source = (calibre != nil && deviceIsEmpty) ? .calibre : .onDevice
    }

    public var availableSources: [Source] {
@@ -59,6 +69,7 @@ public final class UnifiedLibrary {
    public func attach(calibre: LibraryStore?) {
        self.calibre = calibre
        if calibre == nil, source == .calibre { source = .onDevice }
        adoptExistingDownloads()
    }

    // MARK: - Reading
@@ -94,7 +105,7 @@ public final class UnifiedLibrary {
    /// server, where the index lives.
    private var filteredLocal: [LibraryBook] {
        let needle = searchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        let all = local.libraryBooks
        let all = onDeviceBooks
        guard !needle.isEmpty else { return all }
        return all.filter { book in
            book.title.lowercased().contains(needle)
@@ -102,15 +113,39 @@ public final class UnifiedLibrary {
        }
    }

    /// Everything readable without a server, newest first.
    public var onDeviceBooks: [LibraryBook] {
        (local.libraryBooks + downloads.libraryBooks)
            .sorted { ($0.addedOn ?? .distantPast) > ($1.addedOn ?? .distantPast) }
    }

    public func isOnDevice(_ book: LibraryBook) -> Bool {
        book.isLocal || downloads.contains(book.id)
    }

    public func file(for book: LibraryBook) -> URL? {
        guard book.isLocal, let localBook = local.book(id: book.id) else { return nil }
        if book.isLocal {
            guard let localBook = local.book(id: book.id) else { return nil }
            return local.fileURL(for: localBook)
        }
        return downloads.fileURL(for: book.id)
    }

    // MARK: - Actions

    public func reload() async {
        if source == .calibre { await calibre?.reload() } else { local.reload() }
        if source == .calibre {
            await calibre?.reload()
            adoptExistingDownloads()
        } else {
            local.reload()
        }
    }

    /// Files already on disk that the catalogue can now name.
    func adoptExistingDownloads() {
        guard let calibre else { return }
        downloads.adoptOrphans(from: calibre.books.map(LibraryBook.init))
    }

    public func submitSearch() async {
@@ -127,7 +162,12 @@ public final class UnifiedLibrary {
    }

    public func refresh(bookID: Int) async {
        if bookID < 0 { local.reload() } else { await calibre?.refresh(bookID: bookID) }
        if bookID < 0 {
            local.reload()
        } else {
            downloads.reload()
            await calibre?.refresh(bookID: bookID)
        }
    }

    public func setSort(_ sort: LibraryStore.Sort) async {
@@ -152,12 +192,19 @@ public final class UnifiedLibrary {
        }
        if !messages.isEmpty { importFailure = messages.joined(separator: "\n") }
        if !local.books.isEmpty { source = .onDevice }

    }

    public func clearImportFailure() { importFailure = nil }

    public func remove(_ book: LibraryBook) {
        guard book.isLocal, let localBook = local.book(id: book.id) else { return }
        if book.isLocal {
            guard let localBook = local.book(id: book.id) else { return }
            local.remove(localBook)
            return
        }
        // A downloaded Calibre book: the file goes, the book stays in the
        // Calibre tab, ready to be pulled down again.
        downloads.forget(book.id)
    }
}
+25 −3
Changes for Packages/Core/Sources/PodbookUI/Stores/BookPreparation.swift: 25 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -36,6 +36,9 @@ public final class BookPreparation {
    private let libraryID: String?
    private let files: BookFileStore
    private let capabilities: ServerCapabilities
    /// Written to the moment a download lands, so the book can be found again
    /// without the server.
    private let downloads: DownloadedBookStore?
    private var work: Task<Void, Never>?

    public init(
@@ -44,22 +47,35 @@ public final class BookPreparation {
        libraryID: String? = nil,
        files: BookFileStore = BookFileStore(),
        capabilities: ServerCapabilities = .none,
        localFile: URL? = nil
        localFile: URL? = nil,
        downloads: DownloadedBookStore? = nil
    ) {
        self.book = book
        self.client = client
        self.libraryID = libraryID
        self.files = files
        self.capabilities = capabilities
        self.downloads = downloads

        if let localFile, let format = book.formats.first {
            // Imported onto the device: nothing to fetch, nothing to convert.
        if let localFile, let format = Self.format(of: localFile, fallback: book.formats.first) {
            // Already on this device: nothing to fetch, nothing to convert.
            phase = .ready(url: localFile, format: format)
        } else if let existing = Self.downloadedFile(for: book, in: files) {
            phase = .ready(url: existing.url, format: existing.format)
        }
    }

    /// The format is the file's own, not the first one the catalogue lists.
    ///
    /// A Calibre book often has several — AZW3 and EPUB, say — and the one on
    /// disk is whichever was downloaded. Taking `formats.first` handed the
    /// reader « AZW3 » for a file that was an EPUB.
    static func format(of url: URL, fallback: String?) -> String? {
        let fromFile = url.pathExtension.uppercased()
        if !fromFile.isEmpty { return fromFile }
        return fallback
    }

    static func downloadedFile(
        for book: LibraryBook,
        in files: BookFileStore
@@ -148,6 +164,9 @@ public final class BookPreparation {
            try Task.checkCancellation()

            if let existing = files.existingFile(bookID: book.id, format: format) {
                // Already on disk but not in the catalogue: a file written
                // before this store existed, or a catalogue that lost it.
                downloads?.record(book, format: format)
                phase = .ready(url: existing, format: format)
                return
            }
@@ -156,6 +175,9 @@ public final class BookPreparation {
            let data = try await client.downloadFormat(bookID: book.id, format: format, libraryID: libraryID)
            try Task.checkCancellation()
            let url = try files.write(data, bookID: book.id, format: format)
            // Recorded here and nowhere else: this is the last moment the
            // catalogue entry is in hand.
            downloads?.record(book, format: format)
            phase = .ready(url: url, format: format)
        } catch is CancellationError {
            phase = .notStarted
+24 −2
Changes for Packages/Core/Sources/PodbookUI/Views/LibraryView.swift: 24 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -113,11 +113,19 @@ public struct LibraryView: View {
            LazyVGrid(columns: columns, spacing: 20) {
                ForEach(library.books) { book in
                    Button { selection = book } label: {
                        BookCard(book: book, covers: covers)
                        BookCard(
                            book: book,
                            covers: covers,
                            // Seulement côté Calibre : dans « Sur l'appareil »
                            // tout est sur l'appareil, la pastille n'y
                            // distinguerait rien.
                            isOnDevice: library.source == .calibre
                                && library.isOnDevice(book)
                        )
                    }
                    .buttonStyle(.plain)
                    .contextMenu {
                        if book.isLocal {
                        if library.isOnDevice(book) {
                            Button("Retirer de l'appareil", role: .destructive) {
                                library.remove(book)
                            }
@@ -194,6 +202,9 @@ public struct LibraryView: View {
struct BookCard: View {
    let book: LibraryBook
    let covers: CoverProvider
    /// Shown in the Calibre tab so the grid says, at a glance, what is already
    /// here — otherwise the only way to find out is to open each book.
    var isOnDevice = false

    var body: some View {
        VStack(alignment: .leading, spacing: 6) {
@@ -211,6 +222,17 @@ struct BookCard: View {
                            .help("Conversion nécessaire avant lecture")
                    }
                }
                .overlay(alignment: .bottomTrailing) {
                    if isOnDevice {
                        Image(systemName: "arrow.down.circle.fill")
                            .font(.callout)
                            .symbolRenderingMode(.palette)
                            .foregroundStyle(.white, .green)
                            .padding(5)
                            .accessibilityLabel("Téléchargé sur l'appareil")
                            .help("Téléchargé sur l'appareil")
                    }
                }

            Text(book.title)
                .font(.caption.weight(.medium))
Loading