UnifiedSearchCoordinator.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 response: SlskdSearchResponse
  36. let score: Int
  37. var id: String { response.id }
  38. /// Best audio format in this source.
  39. var bestFormat: String {
  40. let audioFiles = response.files.filter(\.isAudioFile)
  41. let extensions = audioFiles.compactMap(\.fileExtension)
  42. // Priority order
  43. for fmt in ["flac", "wav", "aiff", "aif", "ape", "wv", "m4a", "ogg", "aac", "mp3"] {
  44. if extensions.contains(fmt) { return fmt.uppercased() }
  45. }
  46. return extensions.first?.uppercased() ?? "?"
  47. }
  48. /// Number of audio files.
  49. var audioFileCount: Int {
  50. response.files.filter(\.isAudioFile).count
  51. }
  52. /// Audio files in this source.
  53. var audioFiles: [SlskdFile] {
  54. response.files.filter(\.isAudioFile)
  55. }
  56. /// Total size of audio files in bytes.
  57. var totalSize: Int64 {
  58. audioFiles.reduce(0) { $0 + $1.size }
  59. }
  60. /// Human-readable total size (e.g., "847 MB").
  61. var formattedTotalSize: String {
  62. ByteCountFormatter.string(fromByteCount: totalSize, countStyle: .file)
  63. }
  64. /// Format + bitrate display (e.g., "FLAC", "MP3 320k").
  65. var formatDisplay: String {
  66. let fmt = bestFormat
  67. if fmt == "MP3" {
  68. let maxBitrate = audioFiles.compactMap(\.bitRate).max()
  69. if let br = maxBitrate, br > 0 {
  70. return "MP3 \(br)k"
  71. }
  72. }
  73. return fmt
  74. }
  75. /// Score color: green (excellent), yellow (acceptable), red (poor).
  76. var scoreGrade: ScoreGrade {
  77. if score >= 120 { return .excellent }
  78. if score >= 80 { return .good }
  79. return .poor
  80. }
  81. enum ScoreGrade {
  82. case excellent, good, poor
  83. }
  84. }
  85. // MARK: - Coordinator
  86. /// Orchestrates parallel cloud + Soulseek search.
  87. /// NOT a singleton — create one per search session.
  88. @MainActor
  89. @Observable
  90. final class UnifiedSearchCoordinator {
  91. // MARK: - Published State
  92. private(set) var phase: UnifiedSearchPhase = .idle
  93. private(set) var cloudResults: [ChadAlbum] = []
  94. private(set) var soulseekSources: [ScoredSoulseekSource] = []
  95. private(set) var downloadPhase: SourceDownloadPhase = .idle
  96. // MARK: - Private
  97. private let chadMusic = ChadMusicAPIClient.shared
  98. private let slskd = SlskdAPIClient.shared
  99. private nonisolated(unsafe) var searchTask: Task<Void, Never>?
  100. private nonisolated(unsafe) var downloadTask: Task<Void, Never>?
  101. private nonisolated(unsafe) var activeSearchId: String?
  102. private let searchPollInterval: TimeInterval = 2
  103. private let searchTimeout: TimeInterval = 30
  104. private let downloadPollInterval: TimeInterval = 3
  105. private let downloadTimeout: TimeInterval = 600
  106. private let importTimeout: TimeInterval = 300
  107. /// Quality threshold for display. Sources below this are shown grayed out.
  108. private var qualityThreshold: Int {
  109. let stored = UserDefaults.standard.integer(forKey: "slskd.qualityThreshold")
  110. return stored > 0 ? stored : 80
  111. }
  112. deinit {
  113. searchTask?.cancel()
  114. downloadTask?.cancel()
  115. // Best-effort cleanup
  116. if let searchId = activeSearchId {
  117. let client = SlskdAPIClient.shared
  118. Task { try? await client.deleteSearch(id: searchId) }
  119. }
  120. }
  121. // MARK: - Search
  122. /// Cloud-first search. If ChadMusic has no results and Soulseek is configured,
  123. /// automatically searches Soulseek and returns scored sources for the user to pick.
  124. func search(query: String) {
  125. cancel()
  126. searchTask = Task { [weak self] in
  127. guard let self else { return }
  128. do {
  129. try await self.runSearch(query: query)
  130. } catch is CancellationError {
  131. // Cancelled — leave state as-is
  132. } catch {
  133. self.phase = .error(error.localizedDescription)
  134. }
  135. }
  136. }
  137. /// Cancel any active search or download.
  138. func cancel() {
  139. searchTask?.cancel()
  140. searchTask = nil
  141. downloadTask?.cancel()
  142. downloadTask = nil
  143. if let searchId = activeSearchId {
  144. activeSearchId = nil
  145. Task { try? await slskd.deleteSearch(id: searchId) }
  146. }
  147. cloudResults = []
  148. soulseekSources = []
  149. phase = .idle
  150. downloadPhase = .idle
  151. }
  152. /// Download a specific Soulseek source picked by the user.
  153. func downloadSource(
  154. _ source: SlskdSearchResponse,
  155. artist: String,
  156. albumName: String
  157. ) {
  158. downloadTask?.cancel()
  159. downloadPhase = .downloading(progress: 0)
  160. downloadTask = Task { [weak self] in
  161. guard let self else { return }
  162. do {
  163. try await self.runDownloadAndImport(
  164. source: source,
  165. artist: artist,
  166. albumName: albumName
  167. )
  168. } catch is CancellationError {
  169. self.downloadPhase = .idle
  170. } catch {
  171. self.downloadPhase = .failed(error.localizedDescription)
  172. }
  173. }
  174. }
  175. /// Dismiss a completed/failed download state.
  176. func dismissDownload() {
  177. guard !downloadPhase.isActive else { return }
  178. downloadPhase = .idle
  179. }
  180. // MARK: - Private: Search Pipeline
  181. private func runSearch(query: String) async throws {
  182. let lowerQuery = query.lowercased()
  183. // Step 1: Search ChadMusic (client-side filter)
  184. phase = .searchingCloud
  185. let allAlbums = try await chadMusic.fetchAlbums()
  186. try Task.checkCancellation()
  187. cloudResults = allAlbums.filter { album in
  188. album.title.lowercased().contains(lowerQuery) ||
  189. (album.artist?.lowercased().contains(lowerQuery) ?? false)
  190. }
  191. // Step 2: Always search Soulseek in parallel (not just as fallback)
  192. guard slskd.isConfigured else {
  193. phase = .done
  194. return
  195. }
  196. try Task.checkCancellation()
  197. phase = .searchingSoulseek
  198. let searchId = try await slskd.startSearch(query: query)
  199. activeSearchId = searchId
  200. let responses = try await pollSearch(id: searchId)
  201. activeSearchId = nil
  202. // Score and sort responses
  203. soulseekSources = responses
  204. .map { ScoredSoulseekSource(response: $0, score: $0.qualityScore(expectedTrackCount: nil)) }
  205. .filter { $0.score > 0 }
  206. .sorted { $0.score > $1.score }
  207. try Task.checkCancellation()
  208. phase = .done
  209. }
  210. private func pollSearch(id: String) async throws -> [SlskdSearchResponse] {
  211. let deadline = Date().addingTimeInterval(searchTimeout)
  212. while Date() < deadline {
  213. try Task.checkCancellation()
  214. let search = try await slskd.getSearch(id: id)
  215. if search.isComplete {
  216. return search.responses ?? []
  217. }
  218. try await Task.sleep(for: .seconds(searchPollInterval))
  219. }
  220. // Grab whatever we have
  221. let finalSearch = try await slskd.getSearch(id: id)
  222. return finalSearch.responses ?? []
  223. }
  224. // MARK: - Private: Download + Import Pipeline
  225. private func runDownloadAndImport(
  226. source: SlskdSearchResponse,
  227. artist: String,
  228. albumName: String
  229. ) async throws {
  230. let audioFiles = source.files.filter(\.isAudioFile)
  231. guard !audioFiles.isEmpty else {
  232. throw SlskdError.noResults
  233. }
  234. // Step 1: Enqueue downloads
  235. downloadPhase = .downloading(progress: 0)
  236. let enqueuedFilenames = Set(audioFiles.map(\.filename))
  237. try await slskd.enqueueDownloads(username: source.username, files: audioFiles)
  238. // Step 2: Poll downloads
  239. let deadline = Date().addingTimeInterval(downloadTimeout)
  240. let expectedCount = audioFiles.count
  241. while Date() < deadline {
  242. try Task.checkCancellation()
  243. let groups = try await slskd.getDownloads()
  244. if let group = groups.first(where: { $0.username == source.username }) {
  245. let allFiles = group.directories?.flatMap { $0.files ?? [] } ?? []
  246. let ourFiles = allFiles.filter { enqueuedFilenames.contains($0.filename) }
  247. let completed = ourFiles.filter(\.isComplete).count
  248. let failed = ourFiles.filter(\.isFailed).count
  249. let total = max(expectedCount, ourFiles.count)
  250. let progress = total > 0 ? Double(completed + failed) / Double(total) : 0
  251. downloadPhase = .downloading(progress: min(progress, 1.0))
  252. if completed + failed >= expectedCount {
  253. let failThreshold = (expectedCount + 1) / 2
  254. if failed >= failThreshold {
  255. throw SlskdError.downloadFailed("\(failed)/\(expectedCount) files failed")
  256. }
  257. break
  258. }
  259. }
  260. try await Task.sleep(for: .seconds(downloadPollInterval))
  261. }
  262. // Step 3: Trigger ChadMusic import
  263. try Task.checkCancellation()
  264. downloadPhase = .importing
  265. try await chadMusic.triggerRescan()
  266. // Poll for album appearance
  267. let importDeadline = Date().addingTimeInterval(importTimeout)
  268. let searchLower = albumName.lowercased()
  269. while Date() < importDeadline {
  270. try Task.checkCancellation()
  271. try await Task.sleep(for: .seconds(10))
  272. do {
  273. let albums = try await chadMusic.fetchAlbums(filteredBy: "artist", value: artist)
  274. if albums.contains(where: { $0.title.lowercased() == searchLower }) {
  275. downloadPhase = .complete(albumName: albumName)
  276. return
  277. }
  278. } catch {
  279. continue
  280. }
  281. }
  282. // Files are downloaded but import timed out
  283. throw SlskdError.importTimeout
  284. }
  285. }