Publish VCC Plus OSS source distribution for 3.6.2 build 60
This commit is contained in:
commit
c652a5276d
1192 files changed
+272368
No files matched your search
@@ -0,0 +1,143 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import Combine
|
||||
|
||||
// Catalog releases are immutable reference data. This independent, atomic file
|
||||
// retains personal choices across catalog replacements, including IDs absent
|
||||
// from a later catalog. Installation receipts are reconciled into it without editing SQLite.
|
||||
@MainActor
|
||||
final class SoftwareLibraryState: ObservableObject {
|
||||
struct Installation: Codable, Equatable, Sendable {
|
||||
let releaseID: String
|
||||
let packageSHA256: String
|
||||
let installedAt: Date
|
||||
let workingDirectory: URL
|
||||
}
|
||||
private struct Document: Codable, Sendable {
|
||||
var version = 1
|
||||
var favoriteTitleIDs: Set<String> = []
|
||||
var preferredReleaseIDs: [String: String] = [:]
|
||||
var installedReleases: [String: Installation] = [:]
|
||||
}
|
||||
@Published private(set) var favoriteTitleIDs: Set<String> = []
|
||||
@Published private(set) var preferredReleaseIDs: [String: String] = [:]
|
||||
@Published private(set) var installedReleases: [String: Installation] = [:]
|
||||
@Published private(set) var saveError: String?
|
||||
let directory: URL
|
||||
private let fileURL: URL
|
||||
private let queue = DispatchQueue(label: "com.brianholman.vccplus.library-state", qos: .utility)
|
||||
private var companion: (any CompanionLibraryAccess)?
|
||||
private var remoteSave: Task<Void, Never>?
|
||||
private var maySave = true
|
||||
private var revision = 0
|
||||
|
||||
init(directory: URL) {
|
||||
self.directory = directory
|
||||
fileURL = directory.appendingPathComponent("LibraryState.json")
|
||||
do {
|
||||
guard FileManager.default.fileExists(atPath: fileURL.path) else { return }
|
||||
let file = try FileHandle(forReadingFrom: fileURL)
|
||||
defer { try? file.close() }
|
||||
let data = try file.read(upToCount: 1_048_577) ?? Data()
|
||||
guard data.count <= 1_048_576 else { throw StateFailure.invalid }
|
||||
let document = try JSONDecoder().decode(Document.self, from: data)
|
||||
guard document.version == 1,
|
||||
document.favoriteTitleIDs.allSatisfy(Self.validID),
|
||||
document.preferredReleaseIDs.allSatisfy({ Self.validID($0.key) && Self.validID($0.value) }),
|
||||
document.installedReleases.allSatisfy({ key, entry in
|
||||
key == entry.releaseID && Self.validID(key) && entry.packageSHA256.count == 64
|
||||
&& entry.packageSHA256.allSatisfy(\.isHexDigit) && entry.workingDirectory.isFileURL
|
||||
}) else { throw StateFailure.invalid }
|
||||
favoriteTitleIDs = document.favoriteTitleIDs
|
||||
preferredReleaseIDs = document.preferredReleaseIDs
|
||||
installedReleases = document.installedReleases
|
||||
} catch {
|
||||
maySave = false // Preserve unreadable/newer state rather than overwriting it.
|
||||
saveError = "Your saved Library choices could not be read. The original file has been preserved at \(fileURL.path). \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
/// In-memory presentation only. All persistence stays in VCC Plus.
|
||||
init(companion: any CompanionLibraryAccess) {
|
||||
self.companion = companion
|
||||
directory = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCompanionPresentation", isDirectory: true)
|
||||
fileURL = directory.appendingPathComponent("Unused.json")
|
||||
}
|
||||
func applyRemoteSnapshot(_ snapshot: CompanionLibrarySnapshot) {
|
||||
favoriteTitleIDs = snapshot.favorites
|
||||
preferredReleaseIDs = snapshot.preferredReleaseIDs
|
||||
installedReleases = Dictionary(snapshot.installations.map { ($0.releaseID, $0) }, uniquingKeysWith: { _, last in last })
|
||||
saveError = nil
|
||||
}
|
||||
private func sendRemote(_ request: CompanionLibraryRequest) {
|
||||
guard let companion else { return }
|
||||
revision += 1
|
||||
let revision = revision, previous = remoteSave
|
||||
remoteSave = Task { [weak self] in
|
||||
await previous?.value
|
||||
do {
|
||||
let response = try await companion.libraryRequest(request)
|
||||
if let message = response.errorMessage { throw CompanionLibraryFailure(message: message) }
|
||||
guard let self, self.revision == revision else { return }
|
||||
if let snapshot = response.snapshot { self.applyRemoteSnapshot(snapshot) }
|
||||
} catch {
|
||||
guard let self, self.revision == revision else { return }
|
||||
self.saveError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
func isFavorite(_ titleID: String) -> Bool { favoriteTitleIDs.contains(titleID) }
|
||||
func preferredReleaseID(for titleID: String) -> String? { preferredReleaseIDs[titleID] }
|
||||
func toggleFavorite(_ titleID: String) {
|
||||
guard maySave, Self.validID(titleID) else { return }
|
||||
if favoriteTitleIDs.contains(titleID) { favoriteTitleIDs.remove(titleID) }
|
||||
else { favoriteTitleIDs.insert(titleID) }
|
||||
if companion != nil {
|
||||
sendRemote(.init(operation: .setFavorite, titleID: titleID, enabled: favoriteTitleIDs.contains(titleID)))
|
||||
} else { save() }
|
||||
}
|
||||
func selectRelease(_ releaseID: String, for titleID: String) {
|
||||
guard maySave, Self.validID(titleID), Self.validID(releaseID), preferredReleaseIDs[titleID] != releaseID else { return }
|
||||
preferredReleaseIDs[titleID] = releaseID
|
||||
if companion != nil { sendRemote(.init(operation: .setPreferredRelease, releaseID: releaseID, titleID: titleID)) }
|
||||
else { save() }
|
||||
}
|
||||
// Receipts are the authoritative installation record; personal choices stay separate.
|
||||
func replaceInstallations(_ installations: [Installation]) {
|
||||
let entries = Dictionary(installations.map { ($0.releaseID, $0) }, uniquingKeysWith: { _, latest in latest })
|
||||
guard entries != installedReleases else { return }
|
||||
installedReleases = entries
|
||||
if maySave && companion == nil { save() }
|
||||
}
|
||||
// Used at shutdown/testing to await all already-enqueued atomic writes.
|
||||
func flush() async {
|
||||
await remoteSave?.value
|
||||
await withCheckedContinuation { continuation in queue.async { continuation.resume() } }
|
||||
}
|
||||
private static func validID(_ id: String) -> Bool {
|
||||
!id.isEmpty && id.utf8.count <= 256 && !id.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains)
|
||||
}
|
||||
private func save() {
|
||||
let document = Document(favoriteTitleIDs: favoriteTitleIDs, preferredReleaseIDs: preferredReleaseIDs, installedReleases: installedReleases)
|
||||
revision += 1
|
||||
let revision = revision, destination = fileURL
|
||||
queue.async { [weak self] in
|
||||
let failure: String?
|
||||
do {
|
||||
let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]
|
||||
let data = try encoder.encode(document)
|
||||
guard data.count <= 1_048_576 else { throw StateFailure.invalid }
|
||||
try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try data.write(to: destination, options: .atomic)
|
||||
failure = nil
|
||||
} catch { failure = "Library choices could not be saved: \(error.localizedDescription)" }
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.revision == revision else { return }
|
||||
self.saveError = failure
|
||||
}
|
||||
}
|
||||
}
|
||||
private enum StateFailure: LocalizedError {
|
||||
case invalid
|
||||
var errorDescription: String? { "The Library choices file is damaged or uses an unsupported version." }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user