UnifiedSearchCoordinator.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import Foundation
  2. // MARK: - Search Phase
  3. enum UnifiedSearchPhase: Equatable {
  4. case idle
  5. case searchingCloud
  6. case searchingSoulseek
  7. case done
  8. case error(String)
  9. }
  10. // MARK: - Download Phase
  11. enum SourceDownloadPhase: Equatable {
  12. case idle
  13. case downloading(progress: Double)
  14. case importing
  15. case complete(albumName: String)
  16. case failed(String)
  17. var isActive: Bool {
  18. switch self {
  19. case .idle, .complete, .failed: false
  20. default: true
  21. }
  22. }
  23. var statusText: String {
  24. switch self {
  25. case .idle: "Ready"
  26. case .downloading(let p): "Downloading... \(Int(p * 100))%"
  27. case .importing: "Importing to ChadMusic..."
  28. case .complete(let name): "\(name) ready"
  29. case .failed(let msg): "Failed: \(msg)"
  30. }
  31. }
  32. }
  33. // MARK: - Scored Source
  34. struct ScoredSoulseekSource: Identifiable {
  35. let albumSource: SlskdAlbumSource
  36. let score: Int
  37. var id: String { albumSource.id }
  38. /// Best audio format in this source.
  39. var bestFormat: String {
  40. let extensions = albumSource.audioFiles.compactMap(\.fileExtension)
  41. for fmt in ["flac", "wav", "aiff", "aif", "ape", "wv", "m4a", "ogg", "aac", "mp3"] {
  42. if extensions.contains(fmt) { return fmt.uppercased() }
  43. }
  44. return extensions.first?.uppercased() ?? "?"
  45. }
  46. var audioFileCount: Int { albumSource.audioFiles.count }
  47. var audioFiles: [SlskdFile] { albumSource.audioFiles }
  48. var totalSize: Int64 { audioFiles.reduce(0) { $0 + $1.size } }
  49. var formattedTotalSize: String {
  50. ByteCountFormatter.string(fromByteCount: totalSize, countStyle: .file)
  51. }
  52. var formatDisplay: String {
  53. let fmt = bestFormat
  54. if fmt == "MP3" {
  55. let maxBitrate = audioFiles.compactMap(\.bitRate).max()
  56. if let br = maxBitrate, br > 0 {
  57. return "MP3 \(br)k"
  58. }
  59. }
  60. // Lossless: show bit depth / sample rate if available (e.g. "FLAC 16/48", "FLAC 24/96")
  61. if ["FLAC", "WAV", "AIFF", "AIF", "APE", "WV"].contains(fmt) {
  62. let depths = audioFiles.compactMap(\.bitDepth)
  63. let rates = audioFiles.compactMap(\.sampleRate)
  64. if let depth = depths.max(), let rate = rates.max(), depth > 0, rate > 0 {
  65. let rateKHz: String
  66. if rate >= 1000 {
  67. let kHz = Double(rate) / 1000.0
  68. rateKHz = kHz.truncatingRemainder(dividingBy: 1) == 0
  69. ? "\(Int(kHz))"
  70. : String(format: "%.1f", kHz)
  71. } else {
  72. rateKHz = "\(rate)"
  73. }
  74. return "\(fmt) \(depth)/\(rateKHz)"
  75. }
  76. }
  77. return fmt
  78. }
  79. var scoreGrade: ScoreGrade {
  80. if score >= 120 { return .excellent }
  81. if score >= 80 { return .good }
  82. return .poor
  83. }
  84. /// Album name from directory path.
  85. var albumName: String { albumSource.albumName }
  86. /// Artist guess from directory path.
  87. var artistGuess: String? { albumSource.artistGuess }
  88. var username: String { albumSource.username }
  89. var dragRepresentation: String {
  90. "\(username) — \(formatDisplay) — \(audioFileCount) files — \(formattedTotalSize)"
  91. }
  92. enum ScoreGrade {
  93. case excellent, good, poor
  94. }
  95. }
  96. // MARK: - Coordinator
  97. /// Orchestrates parallel cloud + Soulseek search.
  98. /// NOT a singleton — create one per search session.
  99. @MainActor
  100. @Observable
  101. final class UnifiedSearchCoordinator {
  102. // MARK: - Published State
  103. private(set) var phase: UnifiedSearchPhase = .idle
  104. private(set) var cloudResults: [ChadAlbum] = []
  105. private(set) var soulseekSources: [ScoredSoulseekSource] = []
  106. private(set) var downloadPhase: SourceDownloadPhase = .idle
  107. /// Per-file transfer state during download, keyed by filename.
  108. private(set) var activeTransfers: [String: SlskdTransfer] = [:]
  109. // MARK: - Private
  110. private let chadMusic = ChadMusicAPIClient.shared
  111. private let slskd = SlskdAPIClient.shared
  112. private var searchTask: Task<Void, Never>?
  113. private var downloadTask: Task<Void, Never>?
  114. private var activeSearchId: String?
  115. private let searchPollInterval: TimeInterval = 2
  116. private let searchTimeout: TimeInterval = 30
  117. private let downloadPollInterval: TimeInterval = 3
  118. private let downloadTimeout: TimeInterval = 600
  119. private let importTimeout: TimeInterval = 300
  120. /// Quality threshold for display. Sources below this are shown grayed out.
  121. private var qualityThreshold: Int {
  122. let stored = UserDefaults.standard.integer(forKey: "slskd.qualityThreshold")
  123. return stored > 0 ? stored : 80
  124. }
  125. // MARK: - Search
  126. /// Cloud-first search. If ChadMusic has no results and Soulseek is configured,
  127. /// automatically searches Soulseek and returns scored sources for the user to pick.
  128. func search(query: String) {
  129. cancelSearch()
  130. searchTask = Task { [weak self] in
  131. guard let self else { return }
  132. do {
  133. try await self.runSearch(query: query)
  134. } catch is CancellationError {
  135. // Cancelled — leave state as-is
  136. } catch {
  137. self.phase = .error(error.localizedDescription)
  138. }
  139. }
  140. }
  141. /// Cancel any active search or download.
  142. func cancel() {
  143. cancelSearch()
  144. cancelDownload()
  145. }
  146. /// Cancel only the active search, preserving download state.
  147. func cancelSearch() {
  148. searchTask?.cancel()
  149. searchTask = nil
  150. if let searchId = activeSearchId {
  151. activeSearchId = nil
  152. Task { try? await slskd.deleteSearch(id: searchId) }
  153. }
  154. cloudResults = []
  155. soulseekSources = []
  156. phase = .idle
  157. }
  158. /// Cancel only the active download, preserving search results.
  159. func cancelDownload() {
  160. downloadTask?.cancel()
  161. downloadTask = nil
  162. downloadPhase = .idle
  163. activeTransfers = [:]
  164. }
  165. /// Download a specific Soulseek album source picked by the user.
  166. func downloadSource(
  167. _ source: SlskdAlbumSource,
  168. artist: String,
  169. albumName: String
  170. ) {
  171. downloadTask?.cancel()
  172. downloadPhase = .downloading(progress: 0)
  173. downloadTask = Task { [weak self] in
  174. guard let self else { return }
  175. do {
  176. try await self.runDownloadAndImport(
  177. source: source,
  178. artist: artist,
  179. albumName: albumName
  180. )
  181. } catch is CancellationError {
  182. self.downloadPhase = .idle
  183. } catch {
  184. self.downloadPhase = .failed(error.localizedDescription)
  185. }
  186. }
  187. }
  188. /// Dismiss a completed/failed download state.
  189. func dismissDownload() {
  190. guard !downloadPhase.isActive else { return }
  191. downloadPhase = .idle
  192. }
  193. // MARK: - Private: Search Pipeline
  194. private func runSearch(query: String) async throws {
  195. let lowerQuery = query.lowercased()
  196. // Step 1: Search ChadMusic (client-side filter)
  197. phase = .searchingCloud
  198. let allAlbums = try await chadMusic.fetchAlbums()
  199. try Task.checkCancellation()
  200. cloudResults = allAlbums.filter { album in
  201. album.title.lowercased().contains(lowerQuery) ||
  202. (album.artist?.lowercased().contains(lowerQuery) ?? false)
  203. }
  204. // Step 2: Always search Soulseek in parallel (not just as fallback)
  205. guard slskd.isConfigured else {
  206. phase = .done
  207. return
  208. }
  209. try Task.checkCancellation()
  210. phase = .searchingSoulseek
  211. let searchId = try await slskd.startSearch(query: query)
  212. activeSearchId = searchId
  213. let responses = try await pollSearch(id: searchId)
  214. activeSearchId = nil
  215. // Score and sort by directory (album-level grouping)
  216. soulseekSources = responses
  217. .flatMap { $0.groupedByDirectory() }
  218. .map { ScoredSoulseekSource(albumSource: $0, score: $0.qualityScore(expectedTrackCount: nil)) }
  219. .filter { $0.score > 0 }
  220. .sorted { $0.score > $1.score }
  221. try Task.checkCancellation()
  222. phase = .done
  223. }
  224. private func pollSearch(id: String) async throws -> [SlskdSearchResponse] {
  225. let deadline = Date().addingTimeInterval(searchTimeout)
  226. while Date() < deadline {
  227. try Task.checkCancellation()
  228. let search = try await slskd.getSearch(id: id)
  229. if search.isComplete {
  230. return search.responses ?? []
  231. }
  232. try await Task.sleep(for: .seconds(searchPollInterval))
  233. }
  234. // Grab whatever we have
  235. let finalSearch = try await slskd.getSearch(id: id)
  236. return finalSearch.responses ?? []
  237. }
  238. // MARK: - Private: Download + Import Pipeline
  239. private func runDownloadAndImport(
  240. source: SlskdAlbumSource,
  241. artist: String,
  242. albumName: String
  243. ) async throws {
  244. let audioFiles = source.audioFiles
  245. guard !audioFiles.isEmpty else {
  246. throw SlskdError.noResults
  247. }
  248. // Step 1: Enqueue downloads
  249. downloadPhase = .downloading(progress: 0)
  250. let enqueuedFilenames = Set(audioFiles.map(\.filename))
  251. try await slskd.enqueueDownloads(username: source.username, files: audioFiles)
  252. // Step 2: Poll downloads
  253. let deadline = Date().addingTimeInterval(downloadTimeout)
  254. let expectedCount = audioFiles.count
  255. while Date() < deadline {
  256. try Task.checkCancellation()
  257. let groups = try await slskd.getDownloads()
  258. if let group = groups.first(where: { $0.username == source.username }) {
  259. let allFiles = group.directories?.flatMap { $0.files ?? [] } ?? []
  260. let ourFiles = allFiles.filter { enqueuedFilenames.contains($0.filename) }
  261. // Update per-file transfer state
  262. var transfers: [String: SlskdTransfer] = [:]
  263. for file in ourFiles {
  264. transfers[file.filename] = file
  265. }
  266. activeTransfers = transfers
  267. let completed = ourFiles.filter(\.isComplete).count
  268. let failed = ourFiles.filter(\.isFailed).count
  269. let total = max(expectedCount, ourFiles.count)
  270. let progress = total > 0 ? Double(completed + failed) / Double(total) : 0
  271. downloadPhase = .downloading(progress: min(progress, 1.0))
  272. if completed + failed >= expectedCount {
  273. let failThreshold = (expectedCount + 1) / 2
  274. if failed >= failThreshold {
  275. throw SlskdError.downloadFailed("\(failed)/\(expectedCount) files failed")
  276. }
  277. break
  278. }
  279. }
  280. try await Task.sleep(for: .seconds(downloadPollInterval))
  281. }
  282. // Step 3: Trigger ChadMusic import (if auto-import enabled)
  283. try Task.checkCancellation()
  284. let autoImport = UserDefaults.standard.bool(forKey: "slskd.autoImport")
  285. // Default to true when key hasn't been set
  286. let shouldImport = UserDefaults.standard.object(forKey: "slskd.autoImport") == nil ? true : autoImport
  287. guard shouldImport else {
  288. downloadPhase = .complete(albumName: albumName)
  289. return
  290. }
  291. downloadPhase = .importing
  292. try await chadMusic.triggerRescan()
  293. // Poll for album appearance
  294. let importDeadline = Date().addingTimeInterval(importTimeout)
  295. let searchLower = albumName.lowercased()
  296. while Date() < importDeadline {
  297. try Task.checkCancellation()
  298. try await Task.sleep(for: .seconds(10))
  299. do {
  300. let albums = try await chadMusic.fetchAlbums(filteredBy: "artist", value: artist)
  301. if albums.contains(where: { $0.title.lowercased() == searchLower }) {
  302. downloadPhase = .complete(albumName: albumName)
  303. return
  304. }
  305. } catch {
  306. continue
  307. }
  308. }
  309. // Files are downloaded but import timed out
  310. throw SlskdError.importTimeout
  311. }
  312. }