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,160 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import Darwin
|
||||
|
||||
#if !VCC_COMPANION_CLIENT
|
||||
/// VCC Plus alone owns catalog loading, install receipts, downloads and caches.
|
||||
/// The transport authenticates its caller before reaching this disk-only API.
|
||||
@MainActor
|
||||
final class CompanionLibraryAuthority {
|
||||
private let model: SoftwareLibraryModel
|
||||
init(model: SoftwareLibraryModel) { self.model = model }
|
||||
|
||||
func handle(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse {
|
||||
await model.load()
|
||||
// Another native window may already be loading this same model.
|
||||
for _ in 0..<200 where model.loading {
|
||||
try Task.checkCancellation()
|
||||
try await Task.sleep(nanoseconds: 50_000_000)
|
||||
}
|
||||
guard let catalog = model.catalog else { throw failure(model.error ?? "VCC Plus's Software Library is unavailable.") }
|
||||
let disks = catalog.companionDisks(includingOwnedTitles: request.ownedTitlesVersion == 1)
|
||||
func release() throws -> SoftwareLibraryRelease {
|
||||
guard let id = request.releaseID, let value = disks.releases.first(where: { $0.id == id }) else {
|
||||
throw failure("Choose a disk edition from VCC Plus's catalog.")
|
||||
}
|
||||
return value
|
||||
}
|
||||
switch request.operation {
|
||||
case .snapshot:
|
||||
return .init(snapshot: snapshot(disks))
|
||||
case .setFavorite:
|
||||
guard let id = request.titleID, let enabled = request.enabled,
|
||||
disks.titles.contains(where: { $0.id == id }) else { throw failure("This disk title is unavailable.") }
|
||||
if model.state.isFavorite(id) != enabled { model.state.toggleFavorite(id) }
|
||||
await model.state.flush()
|
||||
if let message = model.state.saveError { throw failure(message) }
|
||||
return .init(snapshot: snapshot(disks))
|
||||
case .setPreferredRelease:
|
||||
let selected = try release()
|
||||
guard request.titleID == selected.titleID else { throw failure("This disk edition does not belong to the selected title.") }
|
||||
model.state.selectRelease(selected.id, for: selected.titleID)
|
||||
await model.state.flush()
|
||||
if let message = model.state.saveError { throw failure(message) }
|
||||
return .init(snapshot: snapshot(disks))
|
||||
case .install:
|
||||
let selected = try release()
|
||||
guard model.installingReleaseID == nil || model.installingReleaseID == selected.id else {
|
||||
throw failure("VCC Plus is already installing another title. Let it finish or cancel it there.")
|
||||
}
|
||||
guard !model.launchBusy, !model.hasPendingLaunch else { throw failure("Finish the current VCC Plus library action first.") }
|
||||
if model.installingReleaseID == nil && model.state.installedReleases[selected.id] == nil { model.install(selected) }
|
||||
return try await installStatus(selected, catalog: disks)
|
||||
case .installStatus:
|
||||
return try await installStatus(release(), catalog: disks)
|
||||
case .cancelInstallation:
|
||||
let selected = try release()
|
||||
if model.installingReleaseID == selected.id { model.cancelInstallation() }
|
||||
return .init(snapshot: snapshot(disks), isInstalling: model.installingReleaseID == selected.id)
|
||||
case .removeInstallation:
|
||||
let selected = try release()
|
||||
await model.removeInstallation(selected.id)
|
||||
if let message = model.installationErrors[selected.id] { throw failure(message) }
|
||||
return .init(snapshot: snapshot(disks))
|
||||
case .diskMembers, .exportDisk:
|
||||
let selected = try release()
|
||||
let receipt = try await installedReceipt(selected)
|
||||
let candidates = receipt.relativeFiles.filter(Self.diskMember).map { CompanionLibraryDisk(path: $0, mediaType: "disk") }
|
||||
.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }
|
||||
guard !candidates.isEmpty else { throw failure("This installation contains no supported floppy disk images.") }
|
||||
if request.operation == .diskMembers { return .init(snapshot: snapshot(disks), receipt: receipt, disks: candidates) }
|
||||
guard let member = request.memberPath, candidates.contains(where: { $0.path == member }) else {
|
||||
throw failure("Choose a disk file from this installation.")
|
||||
}
|
||||
let destination = model.state.directory.appendingPathComponent("CompanionDisks", isDirectory: true)
|
||||
let exported = try await Task.detached(priority: .userInitiated) {
|
||||
try Self.exportDisk(receipt: receipt, member: member, destination: destination)
|
||||
}.value
|
||||
return .init(exportedDiskURL: exported)
|
||||
case .thumbnail, .manual:
|
||||
guard let id = request.assetID,
|
||||
let asset = disks.releases.lazy.flatMap({ release in
|
||||
release.assets + (release.ownedGame == nil ? [] : [release.primaryManualAsset].compactMap { $0 })
|
||||
}).first(where: { $0.id == id }) else {
|
||||
throw failure("This supporting asset is unavailable for the disk library.")
|
||||
}
|
||||
if request.operation == .thumbnail {
|
||||
let data = try await SoftwareLibraryArtworkCache.shared.thumbnail(for: asset, directory: model.artworkDirectory)
|
||||
return .init(assetData: data)
|
||||
}
|
||||
guard asset.isManual else { throw failure("Choose a manual or instructions asset.") }
|
||||
let local = try await SoftwareLibraryManualCache.shared.localCopy(for: asset,
|
||||
directory: model.state.directory.appendingPathComponent("Manuals", isDirectory: true))
|
||||
return .init(assetFileURL: local)
|
||||
}
|
||||
}
|
||||
|
||||
private func failure(_ message: String) -> CompanionLibraryFailure { .init(message: message) }
|
||||
private func snapshot(_ catalog: SoftwareLibraryCatalog) -> CompanionLibrarySnapshot {
|
||||
let titleIDs = Set(catalog.titles.map(\.id)), releaseIDs = Set(catalog.releases.map(\.id))
|
||||
return .init(catalog: catalog,
|
||||
favorites: model.state.favoriteTitleIDs.intersection(titleIDs),
|
||||
preferredReleaseIDs: model.state.preferredReleaseIDs.filter { titleIDs.contains($0.key) && releaseIDs.contains($0.value) },
|
||||
installations: model.state.installedReleases.values.filter { releaseIDs.contains($0.releaseID) })
|
||||
}
|
||||
private func installedReceipt(_ release: SoftwareLibraryRelease) async throws -> SoftwareLibraryInstallationReceipt {
|
||||
let receipts = try await model.installer.recoverInstallations()
|
||||
guard let receipt = receipts.first(where: { $0.releaseID == release.id && $0.packageSHA256 == release.packageSHA256 }) else {
|
||||
throw failure("Install this disk edition in VCC Plus first.")
|
||||
}
|
||||
return receipt
|
||||
}
|
||||
private func installStatus(_ release: SoftwareLibraryRelease, catalog: SoftwareLibraryCatalog) async throws -> CompanionLibraryResponse {
|
||||
if let message = model.installationErrors[release.id] { throw failure(message) }
|
||||
let active = model.installingReleaseID == release.id
|
||||
return .init(snapshot: snapshot(catalog), progress: active ? model.installProgress : nil,
|
||||
isInstalling: active)
|
||||
}
|
||||
nonisolated static func diskMember(_ path: String) -> Bool {
|
||||
!path.isEmpty && !path.hasPrefix("/") && !path.contains("\\") && !path.contains(":")
|
||||
&& !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains)
|
||||
&& path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." }
|
||||
&& ["dsk", "os9"].contains((path as NSString).pathExtension.lowercased())
|
||||
}
|
||||
/// Every handoff gets a new writable copy. Verified originals and the
|
||||
/// emulator's working image are never handed to the real CoCo for writing.
|
||||
nonisolated private static func exportDisk(receipt: SoftwareLibraryInstallationReceipt, member: String, destination: URL) throws -> URL {
|
||||
guard diskMember(member), receipt.relativeFiles.contains(member) else { throw CompanionLibraryFailure(message: "Invalid disk member.") }
|
||||
let root = receipt.workingDirectory.standardizedFileURL
|
||||
var source = root
|
||||
for component in member.split(separator: "/") {
|
||||
source.appendPathComponent(String(component))
|
||||
let values = try source.resourceValues(forKeys: [.isSymbolicLinkKey])
|
||||
guard values.isSymbolicLink != true else { throw CompanionLibraryFailure(message: "The disk path contains a symbolic link.") }
|
||||
}
|
||||
guard source.resolvingSymlinksInPath().path.hasPrefix(root.resolvingSymlinksInPath().path + "/") else {
|
||||
throw CompanionLibraryFailure(message: "The disk path leaves its installation.")
|
||||
}
|
||||
let descriptor = open(source.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)
|
||||
guard descriptor >= 0 else { throw CompanionLibraryFailure(message: "The installed disk could not be read.") }
|
||||
let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
|
||||
defer { try? handle.close() }
|
||||
var info = stat()
|
||||
guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFREG,
|
||||
info.st_size > 0, info.st_size <= 16 * 1024 * 1024 else {
|
||||
throw CompanionLibraryFailure(message: "Choose a floppy image within the 16 MiB limit.")
|
||||
}
|
||||
let data = try handle.read(upToCount: 16 * 1024 * 1024 + 1) ?? Data()
|
||||
guard data.count == Int(info.st_size) else { throw CompanionLibraryFailure(message: "The installed disk changed while being read.") }
|
||||
try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
||||
let folder = destination.appendingPathComponent(UUID().uuidString, isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
|
||||
do {
|
||||
let copy = folder.appendingPathComponent(source.lastPathComponent)
|
||||
try data.write(to: copy, options: .atomic)
|
||||
return copy
|
||||
} catch { try? FileManager.default.removeItem(at: folder); throw error }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
Reference in new issue
Block a user