UnifiedSearchCoordinator.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 cloud-first, Soulseek-fallback 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. // If we found cloud results, we're done
  192. if !cloudResults.isEmpty {
  193. phase = .done
  194. return
  195. }
  196. // Step 2: No cloud results — try Soulseek if configured
  197. guard slskd.isConfigured else {
  198. phase = .done
  199. return
  200. }
  201. try Task.checkCancellation()
  202. phase = .searchingSoulseek
  203. let searchId = try await slskd.startSearch(query: query)
  204. activeSearchId = searchId
  205. let responses = try await pollSearch(id: searchId)
  206. activeSearchId = nil
  207. // Score and sort responses
  208. soulseekSources = responses
  209. .map { ScoredSoulseekSource(response: $0, score: $0.qualityScore(expectedTrackCount: nil)) }
  210. .filter { $0.score > 0 }
  211. .sorted { $0.score > $1.score }
  212. try Task.checkCancellation()
  213. phase = .done
  214. }
  215. private func pollSearch(id: String) async throws -> [SlskdSearchResponse] {
  216. let deadline = Date().addingTimeInterval(searchTimeout)
  217. while Date() < deadline {
  218. try Task.checkCancellation()
  219. let search = try await slskd.getSearch(id: id)
  220. if search.isComplete {
  221. return search.responses ?? []
  222. }
  223. try await Task.sleep(for: .seconds(searchPollInterval))
  224. }
  225. // Grab whatever we have
  226. let finalSearch = try await slskd.getSearch(id: id)
  227. return finalSearch.responses ?? []
  228. }
  229. // MARK: - Private: Download + Import Pipeline
  230. private func runDownloadAndImport(
  231. source: SlskdSearchResponse,
  232. artist: String,
  233. albumName: String
  234. ) async throws {
  235. let audioFiles = source.files.filter(\.isAudioFile)
  236. guard !audioFiles.isEmpty else {
  237. throw SlskdError.noResults
  238. }
  239. // Step 1: Enqueue downloads
  240. downloadPhase = .downloading(progress: 0)
  241. let enqueuedFilenames = Set(audioFiles.map(\.filename))
  242. try await slskd.enqueueDownloads(username: source.username, files: audioFiles)
  243. // Step 2: Poll downloads
  244. let deadline = Date().addingTimeInterval(downloadTimeout)
  245. let expectedCount = audioFiles.count
  246. while Date() < deadline {
  247. try Task.checkCancellation()
  248. let groups = try await slskd.getDownloads()
  249. if let group = groups.first(where: { $0.username == source.username }) {
  250. let allFiles = group.directories?.flatMap { $0.files ?? [] } ?? []
  251. let ourFiles = allFiles.filter { enqueuedFilenames.contains($0.filename) }
  252. let completed = ourFiles.filter(\.isComplete).count
  253. let failed = ourFiles.filter(\.isFailed).count
  254. let total = max(expectedCount, ourFiles.count)
  255. let progress = total > 0 ? Double(completed + failed) / Double(total) : 0
  256. downloadPhase = .downloading(progress: min(progress, 1.0))
  257. if completed + failed >= expectedCount {
  258. let failThreshold = (expectedCount + 1) / 2
  259. if failed >= failThreshold {
  260. throw SlskdError.downloadFailed("\(failed)/\(expectedCount) files failed")
  261. }
  262. break
  263. }
  264. }
  265. try await Task.sleep(for: .seconds(downloadPollInterval))
  266. }
  267. // Step 3: Trigger ChadMusic import
  268. try Task.checkCancellation()
  269. downloadPhase = .importing
  270. try await chadMusic.triggerRescan()
  271. // Poll for album appearance
  272. let importDeadline = Date().addingTimeInterval(importTimeout)
  273. let searchLower = albumName.lowercased()
  274. while Date() < importDeadline {
  275. try Task.checkCancellation()
  276. try await Task.sleep(for: .seconds(10))
  277. do {
  278. let albums = try await chadMusic.fetchAlbums(filteredBy: "artist", value: artist)
  279. if albums.contains(where: { $0.title.lowercased() == searchLower }) {
  280. downloadPhase = .complete(albumName: albumName)
  281. return
  282. }
  283. } catch {
  284. continue
  285. }
  286. }
  287. // Files are downloaded but import timed out
  288. throw SlskdError.importTimeout
  289. }
  290. }