Repository Public
1// SP Lecture Studio2// File: Apps/LectureStudio/Shared/Export/ExportSheet.swift3// Description: Export and publishing: MP4 with verification, annotated PDF, captions, transcript, chapters, source assets, archive, explicit resumable upload.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import Observation9import LectureCore10import LectureStorage11import LecturePDF12import LectureRender13import LectureSync14#if os(iOS)15import UIKit16#endif1718struct ExportedFile: Identifiable, Hashable {19 var url: URL20 var kind: String21 var detail: String22 var id: URL { url }23}2425final class ExportCancelFlag: @unchecked Sendable { var cancelled = false }2627@MainActor @Observable28final class ExportCoordinator {29 let session: ProjectSession30 let settings: AppSettings31 let exportsRoot: URL32 var options: ExportOptions { didSet { if options != oldValue { settings.stored.export = options } } }3334 private(set) var running = false35 private(set) var stepTitle = ""36 private(set) var progress = 0.037 private(set) var files: [ExportedFile] = []38 private(set) var error: String?39 private(set) var folder: URL?40 private(set) var interruptedPreviously = false41 private(set) var uploads: [URL: Double] = [:]42 private(set) var uploadMessages: [URL: String] = [:]43 let hasTranscript: Bool44 let hasRecording: Bool45 let outputDuration: MediaTime4647 @ObservationIgnored private var flag = ExportCancelFlag()48 @ObservationIgnored private var task: Task<Void, Never>?49 private var interruptedKey: String { "export.interrupted.\(session.id.uuidString)" }5051 init(session: ProjectSession, settings: AppSettings, exportsRoot: URL) {52 self.session = session; self.settings = settings; self.exportsRoot = exportsRoot53 options = settings.stored.export54 hasTranscript = session.package.loadTranscript()?.segments.isEmpty == false55 hasRecording = session.manifest.hasRecording56 outputDuration = session.package.loadEdits().current.timeMap(duration: session.manifest.duration).outputDuration57 interruptedPreviously = UserDefaults.standard.bool(forKey: interruptedKey)58 if !VideoExporter.isAvailable(.hevc), options.codec == .hevc { options.codec = .h264 }59 }6061 var estimatedVideoBytes: Int64 { options.renderSettings.estimatedBytes(duration: outputDuration) }62 var freeBytes: Int64 { ProjectPackage.freeDiskSpace(at: exportsRoot.deletingLastPathComponent()) }63 var nothingSelected: Bool {64 !(options.video && hasRecording) && !options.annotatedPDF && !(options.captionsSRT && hasTranscript) && !(options.captionsVTT && hasTranscript)65 && !(options.transcriptTXT && hasTranscript) && !(options.chaptersJSON && hasRecording) && !options.sourceAssets && !options.archive66 }6768 func cancel() { flag.cancelled = true }6970 func start() {71 guard !running else { return }72 running = true; error = nil; files = []; progress = 0; flag = ExportCancelFlag()73 UserDefaults.standard.set(true, forKey: interruptedKey)74 let flag = self.flag75 #if os(iOS)76 // Extra background time when the user leaves the app; when it runs out the export is cancelled cleanly and can be restarted.77 var bg: UIBackgroundTaskIdentifier = .invalid78 bg = UIApplication.shared.beginBackgroundTask(withName: "export") { flag.cancelled = true; UIApplication.shared.endBackgroundTask(bg); bg = .invalid }79 UIApplication.shared.isIdleTimerDisabled = true80 #endif81 task = Task { [weak self] in82 guard let self else { return }83 do {84 try await self.run(flag)85 UserDefaults.standard.set(false, forKey: self.interruptedKey)86 } catch ExportError.cancelled {87 self.error = String(localized: "Exportation annulée. Aucun fichier incomplet n'a été laissé.")88 UserDefaults.standard.set(false, forKey: self.interruptedKey)89 } catch let e as ExportError {90 if case .diskFull(let needed, let available) = e {91 self.error = String(localized: "Espace disque insuffisant : il faut environ \(DS.bytes(needed)), il reste \(DS.bytes(available)). Libérez de l'espace puis relancez l'exportation.")92 } else { self.error = e.description }93 UserDefaults.standard.set(false, forKey: self.interruptedKey)94 } catch {95 self.error = (error as NSError).domain == NSCocoaErrorDomain && (error as NSError).code == NSFileWriteOutOfSpaceError96 ? String(localized: "Espace disque insuffisant. Libérez de l'espace puis relancez l'exportation.") : String(describing: error)97 UserDefaults.standard.set(false, forKey: self.interruptedKey)98 }99 self.running = false100 #if os(iOS)101 UIApplication.shared.isIdleTimerDisabled = false102 if bg != .invalid { UIApplication.shared.endBackgroundTask(bg); bg = .invalid }103 #endif104 }105 }106107 private func step(_ title: String) { stepTitle = title; progress = 0 }108109 private func run(_ flag: ExportCancelFlag) async throws {110 let fm = FileManager.default111 let pkg = session.package112 let manifest = try pkg.loadManifest()113 let source = try RenderSource.load(pkg)114 let map = source.timeMap115 let stamp = Date().formatted(.iso8601.year().month().day().dateSeparator(.dash)) + " " + Date().formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute(.twoDigits)).replacingOccurrences(of: ":", with: "h")116 let base = ProjectPackage.safeFileName(manifest.title)117 let dir = ProjectPackage.uniqueURL(in: exportsRoot, baseName: "\(base) \(stamp)", ext: "")118 let folderURL = dir.pathExtension.isEmpty ? dir : dir.deletingPathExtension()119 try fm.createDirectory(at: folderURL, withIntermediateDirectories: true)120 folder = folderURL121 var records: [ExportRecord] = []122 func size(_ u: URL) -> Int64 { (try? fm.attributesOfItem(atPath: u.path)[.size] as? NSNumber)?.int64Value ?? 0 }123 func add(_ url: URL, kind: String, detail: String) {124 files.append(ExportedFile(url: url, kind: kind, detail: detail))125 records.append(ExportRecord(kind: kind, fileName: url.lastPathComponent, detail: detail, byteCount: size(url)))126 }127128 if options.video && manifest.hasRecording {129 step(String(localized: "Vidéo"))130 let url = folderURL.appendingPathComponent("\(base).mp4")131 let exporter = VideoExporter(source: source, settings: options.renderSettings)132 let result = try await exporter.export(to: url, progress: { p in Task { @MainActor [weak self] in self?.progress = p * 0.97 } }, isCancelled: { flag.cancelled })133 step(String(localized: "Vérification de la vidéo"))134 // The file is reopened and decoded like a player would before it is reported as exported.135 let report = await MediaVerifier.verify(url, expectedDuration: result.duration, decodeAll: false)136 let firstFrame = await MediaVerifier.frame(of: url, at: .zero)137 guard report.isValid, firstFrame != nil else {138 try? fm.removeItem(at: url)139 throw ExportError.writerFailed(String(localized: "le fichier produit n'a pas passé la vérification de lecture (\(report.problems.joined(separator: ", ")))"))140 }141 var detail = "\(options.preset.label) · \(options.codec == .hevc ? "HEVC" : "H.264") · \(options.fps) i/s · \(DS.duration(result.duration))"142 if !result.unreadableSegments.isEmpty { detail += " · " + String(localized: "\(result.unreadableSegments.count) segment(s) audio manquant(s) rendu(s) muet(s)") }143 add(url, kind: "video", detail: detail)144 }145 if flag.cancelled { throw ExportError.cancelled }146147 if options.annotatedPDF {148 step(String(localized: "PDF annoté"))149 let url = folderURL.appendingPathComponent("\(base) — annoté.pdf")150 let index = source.index151 try AnnotatedPDFExporter.export(document: source.document, strokes: { index.finalStrokes(page: $0) }, to: url, mode: options.pdfMode, title: manifest.title)152 add(url, kind: "pdf", detail: options.pdfMode == .flattened ? String(localized: "Annotations aplaties") : String(localized: "Annotations modifiables"))153 progress = 1154 }155156 if let transcript = pkg.loadTranscript(), !transcript.segments.isEmpty {157 let captions = CaptionWriter.captions(transcript, map: map)158 if options.captionsSRT {159 let url = folderURL.appendingPathComponent("\(base).srt"); try CaptionWriter.srt(captions).write(to: url, atomically: true, encoding: .utf8)160 add(url, kind: "captions", detail: "SRT · \(captions.count)")161 }162 if options.captionsVTT {163 let url = folderURL.appendingPathComponent("\(base).vtt"); try CaptionWriter.vtt(captions).write(to: url, atomically: true, encoding: .utf8)164 add(url, kind: "captions", detail: "WebVTT · \(captions.count)")165 }166 if options.transcriptTXT {167 let url = folderURL.appendingPathComponent("\(base) — transcription.txt")168 try CaptionWriter.plainText(transcript, map: map, chapters: source.edits.chapters).write(to: url, atomically: true, encoding: .utf8)169 add(url, kind: "transcript", detail: "TXT")170 }171 }172173 if options.chaptersJSON && manifest.hasRecording {174 var chapters = source.edits.chapters175 if chapters.isEmpty {176 let doc = source.document177 chapters = ChapterGenerator.fromSlides(index: source.index, duration: source.duration) { doc.titleGuess(page: $0) ?? String(localized: "Page \($0 + 1)") }178 }179 let url = folderURL.appendingPathComponent("\(base) — chapitres.json")180 try CaptionWriter.chaptersJSON(title: manifest.title, chapters: chapters, map: map).write(to: url, options: .atomic)181 add(url, kind: "chapters", detail: "JSON · \(chapters.count)")182 let txt = folderURL.appendingPathComponent("\(base) — chapitres.txt")183 try CaptionWriter.chapterList(chapters, map: map).write(to: txt, atomically: true, encoding: .utf8)184 add(txt, kind: "chapters", detail: "TXT")185 }186187 if options.sourceAssets {188 step(String(localized: "Fichiers sources"))189 let dest = folderURL.appendingPathComponent("Sources", isDirectory: true)190 try fm.createDirectory(at: dest, withIntermediateDirectories: true)191 // Copies only: the project keeps its originals.192 try fm.copyItem(at: pkg.pdfURL, to: dest.appendingPathComponent(manifest.pdf?.originalName ?? "source.pdf"))193 let media = manifest.sessions.flatMap(\.segments)194 for (i, seg) in media.enumerated() where fm.fileExists(atPath: pkg.url(seg.path).path) {195 if flag.cancelled { throw ExportError.cancelled }196 try fm.copyItem(at: pkg.url(seg.path), to: dest.appendingPathComponent((seg.path as NSString).lastPathComponent))197 progress = Double(i + 1) / Double(max(1, media.count))198 }199 try fm.copyItem(at: pkg.eventsURL, to: dest.appendingPathComponent(ProjectLayout.events))200 try fm.copyItem(at: pkg.manifestURL, to: dest.appendingPathComponent(ProjectLayout.manifest))201 add(dest, kind: "sources", detail: String(localized: "PDF, \(media.count) segment(s), journal"))202 }203204 if options.archive {205 step(String(localized: "Archive du projet"))206 let url = folderURL.appendingPathComponent("\(base).slecture.zip")207 let cancelFlag = flag208 try await Task.detached {209 try Library.exportArchive(pkg, to: url) { p in Task { @MainActor [weak self] in self?.progress = p }; return !cancelFlag.cancelled }210 }.value211 add(url, kind: "archive", detail: String(localized: "Projet complet, réimportable"))212 }213214 step("")215 session.updateManifest { $0.exports.append(contentsOf: records); if $0.exports.count > 200 { $0.exports.removeFirst($0.exports.count - 200) } }216 }217218 // MARK: Explicit upload219220 var canUpload: Bool { settings.stored.uploadEndpoint.isConfigured }221222 func upload(_ file: ExportedFile) {223 guard uploads[file.url] == nil else { return }224 uploadMessages[file.url] = nil225 uploads[file.url] = 0226 let endpoint = settings.stored.uploadEndpoint227 let requireBio = settings.stored.requireBiometricsForCredentials228 let stateKey = "upload.state.\(file.url.path)"229 Task { [weak self] in230 if requireBio, !(await BiometricGate.unlock(reason: String(localized: "Déverrouiller le jeton de téléversement"))) {231 self?.uploads[file.url] = nil; self?.uploadMessages[file.url] = String(localized: "Authentification refusée."); return232 }233 do {234 var state = try UploadState(file: file.url)235 // Resume a previous attempt for the same, unchanged file.236 if let data = UserDefaults.standard.data(forKey: stateKey), let saved = try? JSONDecoder().decode(UploadState.self, from: data),237 saved.fileSize == state.fileSize, abs(saved.fileModified.timeIntervalSince(state.fileModified)) < 1, !saved.completed { state = saved }238 let uploader = ResumableUploader(endpoint: endpoint, token: KeychainStore.get(account: AppSettings.uploadTokenAccount))239 let total = Double(max(1, state.fileSize))240 _ = try await uploader.upload(state, metadata: ["title": self?.session.title ?? ""], onState: { s in241 if let data = try? JSONEncoder().encode(s) { UserDefaults.standard.set(data, forKey: stateKey) }242 Task { @MainActor [weak self] in self?.uploads[file.url] = Double(s.offset) / total }243 })244 UserDefaults.standard.removeObject(forKey: stateKey)245 self?.uploads[file.url] = nil246 self?.uploadMessages[file.url] = String(localized: "Téléversé.")247 } catch {248 self?.uploads[file.url] = nil249 self?.uploadMessages[file.url] = String(localized: "Échec : \((error as? UploadError)?.description ?? error.localizedDescription). Relancez pour reprendre où le transfert s'est arrêté.")250 }251 }252 }253}254255struct ExportSheet: View {256 let model: AppModel257 let session: ProjectSession258 @Environment(\.dismiss) private var dismiss259 @State private var coordinator: ExportCoordinator?260261 var body: some View {262 NavigationStack {263 Group { if let c = coordinator { content(c) } else { ProgressView() } }264 .navigationTitle("Exporter").inlineTitle()265 .toolbar {266 ToolbarItem(placement: .cancellationAction) {267 Button(coordinator?.running == true ? "Annuler l'exportation" : "Fermer") {268 if coordinator?.running == true { coordinator?.cancel() } else { dismiss() }269 }.accessibilityIdentifier("export.close")270 }271 }272 }273 .interactiveDismissDisabled(coordinator?.running ?? false)274 .onAppear { if coordinator == nil { coordinator = ExportCoordinator(session: session, settings: model.settings, exportsRoot: model.exportsRoot) } }275 #if os(macOS)276 .frame(minWidth: 560, minHeight: 640)277 #endif278 }279280 @ViewBuilder private func content(_ c: ExportCoordinator) -> some View {281 Form {282 if c.interruptedPreviously && !c.running && c.files.isEmpty {283 Section { Label("La dernière exportation de cette séance n'a pas pu se terminer (app fermée ou suspendue). Rien d'incomplet n'a été conservé : relancez-la.", systemImage: "arrow.clockwise.circle").foregroundStyle(DS.paused) }284 }285 if !c.files.isEmpty {286 Section {287 ForEach(c.files) { f in288 VStack(alignment: .leading, spacing: 4) {289 HStack(spacing: 8) {290 Image(systemName: Self.icon(f.kind)).foregroundStyle(DS.accent).frame(width: 22)291 VStack(alignment: .leading, spacing: 1) {292 Text(verbatim: f.url.lastPathComponent).font(.subheadline).lineLimit(1)293 Text(verbatim: f.detail).font(.caption).foregroundStyle(.secondary)294 }295 Spacer()296 ShareLink(item: f.url) { Image(systemName: "square.and.arrow.up") }.buttonStyle(.borderless).accessibilityLabel("Partager")297 if c.canUpload, f.kind != "sources" {298 Button { c.upload(f) } label: { Image(systemName: "icloud.and.arrow.up") }.buttonStyle(.borderless).disabled(c.uploads[f.url] != nil)299 .help("Téléverser vers l'adresse configurée").accessibilityLabel("Téléverser")300 }301 }302 if let p = c.uploads[f.url] { ProgressView(value: p) }303 if let m = c.uploadMessages[f.url] { Text(verbatim: m).font(.caption).foregroundStyle(.secondary) }304 }305 .accessibilityIdentifier("export.file.\(f.kind)")306 }307 #if os(macOS)308 if let folder = c.folder { Button("Afficher dans le Finder") { NSWorkspace.shared.activateFileViewerSelecting([folder]) } }309 #else310 Text("Les fichiers sont dans l'app Fichiers : Sur mon appareil › Lecture Studio › Exports.").font(.caption).foregroundStyle(.secondary)311 #endif312 } header: { Text("Fichiers exportés") } footer: { Text("Rien n'est publié automatiquement. Partagez ou téléversez chaque fichier vous-même.") }313 }314 Section {315 Toggle("Vidéo MP4", isOn: bind(c, \.video)).disabled(!c.hasRecording).accessibilityIdentifier("export.video")316 if c.options.video && c.hasRecording {317 Picker("Résolution", selection: bind(c, \.preset)) { ForEach(ExportPreset.allCases) { Text(verbatim: $0.label).tag($0) } }318 Picker("Codec", selection: bind(c, \.codec)) {319 Text(verbatim: "H.264").tag(VideoCodec.h264)320 if VideoExporter.isAvailable(.hevc) { Text(verbatim: "HEVC").tag(VideoCodec.hevc) }321 }322 Picker("Images par seconde", selection: bind(c, \.fps)) { ForEach([24, 30, 60], id: \.self) { Text(verbatim: "\($0)").tag($0) } }323 Picker("Débit", selection: bind(c, \.bitrateMbps)) {324 Text("Automatique").tag(0.0)325 ForEach([2.0, 4, 8, 12, 20, 35], id: \.self) { Text(verbatim: "\(Int($0)) Mbit/s").tag($0) }326 }327 Toggle("Rejouer le zoom", isOn: bind(c, \.replayZoom))328 Toggle("Afficher le pointeur laser", isOn: bind(c, \.showPointer))329 if !session.manifest.segments(.camera).isEmpty { Toggle("Inclure la caméra", isOn: bind(c, \.includeCamera)) }330 LabeledContent("Durée") { Text(verbatim: DS.duration(c.outputDuration)) }331 LabeledContent("Taille estimée") { Text(verbatim: "≈ \(DS.bytes(c.estimatedVideoBytes)) · \(DS.bytes(c.freeBytes)) libres").foregroundStyle(c.freeBytes < c.estimatedVideoBytes * 2 ? DS.recording : .secondary) }332 }333 } header: { Text("Vidéo") } footer: {334 if !c.hasRecording { Text("Aucun enregistrement : la vidéo n'est pas disponible. Le PDF annoté peut être exporté.") }335 else { Text("La vidéo est recalculée à partir du PDF, de l'encre vectorielle et de l'audio — jamais d'une capture d'écran. Elle est relue et vérifiée avant d'être déclarée terminée.") }336 }337338 Section {339 Toggle("PDF annoté", isOn: bind(c, \.annotatedPDF)).accessibilityIdentifier("export.pdf")340 if c.options.annotatedPDF {341 Picker("Annotations", selection: bind(c, \.pdfMode)) {342 Text("Aplaties (aspect exact)").tag(AnnotatedPDFMode.flattened)343 Text("Modifiables (annotations PDF)").tag(AnnotatedPDFMode.annotations)344 }345 }346 Toggle("Sous-titres SRT", isOn: bind(c, \.captionsSRT)).disabled(!c.hasTranscript)347 Toggle("Sous-titres WebVTT", isOn: bind(c, \.captionsVTT)).disabled(!c.hasTranscript)348 Toggle("Transcription TXT", isOn: bind(c, \.transcriptTXT)).disabled(!c.hasTranscript)349 Toggle("Chapitres (JSON et liste)", isOn: bind(c, \.chaptersJSON)).disabled(!c.hasRecording)350 Toggle("Fichiers sources (copie)", isOn: bind(c, \.sourceAssets))351 Toggle("Archive du projet (.slecture.zip)", isOn: bind(c, \.archive))352 } header: { Text("Documents") } footer: {353 if !c.hasTranscript { Text("Les sous-titres et la transcription demandent d'abord de transcrire la séance (onglet « Texte » du montage).") }354 else { Text("Le PDF d'origine n'est jamais modifié : le PDF annoté est un nouveau fichier.") }355 }356357 }358 .formStyle(.grouped)359 .safeAreaInset(edge: .bottom, spacing: 0) { actionBar(c) }360 }361362 /// Always-visible action area: the export button, or progress while running, plus any error.363 private func actionBar(_ c: ExportCoordinator) -> some View {364 VStack(alignment: .leading, spacing: 6) {365 if let e = c.error {366 Label { Text(verbatim: e).font(.caption) } icon: { Image(systemName: "exclamationmark.triangle.fill") }.foregroundStyle(DS.recording).accessibilityIdentifier("export.error")367 }368 if c.running {369 HStack {370 Text(verbatim: c.stepTitle.isEmpty ? String(localized: "Préparation…") : c.stepTitle).font(.subheadline.weight(.semibold))371 Spacer()372 Text(verbatim: "\(Int(c.progress * 100)) %").font(.caption.monospacedDigit()).foregroundStyle(.secondary)373 }374 ProgressView(value: c.progress).accessibilityIdentifier("export.progress")375 } else {376 Button { c.start() } label: {377 Label(c.files.isEmpty ? "Exporter" : "Exporter de nouveau", systemImage: "square.and.arrow.up.on.square").frame(maxWidth: .infinity)378 }379 .buttonStyle(.borderedProminent).controlSize(.large).disabled(c.nothingSelected).accessibilityIdentifier("export.start")380 }381 }382 .padding(.horizontal, 16).padding(.vertical, 10)383 .frame(maxWidth: .infinity, minHeight: 64)384 .background(.bar)385 }386387 private func bind<T>(_ c: ExportCoordinator, _ kp: WritableKeyPath<ExportOptions, T>) -> Binding<T> {388 Binding(get: { c.options[keyPath: kp] }, set: { c.options[keyPath: kp] = $0 })389 }390391 static func icon(_ kind: String) -> String {392 switch kind { case "video": "film"; case "pdf": "doc.richtext"; case "captions": "captions.bubble"; case "transcript": "text.alignleft"393 case "chapters": "list.bullet.indent"; case "sources": "folder"; case "archive": "archivebox"; default: "doc" }394 }395}396