Files
VCCPlusOSS/platforms/macos/App/SoftwareLibraryArtwork.swift
T

244 lines
13 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
import ImageIO
import UniformTypeIdentifiers
import CryptoKit
/// Shared by the sidebar and both cover presentations.
enum SoftwareLibraryCategoryStyle {
static func symbol(for type: String) -> String {
switch type {
case "Games": return "gamecontroller"
case "Applications": return "macwindow"
case "Blank Media": return "document"
case "Hardware": return "airport.extreme"
case "Operating Systems": return "desktopcomputer.and.arrow.down"
case "Music": return "music.note"
case "Educational": return "graduationcap"
case "Programming": return "curlybraces"
case "Utilities": return "wrench.and.screwdriver"
case "Pictures": return "photo.on.rectangle"
case "Books", "Magazines": return "book"
case "Demos": return "play.rectangle"
default: return "books.vertical"
}
}
static func tint(for type: String) -> Color {
switch type {
case "Games": return .indigo
case "Applications", "Operating Systems": return .blue
case "Educational": return .teal
case "Music": return .purple
case "Programming", "Utilities": return .orange
default: return .secondary
}
}
}
/// Only appearance starts a request. Hosted, fingerprinted PNG thumbnails are
/// cached locally; originals and PDF manuals never pass through this loader.
struct SoftwareLibraryArtworkView: View {
@Environment(\.companionLibraryAccess) private var companion
let asset: SoftwareLibraryAsset?
let cacheDirectory: URL
let softwareType: String
@State private var image: CGImage?
@State private var loading = false
var body: some View {
ZStack {
RoundedRectangle(cornerRadius: 9).fill(.quaternary.opacity(0.35))
if let image {
Image(decorative: image, scale: 1).resizable().scaledToFit().padding(5)
} else {
VStack(spacing: 12) {
Image(systemName: SoftwareLibraryCategoryStyle.symbol(for: softwareType))
.font(.system(size: 48, weight: .light))
.foregroundStyle(SoftwareLibraryCategoryStyle.tint(for: softwareType).opacity(0.7))
Text(softwareType == "Other" ? "Software" : softwareType)
.font(.caption.weight(.medium)).foregroundStyle(.secondary)
.lineLimit(1).minimumScaleFactor(0.8)
}.padding(16)
if loading { ProgressView().controlSize(.small).frame(maxHeight: .infinity, alignment: .bottom).padding(8) }
}
}
.accessibilityElement(children: .ignore)
.accessibilityLabel(image != nil ? "Artwork: " + (asset?.name ?? "") : softwareType + " category cover")
.accessibilityValue(image != nil ? "Loaded" : (loading ? "Loading artwork" : "Category illustration"))
.task(id: asset.map { SoftwareLibraryArtworkCache.cacheKey(for: $0) }) {
image = nil
loading = false
guard let asset else { return }
loading = true
defer { loading = false }
do {
let data: Data
if let companion {
let response = try await companion.libraryRequest(.init(operation: .thumbnail, assetID: asset.id))
if let message = response.errorMessage { throw CompanionLibraryFailure(message: message) }
guard let received = response.assetData else { throw SoftwareLibraryArtworkCache.Failure.response }
data = received
} else {
data = try await SoftwareLibraryArtworkCache.shared.thumbnail(for: asset, directory: cacheDirectory)
}
try Task.checkCancellation()
image = SoftwareLibraryArtworkCache.image(from: data)
} catch { /* Quiet placeholder: art availability never blocks browsing. */ }
}
}
}
actor SoftwareLibraryArtworkCache {
static let shared = SoftwareLibraryArtworkCache()
static let maximumSourceBytes = 8 * 1024 * 1024
static let maximumThumbnailBytes = 2 * 1024 * 1024
static let maximumPixelSize = 640
private var active = 0
private let session: URLSession
init(session: URLSession? = nil) {
if let session { self.session = session }
else {
let configuration = URLSessionConfiguration.ephemeral
configuration.timeoutIntervalForRequest = 20
configuration.timeoutIntervalForResource = 45
configuration.httpMaximumConnectionsPerHost = 4
configuration.urlCache = nil
self.session = URLSession(configuration: configuration, delegate: LibraryArtworkRedirects(), delegateQueue: nil)
}
}
enum Failure: Error { case unsupported, oversized, response, fingerprint, invalidImage, invalidCache }
static func accepts(_ url: URL) -> Bool {
guard url.scheme?.lowercased() == "https", url.host?.lowercased() == "vccplus.brianholman.com",
url.user == nil, url.password == nil, url.port == nil || url.port == 443,
url.path.hasPrefix("/dl/software/CoCoLibrary/Artwork/Thumbnails/"),
url.pathExtension.lowercased() == "png", url.query == nil, url.fragment == nil,
!url.path.contains("\\"), !url.pathComponents.contains(".."),
!url.pathComponents.contains(".") else { return false }
return true
}
static func canDisplay(_ asset: SoftwareLibraryAsset) -> Bool {
guard let url = asset.thumbnailURL, accepts(url),
let checksum = asset.thumbnailSHA256, checksum.count == 64,
checksum.allSatisfy({ $0.isHexDigit }),
let size = asset.thumbnailByteSize, size > 0, size <= maximumThumbnailBytes else { return false }
return true
}
static func cacheKey(for asset: SoftwareLibraryAsset) -> String {
let identity = "hosted-thumbnail-v2\n" + (asset.thumbnailURL ?? asset.sourceURL).absoluteString + "\n" + (asset.thumbnailSHA256 ?? "unverified")
return SHA256.hash(data: Data(identity.utf8)).map { String(format: "%02x", $0) }.joined()
}
static func image(from data: Data) -> CGImage? {
guard data.count <= maximumThumbnailBytes,
let source = CGImageSourceCreateWithData(data as CFData, nil),
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
let width = properties[kCGImagePropertyPixelWidth] as? Int,
let height = properties[kCGImagePropertyPixelHeight] as? Int,
width > 0, height > 0, width <= maximumPixelSize, height <= maximumPixelSize else { return nil }
return CGImageSourceCreateImageAtIndex(source, 0, [kCGImageSourceShouldCache: false] as CFDictionary)
}
static func downsample(_ data: Data, expectedSHA256: String?) throws -> Data {
guard data.count <= maximumSourceBytes else { throw Failure.oversized }
if let expectedSHA256 {
let actual = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
guard actual == expectedSHA256.lowercased() else { throw Failure.fingerprint }
}
guard let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),
let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: maximumPixelSize,
kCGImageSourceShouldCacheImmediately: false
] as CFDictionary) else { throw Failure.invalidImage }
let output = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(output, UTType.png.identifier as CFString, 1, nil) else { throw Failure.invalidImage }
CGImageDestinationAddImage(destination, thumbnail, nil)
guard CGImageDestinationFinalize(destination), output.length <= maximumThumbnailBytes else { throw Failure.invalidImage }
return output as Data
}
func thumbnail(for asset: SoftwareLibraryAsset, directory: URL) async throws -> Data {
try Task.checkCancellation()
guard Self.canDisplay(asset), let url = asset.thumbnailURL,
let fingerprint = asset.thumbnailSHA256 else { throw Failure.unsupported }
guard directory.isFileURL else { throw Failure.invalidCache }
let path = directory.appendingPathComponent(Self.cacheKey(for: asset) + ".png")
if let cached = cachedThumbnail(path, expectedSHA256: fingerprint) { return cached }
while active >= 4 {
try await Task.sleep(nanoseconds: 50_000_000)
}
try Task.checkCancellation()
// Another visible cell may have populated this shared cache while waiting.
if let cached = cachedThumbnail(path, expectedSHA256: fingerprint) { return cached }
active += 1
defer { active -= 1 }
var request = URLRequest(url: url)
request.setValue("VCCPlus/SoftwareLibrary-Artwork", forHTTPHeaderField: "User-Agent")
let (bytes, response) = try await session.bytes(for: request)
guard let http = response as? HTTPURLResponse, http.statusCode == 200,
let finalURL = http.url, Self.accepts(finalURL) else { throw Failure.response }
guard http.expectedContentLength <= Self.maximumThumbnailBytes else { throw Failure.oversized }
var data = Data()
data.reserveCapacity(min(max(Int(http.expectedContentLength), 0), Self.maximumThumbnailBytes))
for try await byte in bytes {
guard data.count < Self.maximumThumbnailBytes else { throw Failure.oversized }
data.append(byte)
if data.count.isMultiple(of: 4096) { try Task.checkCancellation() }
}
try Task.checkCancellation()
guard Int64(data.count) == asset.thumbnailByteSize,
SHA256.hash(data: data).map({ String(format: "%02x", $0) }).joined() == fingerprint.lowercased()
else { throw Failure.fingerprint }
guard Self.image(from: data) != nil else { throw Failure.invalidImage }
let thumbnail = data
try Task.checkCancellation()
// A missing/unwritable cache must not suppress successfully decoded art.
do {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
guard !((try? path.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) ?? false) else { throw Failure.invalidCache }
try thumbnail.write(to: path, options: .atomic)
trim(directory)
} catch { }
return thumbnail
}
private func cachedThumbnail(_ path: URL, expectedSHA256: String) -> Data? {
guard let values = try? path.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]),
values.isRegularFile == true, values.isSymbolicLink != true,
let size = values.fileSize, size <= Self.maximumThumbnailBytes,
let data = try? Data(contentsOf: path), Self.image(from: data) != nil,
SHA256.hash(data: data).map({ String(format: "%02x", $0) }).joined() == expectedSHA256.lowercased() else { return nil }
return data
}
private func trim(_ directory: URL) {
let keys: Set<URLResourceKey> = [.fileSizeKey, .contentModificationDateKey, .isRegularFileKey, .isSymbolicLinkKey]
guard let urls = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: Array(keys)) else { return }
let entries = urls.compactMap { url -> (URL, Int, Date)? in
let stem = url.deletingPathExtension().lastPathComponent
guard url.pathExtension == "png", stem.count == 64, stem.allSatisfy({ $0.isHexDigit }),
let values = try? url.resourceValues(forKeys: keys), values.isRegularFile == true,
values.isSymbolicLink != true else { return nil }
return (url, values.fileSize ?? 0, values.contentModificationDate ?? .distantPast)
}.sorted { $0.2 < $1.2 }
var total = entries.reduce(0) { $0 + $1.1 }
for entry in entries where total > 128 * 1024 * 1024 {
do { try FileManager.default.removeItem(at: entry.0); total -= entry.1 } catch { }
}
}
}
private final class LibraryArtworkRedirects: NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
completionHandler(request.url.map(SoftwareLibraryArtworkCache.accepts) == true ? request : nil)
}
}