Repository Public
1// SP Notes Core2// File: Sources/SPNotesSync/Repositories/ResearchRepository.swift3// Description: Research for the apps: the reference library read offline from the entity copy, written online (create, edit, delete, DOI, BibTeX import) with the answer applied to the local copy; citation resolution; exports and the project overview read online.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import SPNotesAPI9import SPNotesStore1011public struct ResearchRepository: Sendable {12 let context: RepositoryContext13 public init(context: RepositoryContext) { self.context = context }1415 // MARK: reading (local, works offline)1617 /// The references of the local copy (all, or those attached to a page), by cite key.18 public func localReferences(pageId: String? = nil) async throws -> [ResearchReference] {19 do {20 return context.decodeEntities(ResearchReference.self, try await context.store.references(projectId: pageId)).filter { $0.deletedAt == nil }21 .sorted { $0.citeKey.localizedCaseInsensitiveCompare($1.citeKey) == .orderedAscending }22 } catch { throw RepositoryError.from(error) }23 }2425 /// Resolves the `refId`s of `citation` nodes from the local copy (works offline). Missing ids are simply absent:26 /// show « référence introuvable » for them.27 public func resolveLocally(ids: [String]) async throws -> [String: ResearchReference] {28 do {29 var out: [String: ResearchReference] = [:]30 for id in Set(ids) {31 if let record = try await context.store.entity(kind: .reference, id: id), !record.deleted,32 let reference = try? APIJSON.decoder().decode(ResearchReference.self, from: record.json), reference.deletedAt == nil { out[id] = reference }33 }34 return out35 } catch { throw RepositoryError.from(error) }36 }3738 /// Resolves citations on the server (adds `label` and the formatted `citation` when the server provides them),39 /// falling back to the local copy offline.40 public func resolve(ids: [String]) async throws -> [String: ResearchReference] {41 do {42 let lookup = try await context.api.references(ids: ids)43 for reference in lookup.references { await cache(reference) }44 return Dictionary(lookup.references.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })45 } catch {46 guard RepositoryError.from(error) == .offline else { throw RepositoryError.from(error) }47 return try await resolveLocally(ids: ids)48 }49 }5051 // MARK: writing (online only)5253 @discardableResult54 public func create(_ draft: ReferenceDraft) async throws -> ResearchReference {55 var draft = draft56 if draft.id == nil { draft.id = NotesAPI.newID() }57 let sent = draft58 let reference = try await context.online { try await context.api.createReference(sent) }59 await cache(reference)60 return reference61 }6263 @discardableResult64 public func update(id: String, _ changes: ReferenceChanges) async throws -> ResearchReference {65 let reference = try await context.online { try await context.api.updateReference(id: id, changes) }66 await cache(reference)67 return reference68 }6970 public func delete(id: String) async throws {71 _ = try await context.online { try await context.api.deleteReference(id: id) }72 await context.uncacheEntity(kind: .reference, id: id)73 }7475 /// Undoes `delete`.76 @discardableResult77 public func restore(id: String) async throws -> ResearchReference {78 let reference = try await context.online { try await context.api.restoreReference(id: id) }79 await cache(reference)80 return reference81 }8283 /// Looks a DOI up (Crossref, through the server) without saving anything.84 public func lookupDOI(_ doi: String) async throws -> DOILookup { try await context.online { try await context.api.lookupDOI(doi) } }8586 /// Adds the reference of a DOI to the library (the new row arrives with the next cycle, requested here).87 @discardableResult88 public func addByDOI(_ doi: String, pageId: String? = nil) async throws -> DOIAddResult {89 let result = try await context.online { try await context.api.addReferenceByDOI(doi, pageID: pageId) }90 await context.scheduleSync()91 return result92 }9394 /// Imports BibTeX text. `dryRun: true` only reports what would be created or skipped.95 @discardableResult96 public func importBibTeX(_ text: String, pageId: String? = nil, dryRun: Bool = false) async throws -> BibTeXImportResult {97 let result = try await context.online { try await context.api.importBibTeX(text: text, pageID: pageId, dryRun: dryRun) }98 if !dryRun { await context.scheduleSync() }99 return result100 }101102 public func exportBibTeX(pageId: String? = nil, projectId: String? = nil) async throws -> BibTeXExport {103 try await context.online { try await context.api.exportBibTeX(pageID: pageId, projectID: projectId) }104 }105106 /// The LaTeX skeleton of a project (a server without the route → `.unsupported`).107 public func exportLaTeX(projectId: String) async throws -> LaTeXExport { try await context.online { try await context.api.exportLaTeX(projectID: projectId) } }108109 // MARK: experiments and overview (online, cached for offline reading)110111 public func experiments(pageId: String? = nil, policy: CachePolicy = .networkFirst) async throws -> Cached<[ResearchExperiment]> {112 try await context.read("research.experiments." + (pageId ?? "all"), policy: policy) { try await context.api.experiments(pageID: pageId) }113 }114115 @discardableResult116 public func createExperiment(_ draft: ExperimentDraft) async throws -> ResearchExperiment { try await context.online { try await context.api.createExperiment(draft) } }117118 @discardableResult119 public func updateExperiment(id: String, _ changes: ExperimentChanges) async throws -> ResearchExperiment { try await context.online { try await context.api.updateExperiment(id: id, changes) } }120121 public func deleteExperiment(id: String) async throws { _ = try await context.online { try await context.api.deleteExperiment(id: id) } }122123 /// The working papers with their counters.124 public func overview(policy: CachePolicy = .networkFirst) async throws -> Cached<[ResearchPaperOverview]> {125 try await context.read("research.overview", policy: policy) { try await context.api.researchOverview() }126 }127128 private func cache(_ reference: ResearchReference) async {129 guard reference.deletedAt == nil else { await context.uncacheEntity(kind: .reference, id: reference.id); return }130 await context.cacheEntity(kind: .reference, id: reference.id, row: reference, rev: reference.rev)131 }132}133