Commit f0859242 authored by Kourser's avatar Kourser
Browse files

fix: authentification Calibre et lecture PDF sur iPad

Deux choses constatées, l'une sur le vrai serveur et l'autre dans le
simulateur.

La connexion échouait toujours, en 400 « Unsupported authentication
method ». L'app envoyait un en-tête Basic d'emblée ; un calibre-server
en mode Digest refuse cela par un 400 et non un 401, et le rejeu ne se
déclenchait que sur 401. Plus rien n'est donc envoyé avant que le
serveur ne le demande, et 400 comme 401 sont lus comme un challenge —
Basic ou Digest. Un aller-retour de plus sur la toute première requête,
et une danse qui marche pour les deux schémas.

Vérifié contre levr.kourser.bzh : sans en-tête il répond 401 avec le
challenge Digest, avec un en-tête Basic il répond 400.

Côté lecture, le lecteur s'ouvrait en feuille par-dessus la feuille de
détail. Une feuille sur une feuille, sur un iPad, c'est un timbre-poste
au milieu de l'écran avec la fiche encore visible derrière. Il prend
maintenant tout l'écran.

Et un PDF de vingt-quatre pages n'avait aucun contrôle : ni numéro de
page, ni moyen d'aller ailleurs. Il y a désormais le numéro de page, une
réglette et un pas de chaque côté. Le saut n'a lieu qu'au relâchement du
doigt : redessiner à chaque cran d'un document de quatre cents pages est
inutilisable. Le thème et le mode de pagination des réglages de lecture
s'appliquent aussi au PDF, et un tap escamote le chrome comme pour
l'EPUB.

223 tests au vert, et cette fois vérifié dans le simulateur iPad : la
réglette va bien de la page 1 à la page 18 et la position suit.

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

## [Non publié]

### Corrigé
- La connexion à un calibre-server échouait toujours, en 400 « Unsupported
  authentication method ». L'app envoyait un en-tête Basic d'emblée, ce qu'un
  serveur en mode Digest refuse par un 400 et non un 401 — et le rejeu ne se
  déclenchait que sur 401. Plus rien n'est envoyé avant que le serveur ne le
  demande, et 400 comme 401 sont lus comme un challenge. Vérifié contre un
  vrai serveur.
- Le lecteur s'ouvrait en feuille par-dessus la feuille de détail : sur iPad,
  un timbre-poste au milieu de l'écran. Il prend maintenant tout l'écran.

### Ajouté
- Contrôles de lecture PDF : numéro de page, réglette de navigation et un pas
  de chaque côté. Le saut n'a lieu qu'au relâchement du doigt.
- Le thème et le mode de pagination des réglages de lecture s'appliquent aussi
  au PDF, et un tap escamote le chrome comme pour l'EPUB.
- Surlignages en cinq couleurs depuis le menu de sélection, note libre par
  surlignage, et marque-page bascule sur la page courante.
- Liste des annotations rangée dans l'ordre du livre, filtrable, avec export
+6 −5
Changes for Packages/Core/Sources/CalibreKit/CalibreClient.swift: 6 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -270,14 +270,15 @@ public struct CalibreClient: Sendable {
    /// Sends the request, and answers an authentication challenge if one comes
    /// back.
    ///
    /// `calibre-server` defaults to `--auth-mode auto`, which means **Digest**.
    /// A client that only knows Basic gets a 401 with correct credentials and no
    /// way to tell why — so a 401 carrying a Digest challenge is learned and the
    /// request replayed once, signed.
    /// Nothing is sent until the server asks. `calibre-server` defaults to
    /// `--auth-mode auto`, which means **Digest**, and it answers a
    /// pre-emptive Basic header with `400 Unsupported authentication method`
    /// rather than a 401 — so both statuses are treated as a challenge, the
    /// scheme is learned, and the request is replayed once, signed.
    func send(_ request: HTTPRequest) async throws -> HTTPResponse {
        let response = try await transport.send(await prepared(request))

        guard response.status == 401,
        guard response.status == 401 || response.status == 400,
              server.credentials != nil,
              await authentication.learn(from: response)
        else { return response }
+48 −22
Changes for Packages/Core/Sources/CalibreKit/DigestAuthentication.swift: 48 added lines, 22 removed lines.
Original line number Diff line number Diff line
@@ -160,27 +160,34 @@ extension URL {
    }
}

/// Remembers the server's Digest challenge between requests.
/// What the server said it wants.
public enum AuthenticationScheme: Sendable, Hashable {
    case basic(realm: String?)
    case digest(DigestChallenge)
}

/// Remembers the server's authentication challenge between requests.
///
/// Without it every single call would cost two round trips: one to be refused,
/// one to answer the challenge. The nonce count increments as the RFC requires,
/// and a fresh challenge — the server rotates its nonce — simply replaces the
/// old one.
/// **Nothing is sent before the server asks.** Sending Basic pre-emptively
/// looks harmless and is not: `calibre-server` in Digest mode answers a Basic
/// header with `400 Unsupported authentication method`, not a 401 — so a client
/// that only retries on 401 never sees the challenge and reports a flat 400
/// with correct credentials. One extra round trip on the very first request
/// buys a dance that works for both schemes.
public actor AuthenticationCache {
    private var challenge: DigestChallenge?
    private var scheme: AuthenticationScheme?
    private var nonceCount = 0

    public init() {}

    /// The header to send, or `nil` to send none.
    /// The header to send, or `nil` while the server has not asked.
    func authorization(for request: HTTPRequest, server: CalibreServer) -> String? {
        guard let credentials = server.credentials else { return nil }
        guard let challenge else {
            // Nothing learned yet: Basic costs one round trip against a server
            // in Basic mode, and is simply refused by one in Digest mode — at
            // which point the challenge arrives and is cached.
        guard let credentials = server.credentials, let scheme else { return nil }

        switch scheme {
        case .basic:
            return server.basicAuthorizationHeader
        }
        case .digest(let challenge):
            nonceCount += 1
            let authenticator = DigestAuthenticator(
                challenge: challenge,
@@ -191,24 +198,43 @@ public actor AuthenticationCache {
                method: request.method,
                uri: request.url.digestURI,
                nonceCount: nonceCount
        ) ?? server.basicAuthorizationHeader
            )
        }
    }

    /// Reads a challenge out of a 401. Returns `true` when it is worth retrying.
    /// Reads a challenge out of a refusal. Returns `true` when it is worth
    /// retrying.
    ///
    /// 400 is accepted alongside 401 on purpose: that is the status Calibre
    /// uses when the scheme itself is wrong.
    func learn(from response: HTTPResponse) -> Bool {
        guard response.status == 401 else { return false }
        let header = response.headers["www-authenticate"]
        guard response.status == 401 || response.status == 400 else { return false }
        guard let header = response.headers["www-authenticate"]
            ?? response.headers["WWW-Authenticate"]
        guard let header, let parsed = DigestChallenge(header: header) else { return false }
        // A rotated nonce is a new challenge, and the count restarts with it.
        let isNew = parsed != challenge
        challenge = parsed
        else { return false }

        let next: AuthenticationScheme
        if let digest = DigestChallenge(header: header) {
            next = .digest(digest)
        } else if header.trimmingCharacters(in: .whitespaces).lowercased().hasPrefix("basic") {
            let realm = DigestChallenge.parameters(
                in: String(header.trimmingCharacters(in: .whitespaces).dropFirst("basic".count))
            )["realm"]
            next = .basic(realm: realm)
        } else {
            return false
        }

        // Nothing new to try if the server repeats itself: that means the
        // credentials are wrong, not the scheme.
        let isNew = next != scheme
        scheme = next
        nonceCount = 0
        return isNew
    }

    public func reset() {
        challenge = nil
        scheme = nil
        nonceCount = 0
    }
}
+26 −3
Changes for Packages/Core/Sources/PodbookUI/Views/BookDetailView.swift: 26 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -50,9 +50,7 @@ public struct BookDetailView: View {
            // A conversion adds a format to the library: let the grid know.
            if case .ready = phase, book.needsConversion { onFormatAdded() }
        }
        .sheet(item: $reading) { file in
            ReaderView(file: file, book: book, services: services)
        }
        .modifier(ReaderPresentation(file: $reading, book: book, services: services))
    }

    private var header: some View {
@@ -220,3 +218,28 @@ extension String {
            .trimmingCharacters(in: .whitespacesAndNewlines)
    }
}


/// Presents the reader over everything.
///
/// It used to be a sheet, and a sheet opened from the detail sheet is a sheet
/// on a sheet: on an iPad that left a postage stamp in the middle of the
/// screen with the card still visible behind it. A book deserves the display.
private struct ReaderPresentation: ViewModifier {
    @Binding var file: ReadableFile?
    let book: LibraryBook
    let services: ReadingServices

    func body(content: Content) -> some View {
        #if canImport(UIKit)
        content.fullScreenCover(item: $file) { file in
            ReaderView(file: file, book: book, services: services)
        }
        #else
        content.sheet(item: $file) { file in
            ReaderView(file: file, book: book, services: services)
                .frame(minWidth: 700, minHeight: 800)
        }
        #endif
    }
}
+253 −64
Changes for Packages/Core/Sources/PodbookUI/Views/ReaderView.swift: 253 added lines, 64 removed lines.
Original line number Diff line number Diff line
@@ -236,10 +236,10 @@ public struct ReaderView: View {
            PDFReaderView(
                file: file,
                locations: locations,
                preferences: services.readerPreferences,
                onSelection: { pdfSelection = $0 },
                onTextSource: { source in textSource = source }
                onNarrationSource: { source in textSource = source }
            )
            .ignoresSafeArea(edges: .bottom)
        case "EPUB":
            #if canImport(ReadiumNavigator)
            EPUBReaderView(
@@ -293,13 +293,69 @@ private struct DrivingCoverModifier: ViewModifier {

// MARK: - PDF

/// PDFKit on both platforms; only the representable wrapper differs. The page
/// is recorded so a PDF resumes where it was left, like an EPUB.
/// Drives the `PDFView` from SwiftUI.
///
/// PDFKit keeps the page state inside its own view, so something has to hold a
/// reference to it for a scrubber or a page button to mean anything. Weak, so
/// the controller never outlives the view it points at.
@MainActor
@Observable
final class PDFController {
    private(set) var currentPage = 0
    private(set) var pageCount = 0
    private(set) var selection: String?

    fileprivate weak var view: PDFView?

    var hasPrevious: Bool { currentPage > 0 }
    var hasNext: Bool { currentPage + 1 < pageCount }

    /// 0…1, for the scrubber and for the stored reading position.
    var progression: Double {
        pageCount > 1 ? Double(currentPage) / Double(pageCount - 1) : 0
    }

    func attach(_ view: PDFView) {
        self.view = view
        pageCount = view.document?.pageCount ?? 0
        syncCurrentPage()
    }

    func go(to page: Int) {
        guard let view, let document = view.document else { return }
        let clamped = min(max(page, 0), max(document.pageCount - 1, 0))
        guard let target = document.page(at: clamped) else { return }
        view.go(to: target)
        currentPage = clamped
    }

    func next() { go(to: currentPage + 1) }
    func previous() { go(to: currentPage - 1) }

    fileprivate func syncCurrentPage() {
        guard let view, let document = view.document, let page = view.currentPage else { return }
        currentPage = document.index(for: page)
        pageCount = document.pageCount
    }

    fileprivate func syncSelection() {
        let text = view?.currentSelection?.string?
            .trimmingCharacters(in: .whitespacesAndNewlines)
        selection = (text?.isEmpty ?? true) ? nil : text
    }
}

/// A PDF, with the controls a 400-page report needs.
struct PDFReaderView: View {
    let file: ReadableFile
    let locations: ReadingLocationStore
    let preferences: ReaderPreferencesStore
    let onSelection: (String?) -> Void
    let onTextSource: (@escaping (DigestScope) async -> [NarrationSegment]) -> Void
    let onNarrationSource: (@escaping (DigestScope) async -> [NarrationSegment]) -> Void

    @State private var controller = PDFController()
    @State private var isChromeVisible = true
    @State private var scrubbing: Double?

    var body: some View {
        let initialPage = locations
@@ -309,27 +365,24 @@ struct PDFReaderView: View {
        PDFViewRepresentable(
            url: file.url,
            initialPage: initialPage,
            onPage: { page, total in
                locations.save(
                    ReadingLocation(
                        locator: String(page),
                        progression: total > 1 ? Double(page) / Double(total - 1) : 0
                    ),
                    bookID: file.bookID,
                    format: file.format
                )
            },
            onSelection: onSelection
            controller: controller,
            preferences: preferences.preferences,
            onPageChange: { savePosition() },
            onSelection: onSelection,
            onTap: { isChromeVisible.toggle() }
        )
        .ignoresSafeArea(edges: .bottom)
        .safeAreaInset(edge: .bottom) {
            if isChromeVisible, controller.pageCount > 0 { footer }
        }
        .onDisappear {
            let locations = locations
            Task { await locations.flush() }
        }
        .task {
            let url = file.url
            let startPage = locations.location(bookID: file.bookID, format: file.format)
                .flatMap { Int($0.locator) }
            onTextSource { scope in
            let startPage = initialPage
            onNarrationSource { scope in
                PDFTextSource.segments(
                    of: url,
                    fromPage: scope == .fromCurrentPosition ? startPage : nil
@@ -337,35 +390,64 @@ struct PDFReaderView: View {
            }
        }
    }

    /// Page number, scrubber, and a step either side — the three things that
    /// were missing and that make a long document navigable.
    private var footer: some View {
        VStack(spacing: 6) {
            HStack(spacing: 18) {
                Button { controller.previous() } label: {
                    Image(systemName: "chevron.left")
                }
                .disabled(!controller.hasPrevious)

/// Speakable text out of a PDF, one segment per sentence, located by page.
///
/// A scanned PDF yields nothing here — it needs the OCR pass from the pipeline
/// before it can be narrated.
enum PDFTextSource {
    static func segments(of url: URL, fromPage: Int? = nil, limit: Int = 2500) -> [NarrationSegment] {
        guard let document = PDFDocument(url: url) else { return [] }
        var segments: [NarrationSegment] = []
        let pageCount = document.pageCount
        let first = min(max(fromPage ?? 0, 0), max(pageCount - 1, 0))
        for index in first..<pageCount {
            if segments.count >= limit { break }
            guard let text = document.page(at: index)?.string, !text.isEmpty else { continue }
            let progression = pageCount > 1 ? Double(index) / Double(pageCount - 1) : 0
            for sentence in SentenceSegmenter.sentences(in: text) {
                segments.append(NarrationSegment(
                    text: sentence,
                    locator: String(index),
                    progression: progression
                ))
                Slider(
                    value: Binding(
                        get: { scrubbing ?? Double(controller.currentPage) },
                        set: { scrubbing = $0 }
                    ),
                    in: 0...Double(max(controller.pageCount - 1, 1)),
                    step: 1,
                    onEditingChanged: { editing in
                        // Jump once, when the finger lifts: re-rendering on
                        // every tick of a 400-page document is unusable.
                        if !editing, let target = scrubbing {
                            controller.go(to: Int(target))
                            savePosition()
                            scrubbing = nil
                        }
                    }
        return segments
                )

                Button { controller.next() } label: {
                    Image(systemName: "chevron.right")
                }
                .disabled(!controller.hasNext)
            }
            .buttonStyle(.plain)

            Text("Page \(Int(scrubbing ?? Double(controller.currentPage)) + 1) sur \(controller.pageCount)")
                .font(.caption.monospacedDigit())
                .foregroundStyle(.secondary)
        }
        .padding(.horizontal, 20)
        .padding(.vertical, 10)
        .background(.bar)
    }

/// Watches page and selection changes.
    private func savePosition() {
        locations.save(
            ReadingLocation(
                locator: String(controller.currentPage),
                progression: controller.progression
            ),
            bookID: file.bookID,
            format: file.format
        )
    }
}

/// Watches page and selection changes, and the tap that hides the chrome.
///
/// Selector-based observation on purpose: the block-based API would need an
/// explicit `removeObserver` in `deinit`, which a nonisolated deinit cannot do
@@ -373,13 +455,22 @@ enum PDFTextSource {
/// automatically when the coordinator is deallocated.
@MainActor
final class PDFCoordinator: NSObject {
    private let onPage: (Int, Int) -> Void
    private let controller: PDFController
    private let onPageChange: () -> Void
    private let onSelection: (String?) -> Void
    private let onTap: () -> Void
    private weak var view: PDFView?

    init(onPage: @escaping (Int, Int) -> Void, onSelection: @escaping (String?) -> Void) {
        self.onPage = onPage
    init(
        controller: PDFController,
        onPageChange: @escaping () -> Void,
        onSelection: @escaping (String?) -> Void,
        onTap: @escaping () -> Void
    ) {
        self.controller = controller
        self.onPageChange = onPageChange
        self.onSelection = onSelection
        self.onTap = onTap
        super.init()
    }

@@ -398,17 +489,17 @@ final class PDFCoordinator: NSObject {
    }

    @objc private func pageDidChange() {
        guard let view,
              let document = view.document,
              let current = view.currentPage
        else { return }
        onPage(document.index(for: current), document.pageCount)
        controller.syncCurrentPage()
        onPageChange()
    }

    @objc private func selectionDidChange() {
        let text = view?.currentSelection?.string?
            .trimmingCharacters(in: .whitespacesAndNewlines)
        onSelection(text?.isEmpty == true ? nil : text)
        controller.syncSelection()
        onSelection(controller.selection)
    }

    @objc func handleTap() {
        onTap()
    }
}

@@ -416,52 +507,150 @@ final class PDFCoordinator: NSObject {
struct PDFViewRepresentable: UIViewRepresentable {
    let url: URL
    let initialPage: Int?
    let onPage: (Int, Int) -> Void
    let controller: PDFController
    let preferences: ReaderPreferences
    let onPageChange: () -> Void
    let onSelection: (String?) -> Void
    let onTap: () -> Void

    func makeCoordinator() -> PDFCoordinator {
        PDFCoordinator(onPage: onPage, onSelection: onSelection)
        PDFCoordinator(
            controller: controller,
            onPageChange: onPageChange,
            onSelection: onSelection,
            onTap: onTap
        )
    }

    func makeUIView(context: Context) -> PDFView {
        let view = configuredPDFView(url: url, initialPage: initialPage)
        let view = configuredPDFView(url: url, initialPage: initialPage, preferences: preferences)
        context.coordinator.observe(view)
        controller.attach(view)

        // `cancelsTouchesInView = false` so the tap still reaches PDFKit for
        // selection and link following.
        let tap = UITapGestureRecognizer(
            target: context.coordinator,
            action: #selector(PDFCoordinator.handleTap)
        )
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
        return view
    }

    func updateUIView(_ view: PDFView, context: Context) {}
    func updateUIView(_ view: PDFView, context: Context) {
        apply(preferences, to: view)
    }
}
#else
struct PDFViewRepresentable: NSViewRepresentable {
    let url: URL
    let initialPage: Int?
    let onPage: (Int, Int) -> Void
    let controller: PDFController
    let preferences: ReaderPreferences
    let onPageChange: () -> Void
    let onSelection: (String?) -> Void
    let onTap: () -> Void

    func makeCoordinator() -> PDFCoordinator {
        PDFCoordinator(onPage: onPage, onSelection: onSelection)
        PDFCoordinator(
            controller: controller,
            onPageChange: onPageChange,
            onSelection: onSelection,
            onTap: onTap
        )
    }

    func makeNSView(context: Context) -> PDFView {
        let view = configuredPDFView(url: url, initialPage: initialPage)
        let view = configuredPDFView(url: url, initialPage: initialPage, preferences: preferences)
        context.coordinator.observe(view)
        controller.attach(view)
        return view
    }

    func updateNSView(_ view: PDFView, context: Context) {}
    func updateNSView(_ view: PDFView, context: Context) {
        apply(preferences, to: view)
    }
}
#endif

/// Theme and page layout come from the same settings as the EPUB reader, so a
/// sepia night-time habit holds across formats.
@MainActor
private func configuredPDFView(url: URL, initialPage: Int?) -> PDFView {
    let view = PDFView()
    view.autoScales = true
private func apply(_ preferences: ReaderPreferences, to view: PDFView) {
    switch preferences.layout {
    case .paginated:
        view.displayMode = .singlePage
        view.displayDirection = .horizontal
        #if canImport(UIKit)
        view.usePageViewController(true)
        #endif
    case .scrolled:
        #if canImport(UIKit)
        view.usePageViewController(false)
        #endif
        view.displayMode = .singlePageContinuous
        view.displayDirection = .vertical
    let document = PDFDocument(url: url)
    }

    #if canImport(UIKit)
    view.backgroundColor = UIColor(preferences.theme.readerBackground)
    #else
    view.backgroundColor = NSColor(preferences.theme.readerBackground)
    #endif
}

extension ReaderPreferences.Theme {
    /// The page itself stays as the document drew it — a PDF is a fixed
    /// layout — so only the surround changes.
    var readerBackground: Color {
        switch self {
        case .light: Color(white: 0.92)
        case .sepia: Color(red: 0.90, green: 0.86, blue: 0.78)
        case .dark: Color(white: 0.12)
        }
    }
}

@MainActor
private func configuredPDFView(
    url: URL,
    initialPage: Int?,
    preferences: ReaderPreferences
) -> PDFView {
    let view = PDFView()
    view.autoScales = true
    let document = PDFKit.PDFDocument(url: url)
    view.document = document
    apply(preferences, to: view)
    if let initialPage, let document, let page = document.page(at: initialPage) {
        view.go(to: page)
    }
    return view
}

/// Speakable text out of a PDF, one segment per sentence, located by page.
///
/// A scanned PDF yields nothing here — it needs the OCR pass from the pipeline
/// before it can be narrated.
enum PDFTextSource {
    static func segments(of url: URL, fromPage: Int? = nil, limit: Int = 2500) -> [NarrationSegment] {
        guard let document = PDFDocument(url: url) else { return [] }
        var segments: [NarrationSegment] = []
        let pageCount = document.pageCount
        let first = min(max(fromPage ?? 0, 0), max(pageCount - 1, 0))
        for index in first..<pageCount {
            if segments.count >= limit { break }
            guard let text = document.page(at: index)?.string, !text.isEmpty else { continue }
            let progression = pageCount > 1 ? Double(index) / Double(pageCount - 1) : 0
            for sentence in SentenceSegmenter.sentences(in: text) {
                segments.append(NarrationSegment(
                    text: sentence,
                    locator: String(index),
                    progression: progression
                ))
            }
        }
        return segments
    }
}
Loading