Manic EMU is an all-in-one retro game emulator for iOS. It packs powerful features while keeping a clean, sleek UI and delivering buttery-smooth gameplay.
Swift
Wire RomM browsing and pending download links.
Daiuno7e4321322e51
diff --git a/ManicEmu/ManicEmu.xcodeproj/project.pbxproj b/ManicEmu/ManicEmu.xcodeproj/project.pbxprojindex 8d69dc6c..ce6c6e90 100644--- a/ManicEmu/ManicEmu.xcodeproj/project.pbxproj+++ b/ManicEmu/ManicEmu.xcodeproj/project.pbxproj@@ -361,6 +361,7 @@579093BD303C7D9100A53656 /* WebDavServiceProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57F632AC2D6FEC25007270E8 /* WebDavServiceProvider.swift */; };68A011012026091500000002 /* RommClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68A011012026091500000001 /* RommClient.swift */; };68A011012026091500000004 /* RommServiceProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68A011012026091500000003 /* RommServiceProvider.swift */; };+ 68A01101202609150000000A /* RommLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68A011012026091500000009 /* RommLibrary.swift */; };579093BE303C7D9100A53656 /* ThemeColorCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 570F590F2DC5BAF4007BFD92 /* ThemeColorCollectionViewCell.swift */; };579093BF303C7D9100A53656 /* CheatTypeExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57B6ECCC2D798419002E619C /* CheatTypeExtensions.swift */; };579093C0303C7D9100A53656 /* ARMaxDecrypt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57B6ECD02D7984A0002E619C /* ARMaxDecrypt.swift */; };@@ -1055,6 +1056,7 @@57CDCDAC2FD5CBD3005BA4C8 /* WebDavServiceProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57F632AC2D6FEC25007270E8 /* WebDavServiceProvider.swift */; };68A011012026091500000005 /* RommClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68A011012026091500000001 /* RommClient.swift */; };68A011012026091500000006 /* RommServiceProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68A011012026091500000003 /* RommServiceProvider.swift */; };+ 68A01101202609150000000B /* RommLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68A011012026091500000009 /* RommLibrary.swift */; };57CDCDAD2FD5CBD3005BA4C8 /* ThemeColorCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 570F590F2DC5BAF4007BFD92 /* ThemeColorCollectionViewCell.swift */; };57CDCDAE2FD5CBD3005BA4C8 /* CheatTypeExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57B6ECCC2D798419002E619C /* CheatTypeExtensions.swift */; };57CDCDAF2FD5CBD3005BA4C8 /* OnlinePlaySettingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5754D88A2E274AB9001EA5ED /* OnlinePlaySettingView.swift */; };@@ -1550,6 +1552,7 @@57F632AD2D6FEC32007270E8 /* WebDavServiceProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57F632AC2D6FEC25007270E8 /* WebDavServiceProvider.swift */; };68A011012026091500000007 /* RommClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68A011012026091500000001 /* RommClient.swift */; };68A011012026091500000008 /* RommServiceProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68A011012026091500000003 /* RommServiceProvider.swift */; };+ 68A01101202609150000000C /* RommLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68A011012026091500000009 /* RommLibrary.swift */; };57F632E32D714E46007270E8 /* WebDavKit in Frameworks */ = {isa = PBXBuildFile; productRef = 57F632E22D714E46007270E8 /* WebDavKit */; };57F632FE2D718236007270E8 /* SettingsListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57F632FD2D71822A007270E8 /* SettingsListView.swift */; };57F633002D718366007270E8 /* SettingItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57F632FF2D718360007270E8 /* SettingItem.swift */; };@@ -2053,6 +2056,7 @@576F0E142D88208C00D2A1BA /* SettingsMembershipGiftView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsMembershipGiftView.swift; sourceTree = "<group>"; };576F0E162D8820AB00D2A1BA /* MembershipInfoView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MembershipInfoView.swift; sourceTree = "<group>"; };577005542D3CC23A00762E8F /* FilesImporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilesImporter.swift; sourceTree = "<group>"; };+ 68A011012026091500000009 /* RommLibrary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RommLibrary.swift; sourceTree = "<group>"; };577005572D3CC30400762E8F /* FileType.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileType.swift; sourceTree = "<group>"; };577005592D3CC35500762E8F /* Game.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Game.swift; sourceTree = "<group>"; };5770055C2D3CC3D700762E8F /* GameSaveState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GameSaveState.swift; sourceTree = "<group>"; };@@ -13216,6 +13220,7 @@577005D32D3F2F8200762E8F /* WebServer.swift */,577005752D3D42FA00762E8F /* FileHashUtil.swift */,577005542D3CC23A00762E8F /* FilesImporter.swift */,+ 68A011012026091500000009 /* RommLibrary.swift */,577005D52D3F396C00762E8F /* PasteImporter.swift */,575FF8E72D34A6DF0043B2F3 /* System.swift */,5708351B2D3216930079D410 /* Log.swift */,@@ -13815,6 +13820,7 @@579093BD303C7D9100A53656 /* WebDavServiceProvider.swift in Sources */,68A011012026091500000002 /* RommClient.swift in Sources */,68A011012026091500000004 /* RommServiceProvider.swift in Sources */,+ 68A01101202609150000000A /* RommLibrary.swift in Sources */,579093BE303C7D9100A53656 /* ThemeColorCollectionViewCell.swift in Sources */,579093BF303C7D9100A53656 /* CheatTypeExtensions.swift in Sources */,579093C0303C7D9100A53656 /* ARMaxDecrypt.swift in Sources */,@@ -14284,6 +14290,7 @@57CDCDAC2FD5CBD3005BA4C8 /* WebDavServiceProvider.swift in Sources */,68A011012026091500000005 /* RommClient.swift in Sources */,68A011012026091500000006 /* RommServiceProvider.swift in Sources */,+ 68A01101202609150000000B /* RommLibrary.swift in Sources */,57CDCDAD2FD5CBD3005BA4C8 /* ThemeColorCollectionViewCell.swift in Sources */,57CDCDAE2FD5CBD3005BA4C8 /* CheatTypeExtensions.swift in Sources */,57B6ECD22D7984A0002E619C /* ARMaxDecrypt.swift in Sources */,@@ -14735,6 +14742,7 @@57F632AD2D6FEC32007270E8 /* WebDavServiceProvider.swift in Sources */,68A011012026091500000007 /* RommClient.swift in Sources */,68A011012026091500000008 /* RommServiceProvider.swift in Sources */,+ 68A01101202609150000000C /* RommLibrary.swift in Sources */,570F59102DC5BB03007BFD92 /* ThemeColorCollectionViewCell.swift in Sources */,57B6ECCD2D798425002E619C /* CheatTypeExtensions.swift in Sources */,57B6ECD12D7984A0002E619C /* ARMaxDecrypt.swift in Sources */,diff --git a/ManicEmu/ManicEmu/Sources/Business/Common/Models/ExtraKey.swift b/ManicEmu/ManicEmu/Sources/Business/Common/Models/ExtraKey.swiftindex b840ba3a..d1df83c0 100644--- a/ManicEmu/ManicEmu/Sources/Business/Common/Models/ExtraKey.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Common/Models/ExtraKey.swift@@ -99,4 +99,10 @@ enum ExtraKey: String {case urlGameURL/// JSON recipe mapping FLASHSkinButton raw values to FLASHKey (KeyboardEvent.code) values.case skinButtonBinding+ /// RomM ROM id for a game imported from that service.+ case rommRomId+ /// ImportService.id of the RomM instance that imported the game.+ case rommServiceId+ /// Play-time milliseconds already pushed to RomM; only the local delta is sent next time.+ case rommPlayDurationPushed}diff --git a/ManicEmu/ManicEmu/Sources/Business/Common/Views/FileBrowserView.swift b/ManicEmu/ManicEmu/Sources/Business/Common/Views/FileBrowserView.swiftindex 0318436e..764bc078 100644--- a/ManicEmu/ManicEmu/Sources/Business/Common/Views/FileBrowserView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Common/Views/FileBrowserView.swift@@ -387,7 +387,7 @@ class FileBrowserView: BaseView {let group = DispatchGroup()for item in items {if DownloadManager.shared.sessionManager.succeededTasks.contains(where: { $0.fileName == item.name }) {- //已经下载过了报错+ // Skip files that are already in the download cache.errors.append(ImportError.downloadExist(fileName: item.name))continue} else {@@ -449,6 +449,17 @@ class FileBrowserView: BaseView {downloadItems[item.name] = url}headers = request?.allHTTPHeaderFields+ } else if let provider = provider as? RommServiceProvider {+ let request = provider.downloadableRequest(of: item)+ if let url = request?.url {+ downloadItems[item.name] = url+ if let romId = Int(item.id.split(separator: "/").first.map(String.init) ?? "") {+ RommLibrary.shared.registerDownloadedRom(fileName: item.name,+ romId: romId,+ serviceId: provider.serviceId)+ }+ }+ headers = request?.allHTTPHeaderFields}}}diff --git a/ManicEmu/ManicEmu/Sources/Business/Import/Models/RommClient.swift b/ManicEmu/ManicEmu/Sources/Business/Import/Models/RommClient.swiftindex ddc45d29..ec9b764a 100644--- a/ManicEmu/ManicEmu/Sources/Business/Import/Models/RommClient.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Import/Models/RommClient.swift@@ -100,11 +100,17 @@ final class RommClient {var PaginationLimit: Int { 250 }- init?(scheme: String, host: String, port: Int?, user: String?, password: String?) {+ init?(scheme: String, host: String, port: Int?, user: String?, password: String?, path: String? = nil) {var components = URLComponents()components.scheme = schemecomponents.host = hostcomponents.port = port+ if let path, !path.isEmpty, path != "/" {+ var normalized = path+ if !normalized.hasPrefix("/") { normalized = "/" + normalized }+ if normalized.hasSuffix("/") { normalized.removeLast() }+ components.path = normalized+ }guard let url = components.url else { return nil }self.baseURL = urlself.authHeader = Self.makeAuthHeader(user: user, password: password)@@ -124,8 +130,13 @@ final class RommClient {}func request(path: String, query: [URLQueryItem] = []) -> URLRequest? {- guard var components = URLComponents(url: baseURL.appendingPathComponent(path),- resolvingAgainstBaseURL: false) else { return nil }+ guard var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else { return nil }+ let api = path.hasPrefix("/") ? path : "/" + path+ if components.path.isEmpty || components.path == "/" {+ components.path = api+ } else {+ components.path += api+ }if !query.isEmpty { components.queryItems = query }guard let url = components.url else { return nil }var req = URLRequest(url: url)@@ -166,6 +177,17 @@ final class RommClient {return try Self.jsonDecoder.decode(T.self, from: await data(for: req))}+ private func getList<T: Decodable>(_ path: String, query: [URLQueryItem] = []) async throws -> [T] {+ guard let req = request(path: path, query: query) else {+ throw URLError(.badURL)+ }+ let payload = try await data(for: req)+ if let page = try? Self.jsonDecoder.decode(RommPage<T>.self, from: payload) {+ return page.items+ }+ return try Self.jsonDecoder.decode([T].self, from: payload)+ }+func data(for request: URLRequest) async throws -> Data {let (data, response) = try await session.data(for: request)guard let http = response as? HTTPURLResponse, 200..<300 ~= http.statusCode else {@@ -213,15 +235,15 @@ final class RommClient {}func saves(romID: Int) async throws -> [RommSave] {- try await get(SaveApiStub, query: [.init(name: "rom_id", value: "\(romID)")])+ try await getList(SaveApiStub, query: [.init(name: "rom_id", value: "\(romID)")])}func states(romID: Int) async throws -> [RommState] {- try await get(StateApiStub, query: [.init(name: "rom_id", value: "\(romID)")])+ try await getList(StateApiStub, query: [.init(name: "rom_id", value: "\(romID)")])}func playSessions(romID: Int) async throws -> [RommPlaySession] {- try await get(PlaySessionApiStub, query: [.init(name: "rom_id", value: "\(romID)")])+ try await getList(PlaySessionApiStub, query: [.init(name: "rom_id", value: "\(romID)")])}func saveContentRequest(saveID: Int) -> URLRequest? {diff --git a/ManicEmu/ManicEmu/Sources/Business/Import/Models/RommServiceProvider.swift b/ManicEmu/ManicEmu/Sources/Business/Import/Models/RommServiceProvider.swiftindex 47dcfd09..c1a79848 100644--- a/ManicEmu/ManicEmu/Sources/Business/Import/Models/RommServiceProvider.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Import/Models/RommServiceProvider.swift@@ -42,7 +42,8 @@ class RommServiceProvider: CloudServiceProvider {host: service.host ?? "",port: service.port,user: service.user,- password: service.password)+ password: service.password,+ path: service.path)}func contentsOfDirectory(_ directory: CloudServiceKit.CloudItem,diff --git a/ManicEmu/ManicEmu/Sources/Business/Import/Views/AddImportServiceView.swift b/ManicEmu/ManicEmu/Sources/Business/Import/Views/AddImportServiceView.swiftindex 69e8b527..2cacd105 100644--- a/ManicEmu/ManicEmu/Sources/Business/Import/Views/AddImportServiceView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Import/Views/AddImportServiceView.swift@@ -71,6 +71,7 @@ class AddImportServiceView: BaseView {var services: [ImportService] = []services.append(ImportService.genService(type: .webdav))services.append(ImportService.genService(type: .samba))+ services.append(ImportService.genService(type: .romm))return services}()diff --git a/ManicEmu/ManicEmu/Sources/Business/Import/Views/LanServiceEditView.swift b/ManicEmu/ManicEmu/Sources/Business/Import/Views/LanServiceEditView.swiftindex e3c44f08..e7ced865 100644--- a/ManicEmu/ManicEmu/Sources/Business/Import/Views/LanServiceEditView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Import/Views/LanServiceEditView.swift@@ -60,7 +60,7 @@ class LanServiceEditView: BaseView {break}} else if action.isBottom {- //点击连接处理+ // Connect after the form validates.self.listPageView.collectionView.endEditing(true)UIView.makeLoading()func handleServiceDetail() {@@ -79,7 +79,7 @@ class LanServiceEditView: BaseView {}}if self.service.type == .samba {- //验证smaba服务是否可以连接+ // Verify the SMB service is reachable.if let host = self.service.host {let client = SMBClient(host: host, port: self.service.port ?? 445)Task {@@ -130,7 +130,38 @@ class LanServiceEditView: BaseView {}} catch {await MainActor.run {- //发生错误+ UIView.hideLoading()+ UIView.makeToast(message: R.string.localizable.addLandServiceFailed(self.service.title))+ }+ }+ }+ } else {+ UIView.hideLoading()+ UIView.makeToast(message: R.string.localizable.errorUnknown())+ }+ } else if self.service.type == .romm {+ if let host = service.host, let scheme = service.scheme,+ let client = RommClient(scheme: scheme,+ host: host,+ port: service.port,+ user: service.user,+ password: service.password,+ path: service.path) {+ Task {+ do {+ _ = try await client.platforms()+ handleServiceDetail()+ ImportService.change { realm in+ realm.add(self.service)+ }+ await MainActor.run {+ self.hide()+ self.successHandler?()+ UIView.hideLoading()+ UIView.makeToast(message: R.string.localizable.addLandServiceSuccess(self.service.title))+ }+ } catch {+ await MainActor.run {UIView.hideLoading()UIView.makeToast(message: R.string.localizable.addLandServiceFailed(self.service.title))}@@ -149,7 +180,7 @@ class LanServiceEditView: BaseView {return view}()- private var editItems: [EditItem] = [+ private lazy var editItems: [EditItem] = [EditItem(title: R.string.localizable.landServiceEditServerName(),placeholderString: R.string.localizable.landServiceEditServerNamePlaceholder(),keyboardType: .default,@@ -169,7 +200,9 @@ class LanServiceEditView: BaseView {type: .user,returnKeyType: .next),EditItem(title: R.string.localizable.landServiceEditPassword(),- placeholderString: R.string.localizable.landServiceEditOptionalPlaceholder(),+ placeholderString: service.type == .romm+ ? R.string.localizable.rommPasswordOrApiKey()+ : R.string.localizable.landServiceEditOptionalPlaceholder(),keyboardType: .default,requiredField: false,type: .password,@@ -222,18 +255,17 @@ class LanServiceEditView: BaseView {if let components = inputUrl?.validateAndExtractURLComponents {if service.type == .samba {if let scheme = components.scheme, scheme.lowercased() != "smb" {- //如果填写了scheme,但不是smb就不行+ // Reject a non-smb scheme when one is provided.isValid = falsebreak}- } else if service.type == .webdav {+ } else if service.type == .webdav || service.type == .romm {guard let scheme = components.scheme else {- //webdav的scheme必须存在+ // WebDAV and RomM require http or https.isValid = falsebreak}if scheme.lowercased() != "http" && scheme.lowercased() != "https" {- //webdav的scheme必须是http或httpsisValid = falsebreak}diff --git a/ManicEmu/ManicEmu/Sources/Business/Play/Models/Game.swift b/ManicEmu/ManicEmu/Sources/Business/Play/Models/Game.swiftindex 05a55568..378fe205 100644--- a/ManicEmu/ManicEmu/Sources/Business/Play/Models/Game.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Play/Models/Game.swift@@ -146,12 +146,36 @@ class Game: Object, ObjectUpdatable {FileManager.default.fileExists(atPath: gameSaveUrl.path)}- /// 文件名 包含名称和扩展名+ /// File name including extension.var fileName: String {"\(name).\(fileExtension)"}- //游戏文件路径+ var rommRomId: Int? {+ get {+ if let value = getExtraInt(key: ExtraKey.rommRomId.rawValue) { return value }+ if let number = getExtra(key: ExtraKey.rommRomId.rawValue) as? NSNumber { return number.intValue }+ return nil+ }+ set { updateExtra(key: ExtraKey.rommRomId.rawValue, value: newValue) }+ }++ var rommServiceId: String? {+ get { getExtraString(key: ExtraKey.rommServiceId.rawValue) }+ set { updateExtra(key: ExtraKey.rommServiceId.rawValue, value: newValue) }+ }++ var rommPlayDurationPushed: Double {+ get {+ if let value = getExtraDouble(key: ExtraKey.rommPlayDurationPushed.rawValue) { return value }+ if let value = getExtraInt(key: ExtraKey.rommPlayDurationPushed.rawValue) { return Double(value) }+ if let number = getExtra(key: ExtraKey.rommPlayDurationPushed.rawValue) as? NSNumber { return number.doubleValue }+ return 0+ }+ set { updateExtra(key: ExtraKey.rommPlayDurationPushed.rawValue, value: newValue) }+ }++ // ROM file pathvar romUrl: URL {if isMultiFileGame {return URL(fileURLWithPath: R.Path.Data.appendingPathComponent(fileName.deletingPathExtension).appendingPathComponent(fileName))diff --git a/ManicEmu/ManicEmu/Sources/Tools/Others/RommLibrary.swift b/ManicEmu/ManicEmu/Sources/Tools/Others/RommLibrary.swiftnew file mode 100644index 00000000..7faad8aa--- /dev/null+++ b/ManicEmu/ManicEmu/Sources/Tools/Others/RommLibrary.swift@@ -0,0 +1,540 @@+//+// RommLibrary.swift+// ManicEmu+//+// Created by Chris Habibi on 6/29/26.+// Copyright © 2026 Manic EMU. All rights reserved.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++import Foundation+import IceCream+import RealmSwift++/// Pending download links plus manual pull/push for games imported from a RomM service.+final class RommLibrary {+ static let shared = RommLibrary()+ private init() {}++ private static let pendingLinksKey = "RomMPendingSaveLinks"+ private static let stateFileSuffix = ".manicstate"++ struct TransferSummary {+ var succeeded = 0+ var failed = 0+ }++ // MARK: - Pending download → import bind++ func registerDownloadedRom(fileName: String, romId: Int, serviceId: String) {+ var map = pendingMap()+ map[fileName] = ["romId": romId, "serviceId": serviceId]+ UserDefaults.standard.set(map, forKey: Self.pendingLinksKey)+ }++ func hasPendingLink(fileName: String) -> Bool {+ pendingMap()[fileName] != nil+ }++ func discardPendingLink(fileName: String) {+ var map = pendingMap()+ guard map[fileName] != nil else { return }+ map[fileName] = nil+ UserDefaults.standard.set(map, forKey: Self.pendingLinksKey)+ }++ /// Bind extras and pull sidecar data after a newly created game import.+ func applyAfterImport(gameId: String, fileName: String? = nil) {+ Task { @MainActor in+ await self.applyAfterImportOnMain(gameId: gameId, fileName: fileName)+ }+ }++ func linkedGameCount(service: ImportService) -> Int {+ linkedGameIds(serviceId: "\(service.id)").count+ }++ func pull(service: ImportService) async -> TransferSummary {+ await transfer(service: service, direction: .pull)+ }++ func push(service: ImportService) async -> TransferSummary {+ await transfer(service: service, direction: .push)+ }++ // MARK: - Pending helpers++ private func pendingMap() -> [String: [String: Any]] {+ UserDefaults.standard.dictionary(forKey: Self.pendingLinksKey) as? [String: [String: Any]] ?? [:]+ }++ private func consumePendingLink(fileName: String) -> (romId: Int, serviceId: String)? {+ var map = pendingMap()+ guard let entry = map[fileName],+ let romId = Self.intValue(entry["romId"]),+ let serviceId = entry["serviceId"] as? String else { return nil }+ map[fileName] = nil+ UserDefaults.standard.set(map, forKey: Self.pendingLinksKey)+ return (romId, serviceId)+ }++ private static func intValue(_ any: Any?) -> Int? {+ if let value = any as? Int { return value }+ if let number = any as? NSNumber { return number.intValue }+ if let string = any as? String { return Int(string) }+ return nil+ }++ // MARK: - Import sidecar++ @MainActor+ private func applyAfterImportOnMain(gameId: String, fileName: String?) async {+ guard let game = Database.realm.object(ofType: Game.self, forPrimaryKey: gameId), !game.isDeleted else {+ if let fileName { discardPendingLink(fileName: fileName) }+ return+ }+ let pendingName = fileName ?? game.fileName+ guard let pending = consumePendingLink(fileName: pendingName) ?? consumePendingLink(fileName: game.fileName) else {+ return+ }+ persistLink(gameId: gameId, romId: pending.romId, serviceId: pending.serviceId)+ guard let client = makeClient(serviceId: pending.serviceId) else {+ Log.debug("[RomM] applyAfterImport: client unavailable for service \(pending.serviceId)")+ return+ }+ do {+ try await pullSidecar(gameId: gameId, client: client, romId: pending.romId)+ } catch {+ Log.debug("[RomM] applyAfterImport failed for \(game.fileName): \(error)")+ }+ }++ // MARK: - Service transfer++ private enum Direction {+ case pull, push+ }++ private func transfer(service: ImportService, direction: Direction) async -> TransferSummary {+ let snapshot = await MainActor.run { ServiceSnapshot(service: service) }+ guard let client = snapshot.makeClient() else {+ return TransferSummary(succeeded: 0, failed: 1)+ }+ do {+ _ = try await client.platforms()+ } catch {+ Log.debug("[RomM] cannot reach service \(snapshot.id): \(error)")+ return TransferSummary(succeeded: 0, failed: 1)+ }++ let gameIds = await MainActor.run { linkedGameIds(serviceId: snapshot.id) }+ var summary = TransferSummary()+ for gameId in gameIds {+ do {+ switch direction {+ case .pull:+ try await pullSidecar(gameId: gameId, client: client)+ case .push:+ try await pushSidecar(gameId: gameId, client: client)+ }+ summary.succeeded += 1+ } catch {+ summary.failed += 1+ Log.debug("[RomM] \(direction == .pull ? "pull" : "push") failed for \(gameId): \(error)")+ }+ }+ return summary+ }++ @MainActor+ private func linkedGameIds(serviceId: String) -> [String] {+ Database.realm.objects(Game.self)+ .where { !$0.isDeleted }+ .filter { $0.rommServiceId == serviceId && $0.rommRomId != nil }+ .map { $0.id }+ }++ @MainActor+ private func persistLink(gameId: String, romId: Int, serviceId: String) {+ guard let game = Database.realm.object(ofType: Game.self, forPrimaryKey: gameId) else { return }+ game.rommRomId = romId+ game.rommServiceId = serviceId+ }++ @MainActor+ private func makeClient(serviceId: String) -> RommClient? {+ guard let serviceIdValue = Int(serviceId),+ let service = Database.realm.object(ofType: ImportService.self, forPrimaryKey: serviceIdValue),+ !service.isDeleted else { return nil }+ return ServiceSnapshot(service: service).makeClient()+ }++ // MARK: - Pull sidecar++ private func pullSidecar(gameId: String, client: RommClient, romId: Int? = nil) async throws {+ let resolvedRomId = try await MainActor.run { () -> Int in+ if let romId { return romId }+ guard let game = Database.realm.object(ofType: Game.self, forPrimaryKey: gameId),+ let linked = game.rommRomId else {+ throw RommLibraryError.missingGame+ }+ return linked+ }+ let rom = try await client.rom(id: resolvedRomId)+ await applyCover(gameId: gameId, client: client, rom: rom)+ await applyMetadata(gameId: gameId, rom: rom)+ await applyPlayTime(gameId: gameId, client: client, rom: rom)+ await pullSave(gameId: gameId, client: client, romId: resolvedRomId)+ await pullStates(gameId: gameId, client: client, romId: resolvedRomId)+ }++ private func applyCover(gameId: String, client: RommClient, rom: RommRom) async {+ guard let data = await downloadCover(client: client, rom: rom), !data.isEmpty else { return }+ await MainActor.run {+ var didWrite = false+ Game.change { realm in+ guard let game = realm.object(ofType: Game.self, forPrimaryKey: gameId), !game.isDeleted else { return }+ game.gameCover?.deleteAndClean(realm: realm)+ game.gameCover = CreamAsset.create(objectID: game.id, propName: "gameCover", data: data)+ game.hasCoverMatch = true+ game.onlineCoverUrl = nil+ didWrite = true+ }+ if didWrite {+ NotificationCenter.default.post(name: R.NotificationName.GameCoverChange, object: nil)+ }+ }+ }++ private func downloadCover(client: RommClient, rom: RommRom) async -> Data? {+ if let path = rom.preferredCoverPath,+ let request = client.assetDownloadRequest(downloadPath: path),+ let data = try? await client.data(for: request),+ !data.isEmpty {+ return data+ }+ guard let urlCover = rom.url_cover, !urlCover.isEmpty else { return nil }+ if urlCover.hasPrefix("http"), let url = URL(string: urlCover) {+ return try? await client.data(for: URLRequest(url: url))+ }+ if let request = client.assetDownloadRequest(downloadPath: urlCover) {+ return try? await client.data(for: request)+ }+ return nil+ }++ private func applyMetadata(gameId: String, rom: RommRom) async {+ await MainActor.run {+ guard let game = Database.realm.object(ofType: Game.self, forPrimaryKey: gameId), !game.isDeleted else { return }+ var metadata = GameMetadata.getGameMetadata(game: game) ?? GameMetadata()+ if let name = rom.name, !name.isEmpty {+ metadata.displayName = name+ metadata.fullName = name+ }+ if let summary = rom.summary {+ metadata.overview = summary+ }+ if let genres = rom.metadatum?.genres, !genres.isEmpty {+ metadata.genre = genres.joined(separator: ", ")+ }+ if let franchises = rom.metadatum?.franchises, !franchises.isEmpty {+ metadata.franchise = franchises.joined(separator: ", ")+ }+ if let companies = rom.metadatum?.companies, !companies.isEmpty {+ metadata.developer = companies[0]+ metadata.publisher = companies.count > 1 ? companies[companies.count - 1] : companies[0]+ }+ if let timestamp = rom.metadatum?.first_release_date {+ let seconds = timestamp > 10_000_000_000 ? timestamp / 1000 : timestamp+ let date = Date(timeIntervalSince1970: TimeInterval(seconds))+ let calendar = Calendar(identifier: .gregorian)+ metadata.releaseYear = calendar.component(.year, from: date)+ metadata.releaseMonth = calendar.component(.month, from: date)+ }+ if let ratings = rom.metadatum?.age_ratings, let esrp = Self.esrp(from: ratings) {+ metadata.ratingId = esrp.ratingId+ }+ metadata.persist(to: game)+ game.updateExtra(key: ExtraKey.hasQueryMetadata.rawValue, value: true)+ }+ }++ private func applyPlayTime(gameId: String, client: RommClient, rom: RommRom) async {+ let sessions = (try? await client.playSessions(romID: rom.id)) ?? []+ let remoteTotal = Double(sessions.reduce(0) { $0 + $1.duration_ms })+ let lastPlayed = rom.rom_user?.last_played ?? sessions.compactMap(\.end_time).max()+ await MainActor.run {+ Game.change { realm in+ guard let game = realm.object(ofType: Game.self, forPrimaryKey: gameId), !game.isDeleted else { return }+ if remoteTotal > 0 {+ game.totalPlayDuration = remoteTotal+ }+ if let lastPlayed {+ game.latestPlayDate = lastPlayed+ }+ }+ if let game = Database.realm.object(ofType: Game.self, forPrimaryKey: gameId) {+ let watermark = remoteTotal > 0 ? remoteTotal : game.totalPlayDuration+ game.rommPlayDurationPushed = watermark+ }+ }+ }++ private func pullSave(gameId: String, client: RommClient, romId: Int) async {+ let context = await MainActor.run { () -> (url: URL, skip: Bool)? in+ guard let game = Database.realm.object(ofType: Game.self, forPrimaryKey: gameId), !game.isDeleted else { return nil }+ return (game.gameSaveUrl, game.gameType == ._3ds || game.gameType == .psp)+ }+ guard let context, !context.skip else { return }+ let remote = (try? await client.saves(romID: romId))?+ .sorted(by: { ($0.updated_at ?? .distantPast) > ($1.updated_at ?? .distantPast) })+ .first+ guard let remote,+ let request = client.saveContentRequest(saveID: remote.id),+ let data = try? await client.data(for: request) else { return }+ let directory = context.url.deletingLastPathComponent()+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ do {+ try data.write(to: context.url, options: .atomic)+ if let date = remote.updated_at {+ try? FileManager.default.setAttributes([.modificationDate: date], ofItemAtPath: context.url.path)+ }+ SyncManager.upload(localFilePath: context.url.path)+ } catch {+ Log.debug("[RomM] write save failed: \(error)")+ }+ }++ private func pullStates(gameId: String, client: RommClient, romId: Int) async {+ guard let remoteStates = try? await client.states(romID: romId) else { return }+ for remote in remoteStates {+ guard let request = client.assetDownloadRequest(downloadPath: remote.download_path),+ let data = try? await client.data(for: request) else { continue }+ var coverData: Data?+ if let screenshot = remote.screenshot,+ let coverRequest = client.assetDownloadRequest(downloadPath: screenshot.download_path) {+ coverData = try? await client.data(for: coverRequest)+ }+ await upsertLocalState(gameId: gameId,+ remoteName: remote.file_name,+ date: remote.updated_at ?? Date(),+ data: data,+ cover: coverData)+ }+ }++ @MainActor+ private func upsertLocalState(gameId: String, remoteName: String, date: Date, data: Data, cover: Data?) {+ guard let game = Database.realm.object(ofType: Game.self, forPrimaryKey: gameId), !game.isDeleted else { return }+ let key = Self.normalizedKey(remoteName)+ if let existing = game.gameSaveStates.first(where: { Self.normalizedKey($0.name) == key }) {+ Game.change { realm in+ existing.date = date+ existing.stateData?.deleteAndClean(realm: realm)+ existing.stateData = CreamAsset.create(objectID: existing.name, propName: "stateData", data: data)+ if let cover {+ existing.stateCover?.deleteAndClean(realm: realm)+ existing.stateCover = CreamAsset.create(objectID: existing.name, propName: "stateCover", data: cover)+ }+ }+ return+ }+ let preferred = Self.deriveStateName(from: remoteName)+ var stateName = preferred+ if Database.realm.object(ofType: GameSaveState.self, forPrimaryKey: stateName) != nil {+ stateName = "\(gameId)_\(preferred)"+ }+ if Database.realm.object(ofType: GameSaveState.self, forPrimaryKey: stateName) != nil {+ stateName = "\(gameId)_\(Int(Date().timeIntervalSince1970))_\(preferred)"+ }+ Game.change { realm in+ guard let game = realm.object(ofType: Game.self, forPrimaryKey: gameId) else { return }+ let state = GameSaveState()+ state.name = stateName+ state.type = .manualSaveState+ state.date = date+ if let cover {+ state.stateCover = CreamAsset.create(objectID: state.name, propName: "stateCover", data: cover)+ }+ state.stateData = CreamAsset.create(objectID: state.name, propName: "stateData", data: data)+ game.gameSaveStates.append(state)+ }+ }++ // MARK: - Push sidecar++ private func pushSidecar(gameId: String, client: RommClient) async throws {+ let snapshot = try await MainActor.run { () -> PushSnapshot in+ guard let game = Database.realm.object(ofType: Game.self, forPrimaryKey: gameId),+ !game.isDeleted,+ let romId = game.rommRomId else {+ throw RommLibraryError.missingGame+ }+ return PushSnapshot(game: game, romId: romId)+ }+ try await pushCoverAndMetadata(client: client, snapshot: snapshot)+ try await pushPlayTime(client: client, snapshot: snapshot)+ await pushSave(client: client, snapshot: snapshot)+ await pushStates(client: client, snapshot: snapshot)+ }++ private func pushCoverAndMetadata(client: RommClient, snapshot: PushSnapshot) async throws {+ var artwork: (fileName: String, data: Data)?+ if let cover = snapshot.coverData, !cover.isEmpty {+ artwork = (fileName: "cover.jpg", data: cover)+ }+ try await client.updateRom(romID: snapshot.romId,+ name: snapshot.displayName,+ summary: snapshot.overview,+ artwork: artwork)+ }++ private func pushPlayTime(client: RommClient, snapshot: PushSnapshot) async throws {+ let delta = Int(snapshot.totalPlayDuration - snapshot.playDurationPushed)+ if delta > 0 {+ try await client.ingestPlaySession(romID: snapshot.romId, durationMs: delta)+ }+ if snapshot.latestPlayDate != nil {+ try? await client.updateLastPlayed(romID: snapshot.romId)+ }+ await MainActor.run {+ guard let game = Database.realm.object(ofType: Game.self, forPrimaryKey: snapshot.gameId) else { return }+ game.rommPlayDurationPushed = snapshot.totalPlayDuration+ }+ }++ private func pushSave(client: RommClient, snapshot: PushSnapshot) async {+ guard snapshot.supportsBatterySave,+ FileManager.default.fileExists(atPath: snapshot.saveURL.path),+ let data = try? Data(contentsOf: snapshot.saveURL) else { return }+ do {+ try await client.uploadSave(romID: snapshot.romId,+ emulator: nil,+ fileName: snapshot.saveURL.lastPathComponent,+ fileData: data)+ } catch {+ Log.debug("[RomM] upload save failed: \(error)")+ }+ }++ private func pushStates(client: RommClient, snapshot: PushSnapshot) async {+ for state in snapshot.states {+ guard let data = state.data, !data.isEmpty else { continue }+ var screenshot: (fileName: String, data: Data)?+ if let cover = state.cover, !cover.isEmpty {+ screenshot = (fileName: "\(state.name).jpg", data: cover)+ }+ let remoteName = state.name.hasSuffix(Self.stateFileSuffix)+ ? state.name+ : "\(state.name)\(Self.stateFileSuffix)"+ do {+ _ = try await client.uploadState(romID: snapshot.romId,+ emulator: nil,+ fileName: remoteName,+ fileData: data,+ screenshot: screenshot)+ } catch {+ Log.debug("[RomM] upload state failed (\(state.name)): \(error)")+ }+ }+ }++ // MARK: - Mapping++ private static func esrp(from ratings: [String]) -> ESRP? {+ let joined = ratings.joined(separator: " ").lowercased()+ if joined.contains("adults only") || joined.contains("esrb: ao") || joined.contains("esrb ao") { return .AO }+ if joined.contains("everyone 10") || joined.contains("e10") { return .E10 }+ if joined.contains("early childhood") || joined.contains("esrb: ec") { return .EC }+ if joined.contains("kids to adults") || joined.contains("k-a") || joined.contains("k–a") { return .K_A }+ if joined.contains("rating pending") && joined.contains("17") { return .RP17 }+ if joined.contains("rating pending") || joined.contains("esrb: rp") { return .RP }+ if joined.contains("mature") || joined.contains("esrb: m") { return .M }+ if joined.contains("teen") || joined.contains("esrb: t") { return .T }+ if joined.contains("everyone") || joined.contains("esrb: e") { return .E }+ return nil+ }++ private static func normalizedKey(_ raw: String) -> String {+ var value = raw+ if value.hasSuffix(stateFileSuffix) {+ value = String(value.dropLast(stateFileSuffix.count))+ }+ return value.lowercased().filter { $0.isLetter || $0.isNumber }+ }++ private static func deriveStateName(from fileName: String) -> String {+ if fileName.hasSuffix(stateFileSuffix) {+ return String(fileName.dropLast(stateFileSuffix.count))+ }+ return fileName+ }++ // MARK: - Snapshots++ private struct ServiceSnapshot {+ let id: String+ let scheme: String+ let host: String+ let port: Int?+ let user: String?+ let password: String?+ let path: String?++ init(service: ImportService) {+ id = "\(service.id)"+ scheme = service.scheme ?? "http"+ host = service.host ?? ""+ port = service.port+ user = service.user+ password = service.password+ path = service.path+ }++ func makeClient() -> RommClient? {+ RommClient(scheme: scheme, host: host, port: port, user: user, password: password, path: path)+ }+ }++ private struct StatePushSnapshot {+ let name: String+ let data: Data?+ let cover: Data?+ }++ private struct PushSnapshot {+ let gameId: String+ let romId: Int+ let displayName: String+ let overview: String?+ let coverData: Data?+ let saveURL: URL+ let supportsBatterySave: Bool+ let totalPlayDuration: Double+ let playDurationPushed: Double+ let latestPlayDate: Date?+ let states: [StatePushSnapshot]++ init(game: Game, romId: Int) {+ gameId = game.id+ self.romId = romId+ displayName = game.displayName+ overview = GameMetadata.getGameMetadata(game: game)?.overview+ coverData = game.gameCover?.storedData()+ saveURL = game.gameSaveUrl+ supportsBatterySave = game.gameType != ._3ds && game.gameType != .psp+ totalPlayDuration = game.totalPlayDuration+ playDurationPushed = game.rommPlayDurationPushed+ latestPlayDate = game.latestPlayDate+ states = game.gameSaveStates.map {+ StatePushSnapshot(name: $0.name,+ data: $0.stateData?.storedData(),+ cover: $0.stateCover?.storedData())+ }+ }+ }++ private enum RommLibraryError: Error {+ case missingGame+ }+}