Commit 55876151 authored by Kourser's avatar Kourser
Browse files

feat: mode autonome sans serveur et tutoriel de bienvenue

Podbook réclamait un serveur Calibre avant de montrer quoi que ce soit.
Un EPUB déposé depuis Fichiers est maintenant un livre comme un autre :
titre, auteur et couverture extraits du fichier, puis lecture,
traduction, narration et résumés. L'app se déclare aussi destinataire des
EPUB et des PDF, donc un livre reçu par mail s'ouvre directement dedans.

Les fichiers sont copiés dans le conteneur de l'app, pas référencés : une
URL remise par Fichiers cesse d'être lisible dès que sa portée est
relâchée, et une bibliothèque qui marche une fois puis plus serait pire
que pas de bibliothèque.

Les deux sources cohabitent dans un sélecteur plutôt que de fusionner :
elles n'ont ni la même taille, ni la même recherche, ni les mêmes
capacités de conversion. Les identifiants locaux sont négatifs et ceux de
Calibre positifs, si bien que les magasins de position, de résumés et de
traduction restent indexés sur un simple entier, sans collision possible.

Le tutoriel de bienvenue fait six étapes, rejouables depuis les réglages,
et présente le serveur Calibre comme facultatif — c'était le point. Les
voix améliorées d'Apple ne peuvent être installées que par le système,
donc l'étape indique le chemin dans les Réglages plutôt que de prétendre
le faire.

Un bug trouvé par les tests : les métadonnées étaient extraites du
fichier déjà renommé en « <id>.epub », donc tout livre sans métadonnée
s'appelait « 1 ». Le nom d'origine est désormais transmis comme titre de
repli.

160 tests au vert.

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

### Ajouté
- Podbook est utilisable sans serveur Calibre : import d'EPUB et de PDF depuis
  Fichiers, iCloud Drive ou la feuille de partage, avec extraction du titre, de
  l'auteur et de la couverture. L'app apparaît dans « Ouvrir dans ».
- Les deux sources cohabitent dans un sélecteur quand un serveur est connecté.
  Les identifiants locaux sont négatifs, ceux de Calibre positifs : les
  positions, résumés et traductions restent indexés sans collision possible.
- Tutoriel de bienvenue en six étapes au premier lancement, rejouable depuis
  les réglages, où le serveur Calibre est explicitement facultatif.
- Résumés parlés : cinq formats (flash, chapitre, le livre en 20 minutes,
  conversation à deux voix, approfondissement) et quatre angles (fidèle, idées
  clés, débutant, critique), sur tout le livre ou à partir de la page lue.
+34 −0
Changes for Info.plist: 34 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -18,6 +18,40 @@
	<key>NSLocalNetworkUsageDescription</key>
	<string>Podbook se connecte au serveur Calibre de votre réseau local pour lire votre bibliothèque.</string>

	<!-- Pour que Podbook apparaisse dans « Ouvrir dans » et dans la feuille de
	     partage : c'est ce qui rend le mode autonome utilisable sans passer par
	     le sélecteur de fichiers. Les formats listés sont ceux que l'app sait
	     ouvrir seule ; le reste demande une conversion, donc un serveur. -->
	<key>LSSupportsOpeningDocumentsInPlace</key>
	<true/>
	<key>CFBundleDocumentTypes</key>
	<array>
		<dict>
			<key>CFBundleTypeName</key>
			<string>EPUB</string>
			<key>CFBundleTypeRole</key>
			<string>Viewer</string>
			<key>LSHandlerRank</key>
			<string>Alternate</string>
			<key>LSItemContentTypes</key>
			<array>
				<string>org.idpf.epub-container</string>
			</array>
		</dict>
		<dict>
			<key>CFBundleTypeName</key>
			<string>PDF</string>
			<key>CFBundleTypeRole</key>
			<string>Viewer</string>
			<key>LSHandlerRank</key>
			<string>Alternate</string>
			<key>LSItemContentTypes</key>
			<array>
				<string>com.adobe.pdf</string>
			</array>
		</dict>
	</array>

	<!-- Sans ceci, la narration s'arrête dès que l'écran s'éteint ou que l'app
	     passe en arrière-plan : c'est la clé qui rend le trajet en voiture
	     possible, et elle ne demande aucune autorisation à Apple. La session
+38 −17
Changes for Packages/Core/Sources/PodbookUI/Library/CoverProvider.swift: 38 added lines, 17 removed lines.
Original line number Diff line number Diff line
import CalibreKit
import Foundation

/// Covers cannot go through `AsyncImage`: the server may require Basic auth and
/// `AsyncImage` sends no headers. So they are fetched through the client, then
/// cached in memory and on disk — a library grid scrolls past hundreds of them.
public actor CoverLoader {
    private let client: CalibreClient
/// Serves covers for both kinds of book.
///
/// Covers cannot go through `AsyncImage`: a Calibre server may require Basic
/// auth and `AsyncImage` sends no headers, and a local cover is a file in the
/// app's own container. So both go through here, cached in memory and on disk —
/// a library grid scrolls past hundreds of them.
public actor CoverProvider {
    private let client: CalibreClient?
    private let libraryID: String?
    private let localCovers: URL?
    private let diskCache: URL?
    private var memory: [Int: Data] = [:]
    private var inFlight: [Int: Task<Data?, Never>] = [:]
    private let memoryLimit: Int

    public init(client: CalibreClient, libraryID: String?, memoryLimit: Int = 300) {
    public init(
        client: CalibreClient? = nil,
        libraryID: String? = nil,
        localCovers: URL? = nil,
        memoryLimit: Int = 300
    ) {
        self.client = client
        self.libraryID = libraryID
        self.localCovers = localCovers
        self.memoryLimit = memoryLimit
        self.diskCache = Self.makeDiskCache()
        diskCache = Self.makeDiskCache()
    }

    public func cover(for bookID: Int) async -> Data? {
        if let cached = memory[bookID] { return cached }
        if let onDisk = readFromDisk(bookID) {
            remember(onDisk, for: bookID)
    public func cover(for book: LibraryBook) async -> Data? {
        if let cached = memory[book.id] { return cached }

        if book.isLocal {
            guard let localCovers else { return nil }
            let url = localCovers.appendingPathComponent("\(abs(book.id)).jpg")
            guard let data = try? Data(contentsOf: url) else { return nil }
            remember(data, for: book.id)
            return data
        }

        if let onDisk = readFromDisk(book.id) {
            remember(onDisk, for: book.id)
            return onDisk
        }
        guard let client else { return nil }
        // Collapse concurrent requests for the same cover into one download.
        if let existing = inFlight[bookID] { return await existing.value }
        if let existing = inFlight[book.id] { return await existing.value }

        let id = book.id
        let task = Task<Data?, Never> { [client, libraryID] in
            try? await client.downloadCover(bookID: bookID, libraryID: libraryID)
            try? await client.downloadCover(bookID: id, libraryID: libraryID)
        }
        inFlight[bookID] = task
        inFlight[id] = task
        let data = await task.value
        inFlight[bookID] = nil
        inFlight[id] = nil
        if let data, !data.isEmpty {
            remember(data, for: bookID)
            writeToDisk(data, bookID: bookID)
            remember(data, for: id)
            writeToDisk(data, bookID: id)
            return data
        }
        return nil
+121 −0
Changes for Packages/Core/Sources/PodbookUI/Library/LibraryBook.swift: 121 added lines, 0 removed lines.
Original line number Diff line number Diff line
import CalibreKit
import Foundation

/// A book in the library, whatever it came from.
///
/// Podbook has to work with no Calibre server at all — a file dropped in from
/// the Files app is a first-class book, not a degraded one. So the grid, the
/// detail sheet and the reader all speak this type, and the two sources adapt
/// into it.
///
/// `id` is deliberately a plain `Int` with a sign convention: Calibre ids are
/// positive, locally imported books get negative ones. That keeps the reading
/// position, digest and translation stores keyed exactly as before, with no
/// chance of a local book colliding with a Calibre one.
public struct LibraryBook: Identifiable, Hashable, Sendable {
    public enum Origin: Hashable, Sendable {
        case calibre
        case local
    }

    public var id: Int
    public var origin: Origin
    public var title: String
    public var authors: [String]
    public var series: String?
    public var seriesIndex: Double?
    public var tags: [String]
    public var starsOutOfFive: Double?
    public var comments: String?
    public var publisher: String?
    public var languages: [String]
    public var identifiers: [String: String]
    public var formats: [String]
    public var formatSizes: [String: Int]
    public var publishedOn: Date?
    public var addedOn: Date?

    public init(
        id: Int,
        origin: Origin,
        title: String,
        authors: [String] = [],
        series: String? = nil,
        seriesIndex: Double? = nil,
        tags: [String] = [],
        starsOutOfFive: Double? = nil,
        comments: String? = nil,
        publisher: String? = nil,
        languages: [String] = [],
        identifiers: [String: String] = [:],
        formats: [String] = [],
        formatSizes: [String: Int] = [:],
        publishedOn: Date? = nil,
        addedOn: Date? = nil
    ) {
        self.id = id
        self.origin = origin
        self.title = title
        self.authors = authors
        self.series = series
        self.seriesIndex = seriesIndex
        self.tags = tags
        self.starsOutOfFive = starsOutOfFive
        self.comments = comments
        self.publisher = publisher
        self.languages = languages
        self.identifiers = identifiers
        self.formats = formats
        self.formatSizes = formatSizes
        self.publishedOn = publishedOn
        self.addedOn = addedOn
    }

    public var authorLine: String { authors.joined(separator: ", ") }

    /// Formats the reader opens without a conversion step.
    public var directlyReadableFormats: [String] {
        formats.filter { CalibreBook.nativeFormats.contains($0.uppercased()) }
    }

    public var needsConversion: Bool {
        !formats.isEmpty && directlyReadableFormats.isEmpty
    }

    public var isLocal: Bool { origin == .local }
}

public extension LibraryBook {
    init(_ book: CalibreBook) {
        self.init(
            id: book.id,
            origin: .calibre,
            title: book.title,
            authors: book.authors,
            series: book.series,
            seriesIndex: book.seriesIndex,
            tags: book.tags,
            starsOutOfFive: book.starsOutOfFive,
            comments: book.comments,
            publisher: book.publisher,
            languages: book.languages,
            identifiers: book.identifiers,
            formats: book.formats,
            formatSizes: book.formatMetadata.compactMapValues(\.size),
            publishedOn: book.pubdate?.date,
            addedOn: book.timestamp?.date
        )
    }

    init(_ book: LocalBook) {
        self.init(
            id: book.id,
            origin: .local,
            title: book.title,
            authors: book.authors,
            formats: [book.format.uppercased()],
            formatSizes: [book.format.uppercased(): book.byteCount],
            addedOn: book.addedOn
        )
    }
}
+55 −0
Changes for Packages/Core/Sources/PodbookUI/Library/LocalBook.swift: 55 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation

/// A book imported straight onto the device, with no Calibre server involved.
public struct LocalBook: Codable, Sendable, Hashable, Identifiable {
    /// Always negative, so it can never collide with a Calibre id.
    public var id: Int
    public var title: String
    public var authors: [String]
    public var format: String
    /// Name inside the local library folder, not the original path: the file is
    /// copied in at import, because a URL handed over by the Files app stops
    /// being readable once its security scope is released.
    public var fileName: String
    public var byteCount: Int
    /// SHA-256 of the file, so importing the same book twice is recognised
    /// whatever it was called the second time.
    public var contentHash: String
    public var addedOn: Date

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

public enum LocalImportError: Error, Sendable, Hashable, LocalizedError {
    case unreadable(String)
    case unsupportedFormat(String)
    case alreadyImported(String)

    public var errorDescription: String? {
        switch self {
        case .unreadable(let name): "Fichier illisible : \(name)"
        case .unsupportedFormat(let ext):
            "Podbook ne sait pas ouvrir un fichier .\(ext). Les formats Kindle demandent une conversion, "
                + "donc un serveur Calibre."
        case .alreadyImported(let title): "« \(title) » est déjà dans la bibliothèque."
        }
    }
}
Loading