Files

142 lines
5.8 KiB
Swift

import Combine
import Foundation
import ImageIO
import EzDentStorage
@MainActor
final class PatientLibrary: ObservableObject {
@Published private(set) var patients: [PatientRecord] = []
@Published private(set) var loadError: String?
private let directory: URL
private var index: URL { directory.appendingPathComponent(LibraryPaths.index) }
init(directory: URL = URL.applicationSupportDirectory.appendingPathComponent("EzDent/Library")) {
self.directory = directory
do {
if FileManager.default.fileExists(atPath: index.path) {
patients = try JSONDecoder().decode([PatientRecord].self, from: Data(contentsOf: index))
}
} catch {
loadError = error.localizedDescription
}
}
func savePatient(id: UUID?, name: String, chartNumber: String) throws -> UUID {
let name = name.trimmingCharacters(in: .whitespacesAndNewlines)
let chartNumber = chartNumber.trimmingCharacters(in: .whitespacesAndNewlines)
guard !name.isEmpty, !chartNumber.isEmpty else { throw LibraryError.missingFields }
guard !patients.contains(where: {
$0.id != id && $0.chartNumber.caseInsensitiveCompare(chartNumber) == .orderedSame
}) else { throw LibraryError.duplicateChart }
var updated = patients
let patientID = id ?? UUID()
if let position = updated.firstIndex(where: { $0.id == patientID }) {
updated[position].name = name
updated[position].chartNumber = chartNumber
} else {
updated.append(PatientRecord(id: patientID, name: name, chartNumber: chartNumber))
}
try save(updated)
return patientID
}
func importImage(from source: URL, for patientID: UUID) throws -> PatientImage {
guard let position = patients.firstIndex(where: { $0.id == patientID }) else {
throw LibraryError.patientMissing
}
try prepareDirectory()
let hasAccess = source.startAccessingSecurityScopedResource()
defer { if hasAccess { source.stopAccessingSecurityScopedResource() } }
guard let imageSource = CGImageSourceCreateWithURL(source as CFURL, nil),
CGImageSourceGetCount(imageSource) > 0,
CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) != nil else {
throw LibraryError.unsupportedImage
}
let image = PatientImage(id: UUID(), name: source.lastPathComponent, importedAt: Date())
let destination = url(for: image)
try FileManager.default.copyItem(at: source, to: destination)
do {
var updated = patients
updated[position].images.insert(image, at: 0)
try save(updated)
} catch {
try? FileManager.default.removeItem(at: destination)
throw error
}
return image
}
func importDICOM(from sources: [URL], for patientID: UUID) async throws -> PatientImage {
let accessed = sources.filter { $0.startAccessingSecurityScopedResource() }
defer { accessed.forEach { $0.stopAccessingSecurityScopedResource() } }
try await Task.detached(priority: .userInitiated) {
_ = try DICOMVolume(urls: sources)
}.value
guard let position = patients.firstIndex(where: { $0.id == patientID }) else {
throw LibraryError.patientMissing
}
try prepareDirectory()
let name = sources.count == 1 ? sources[0].lastPathComponent : "Серия DICOM (\(sources.count) срезов)"
let image = PatientImage(id: UUID(), name: name, importedAt: Date(), dicomCount: sources.count)
let folder = url(for: image)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
do {
for (source, destination) in zip(sources, dicomURLs(for: image)) {
try FileManager.default.copyItem(at: source, to: destination)
}
var updated = patients
updated[position].images.insert(image, at: 0)
try save(updated)
} catch {
try? FileManager.default.removeItem(at: folder)
throw error
}
return image
}
func dicomURLs(for image: PatientImage) -> [URL] {
(0..<(image.dicomCount ?? 0)).map {
LibraryPaths.slice($0 + 1, of: image.id, in: directory)
}
}
func url(for image: PatientImage) -> URL {
LibraryPaths.attachment(image.id, in: directory)
}
private func prepareDirectory() throws {
guard loadError == nil else { throw LibraryError.indexUnavailable }
try FileManager.default.createDirectory(
at: directory,
withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700]
)
}
private func save(_ updated: [PatientRecord]) throws {
try prepareDirectory()
let sorted = updated.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
try JSONEncoder().encode(sorted).write(to: index, options: .atomic)
patients = sorted
}
}
private enum LibraryError: LocalizedError {
case missingFields, duplicateChart, patientMissing, unsupportedImage, indexUnavailable
var errorDescription: String? {
switch self {
case .missingFields: return "Введите имя и номер карты."
case .duplicateChart: return "Карточка с таким номером уже существует."
case .patientMissing: return "Карточка пациента недоступна."
case .unsupportedImage: return "Формат снимка не поддерживается."
case .indexUnavailable: return "Индекс библиотеки недоступен."
}
}
}