Files
2026-10-11 16:01:50 -07:00

411 lines
16 KiB
Swift

import CryptoKit
import Foundation
import Observation
/// The account's games and their downloads, as the library screen sees them.
///
/// Games download one at a time, in the order they were asked for, into
/// `Documents/steamapps`, which the Files app shows. What has been downloaded
/// and what was left unfinished is remembered between launches.
@Observable @MainActor
final class LibraryModel {
struct Game: Identifiable, Codable, Hashable, Sendable {
let id: UInt32
var name: String
/// About how much there is to download; 0 when Steam does not say.
var downloadBytes: UInt64
}
/// A download that has been started and is not finished.
struct Download: Equatable {
enum Status: Equatable {
case waiting
case running
case paused
case stopped(String)
}
var status: Status
var stage: DownloadProgress.Stage = .preparing
var doneBytes: UInt64 = 0
var totalBytes: UInt64 = 0
var bytesPerSecond: Double = 0
var fraction: Double? {
totalBytes > 0 ? min(1, Double(doneBytes) / Double(totalBytes)) : nil
}
}
/// A game that is fully on this device.
struct Finished: Codable, Equatable {
var folder: String
var bytes: UInt64
var build: UInt32
}
private(set) var games: [Game] = []
private(set) var isRefreshing = false
/// False until the list has been fetched or read from disk once.
private(set) var hasList = false
private(set) var downloads: [UInt32: Download] = [:]
private(set) var finished: [UInt32: Finished] = [:]
var problem: String?
/// The download that is running now.
var current: (game: Game, download: Download)? {
guard let id = running?.id, let download = downloads[id], download.status == .running,
let game = games.first(where: { $0.id == id }) else { return nil }
return (game, download)
}
var waitingCount: Int { queue.count }
var isBusy: Bool { running != nil || !queue.isEmpty }
// MARK: Parts
private let signIn: SignInModel
private let client: SteamClient
private let catalog: SteamCatalog
private let keeper = BackgroundKeeper()
private let library: URL
private let notes: URL
private let stateFile: URL
private var started = false
private var ownedApps: Set<UInt32> = []
/// Whose list this is, as a hash, so that the saved file names no account.
private var listOwner: String?
private var listed: Date?
/// The folder each started download went into, so it can be found again whatever the list says.
private var folders: [UInt32: String] = [:]
private var queue: [UInt32] = []
private var running: (id: UInt32, task: Task<Void, Never>)?
/// Asked to continue while still winding down from a pause.
private var restart: Set<UInt32> = []
/// Paused because the app ran out of time in the background.
private var interrupted: [UInt32] = []
/// Being deleted; not to be started or marked as downloaded meanwhile.
private var removing: Set<UInt32> = []
/// The folder the running download reported, which arrives off the main thread.
private var chosenFolder: ChosenFolder?
private var lastSave = Date.distantPast
/// `client` and `folder` are for tests; an app uses the defaults.
init(signIn: SignInModel, client: SteamClient? = nil, folder: URL? = nil) {
self.signIn = signIn
let current = signIn.current
let client = client ?? SteamClient { current.value.map { .account($0) } }
self.client = client
catalog = SteamCatalog(client: client)
let manager = FileManager.default
let documents = folder ?? manager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let support = (folder ?? manager.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0])
.appendingPathComponent("SteamDownloader", isDirectory: true)
library = documents.appendingPathComponent("steamapps", isDirectory: true)
notes = support.appendingPathComponent("unfinished", isDirectory: true)
stateFile = support.appendingPathComponent("library.json")
}
/// Called when the first screen appears; once per launch.
func start() {
guard !started else { return }
started = true
signIn.onChange = { [weak self] in self?.accountChanged() }
keeper.onTimeUp = { [weak self] in self?.interruptForBackground() }
keeper.onReturn = { [weak self] in self?.continueAfterBackground() }
readState()
if signIn.isSignedIn, Date().timeIntervalSince(listed ?? .distantPast) > 6 * 3600 {
Task { await refresh(byRequest: false) }
}
}
// MARK: The list
/// Fetches the list of games from Steam. `byRequest` is false for the
/// refresh the app does by itself, which stays quiet about a failure when
/// there is an older list to show.
func refresh(byRequest: Bool = true) async {
guard signIn.isSignedIn, !isRefreshing else { return }
isRefreshing = true
defer { isRefreshing = false }
do {
let owned = try await catalog.ownedAppIDs()
let described = try await catalog.apps(owned.sorted())
var byID: [UInt32: Game] = [:]
for app in described where app.isPlayable {
byID[app.id] = Game(id: app.id, name: app.name, downloadBytes: app.downloadBytes(owned: owned))
}
games = byID.values.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
ownedApps = owned
listOwner = Self.fingerprint(signIn.accountName)
listed = Date()
hasList = true
problem = nil
saveState()
} catch {
guard !(error is CancellationError) else { return }
if byRequest || games.isEmpty || Self.isRejection(error) {
problem = Self.words(for: error)
}
}
}
/// A sign-in was stored or removed.
private func accountChanged() {
problem = nil
if signIn.isSignedIn {
guard Self.fingerprint(signIn.accountName) != listOwner else { return }
games = []
ownedApps = []
hasList = false
Task { await refresh() }
} else {
for id in Array(downloads.keys) { pause(id) }
games = []
ownedApps = []
hasList = false
listOwner = nil
listed = nil
saveState()
Task { await client.disconnect() }
}
}
// MARK: Downloads
/// Starts a game's download, or continues one that was stopped.
func download(_ id: UInt32) {
guard signIn.isSignedIn else {
problem = SteamFailure.notSignedIn.errorDescription
return
}
guard finished[id] == nil, !queue.contains(id), !removing.contains(id) else { return }
if let running, running.id == id {
// Paused a moment ago and not stopped yet: pick it up again once it has.
if running.task.isCancelled, downloads[id] != nil {
restart.insert(id)
downloads[id]?.status = .waiting
}
return
}
var entry = downloads[id] ?? Download(status: .waiting)
entry.status = .waiting
entry.bytesPerSecond = 0
downloads[id] = entry
queue.append(id)
startNext()
}
func pause(_ id: UInt32) {
restart.remove(id)
interrupted.removeAll { $0 == id }
if let running, running.id == id {
running.task.cancel()
} else if let index = queue.firstIndex(of: id) {
queue.remove(at: index)
} else {
return
}
downloads[id]?.status = .paused
downloads[id]?.bytesPerSecond = 0
}
/// Stops a game's download if one is under way and deletes its files, finished or not.
func remove(_ id: UInt32) {
let stopping = running?.id == id ? running?.task : nil
pause(id)
downloads[id] = nil
finished[id] = nil
removing.insert(id)
saveState()
let library = library
let notes = notes
Task {
// Only once the download has let go is it known which folder it used.
await stopping?.value
let folder = self.folders.removeValue(forKey: id)
await Task.detached(priority: .utility) {
GameDownloader.remove(appID: id, folder: folder, library: library, notes: notes)
}.value
self.removing.remove(id)
self.saveState()
}
}
private func startNext() {
guard running == nil, !queue.isEmpty else { return }
let id = queue.removeFirst()
downloads[id]?.status = .running
downloads[id]?.stage = .preparing
keeper.workBegan(named: games.first { $0.id == id }?.name ?? "Steam game")
running = (id, Task { await self.run(id) })
}
private func run(_ id: UInt32) async {
var completed = false
let chosen = ChosenFolder()
chosenFolder = chosen
do {
try prepareLibrary()
let downloader = GameDownloader(client: client, catalog: catalog, library: library, notes: notes)
let owned = ownedApps
let game = try await downloader.download(appID: id, owned: owned, folderChosen: { chosen.name = $0 }, report: { [weak self] progress in
Task { @MainActor in self?.show(progress, for: id) }
})
folders[id] = game.folder
downloads[id] = nil
// A game deleted in its last moments stays deleted.
if !removing.contains(id) {
finished[id] = Finished(folder: game.folder, bytes: game.bytesOnDisk, build: game.buildID)
completed = true
}
} catch {
if error is CancellationError || Task.isCancelled {
if downloads[id] != nil, !restart.contains(id) { downloads[id]?.status = .paused }
} else if downloads[id] != nil {
downloads[id]?.status = .stopped(Self.words(for: error))
restart.remove(id)
if Self.isRejection(error) { problem = Self.words(for: error) }
}
downloads[id]?.bytesPerSecond = 0
}
if let folder = chosen.name { folders[id] = folder }
chosenFolder = nil
running = nil
if restart.remove(id) != nil, downloads[id] != nil { queue.insert(id, at: 0) }
saveState()
if queue.isEmpty { keeper.workEnded(success: completed) }
startNext()
}
private func show(_ progress: DownloadProgress, for id: UInt32) {
guard var entry = downloads[id], running?.id == id else { return }
entry.stage = progress.stage
// Each attempt starts by reading the file lists; until it knows better, the last figures stand.
if progress.totalBytes > 0 {
entry.doneBytes = progress.doneBytes
entry.totalBytes = progress.totalBytes
entry.bytesPerSecond = entry.status == .running ? progress.bytesPerSecond : 0
}
downloads[id] = entry
keeper.progressed(to: entry.fraction)
// Written down early, so that a download cut short by the app being closed can still be found.
if let folder = chosenFolder?.name, folders[id] != folder {
folders[id] = folder
saveState()
} else if Date().timeIntervalSince(lastSave) > 5 {
saveState()
}
}
/// Makes the library folder. Games can be downloaded again, so they are kept out of device backups.
private func prepareLibrary() throws {
var folder = library
try FileManager.default.createDirectory(at: folder.appendingPathComponent("common", isDirectory: true), withIntermediateDirectories: true)
var values = URLResourceValues()
values.isExcludedFromBackup = true
try? folder.setResourceValues(values)
}
// MARK: Background
private func interruptForBackground() {
var ids = queue
if let running, !running.task.isCancelled { ids.insert(running.id, at: 0) }
for id in ids { pause(id) }
interrupted = ids
}
private func continueAfterBackground() {
let ids = interrupted
interrupted = []
for id in ids { download(id) }
}
// MARK: Remembering
private struct Saved: Codable {
struct Unfinished: Codable {
var folder: String?
var done: UInt64
var total: UInt64
}
var owner: String?
var listed: Date?
var games: [Game] = []
var ownedApps: [UInt32] = []
var finished: [String: Finished] = [:]
var unfinished: [String: Unfinished] = [:]
}
private func readState() {
guard let data = try? Data(contentsOf: stateFile), let saved = try? JSONDecoder().decode(Saved.self, from: data) else { return }
let manager = FileManager.default
// What is listed as downloaded must still be there: the Files app can delete it.
for (key, game) in saved.finished {
guard let id = UInt32(key),
manager.fileExists(atPath: library.appendingPathComponent("common/\(game.folder)").path) else { continue }
finished[id] = game
folders[id] = game.folder
}
for (key, partial) in saved.unfinished {
guard let id = UInt32(key), finished[id] == nil, GameDownloader.hasNotes(appID: id, notes: notes) else { continue }
folders[id] = partial.folder
downloads[id] = Download(status: .paused, stage: .downloading, doneBytes: partial.done, totalBytes: partial.total)
}
// The list itself belongs to an account.
if signIn.isSignedIn, saved.owner == Self.fingerprint(signIn.accountName) {
games = saved.games
ownedApps = Set(saved.ownedApps)
listOwner = saved.owner
listed = saved.listed
hasList = saved.listed != nil
}
}
private func saveState() {
lastSave = Date()
var saved = Saved(owner: listOwner, listed: listed, games: games, ownedApps: ownedApps.sorted())
for (id, game) in finished { saved.finished[String(id)] = game }
for (id, download) in downloads {
saved.unfinished[String(id)] = Saved.Unfinished(folder: folders[id], done: download.doneBytes, total: download.totalBytes)
}
guard let data = try? JSONEncoder().encode(saved) else { return }
try? FileManager.default.createDirectory(at: stateFile.deletingLastPathComponent(), withIntermediateDirectories: true)
try? data.write(to: stateFile, options: .atomic)
}
// MARK: Words
private static func fingerprint(_ accountName: String?) -> String? {
accountName.map { SHA256.hash(data: Data($0.lowercased().utf8)).map { String(format: "%02x", $0) }.joined() }
}
private static func isRejection(_ error: Error) -> Bool {
if case .signInRejected? = error as? SteamFailure { return true }
return false
}
private static func words(for error: Error) -> String {
if let error = error as? LocalizedError, let text = error.errorDescription { return text }
if let error = error as? URLError {
return error.code == .notConnectedToInternet ? "There's no internet connection." : "The network failed (\(error.code.rawValue)). Try again."
}
return "Something went wrong. Try again."
}
}
/// The folder name a running download settled on, handed across threads.
private final class ChosenFolder: @unchecked Sendable {
private let lock = NSLock()
private var stored: String?
var name: String? {
get { lock.withLock { stored } }
set { lock.withLock { stored = newValue } }
}
}