Branchwell

PulseCanvas / app / Sources / PulseCanvas / RadioLibrary.swift

1import AVFoundation
2import CryptoKit
3import Foundation
4import Combine
5
6struct RadioStation: Codable, Identifiable, Sendable {
7 let id: String
8 let title: String
9 let description: String
10 let catalog: String
11
12 func resolvedURL(relativeTo directoryURL: URL) throws -> URL {
13 guard let url = URL(string: catalog, relativeTo: directoryURL)?.absoluteURL else { throw RadioError.invalidCatalog }
14 if directoryURL.isFileURL {
15 guard url.isFileURL, url.resolvingSymlinksInPath().path.hasPrefix(directoryURL.deletingLastPathComponent().resolvingSymlinksInPath().path + "/") else { throw RadioError.invalidCatalog }
16 } else {
17 guard url.scheme == "https", url.host != nil, url.user == nil, url.password == nil else { throw RadioError.invalidCatalog }
18 }
19 return url
20 }
21}
22
23struct RadioStationDirectory: Codable, Sendable {
24 let version: Int
25 let stations: [RadioStation]
26
27 static func decode(_ data: Data, from url: URL) throws -> Self {
28 guard data.count <= 2_000_000 else { throw RadioError.invalidCatalog }
29 let directory = try JSONDecoder().decode(Self.self, from: data)
30 guard directory.version == 1, (1...100).contains(directory.stations.count),
31 Set(directory.stations.map(\.id)).count == directory.stations.count else { throw RadioError.invalidCatalog }
32 for station in directory.stations {
33 guard !station.id.isEmpty, station.id.count <= 80, !station.title.isEmpty else { throw RadioError.invalidCatalog }
34 _ = try station.resolvedURL(relativeTo: url)
35 }
36 return directory
37 }
38}
39
40struct RadioTrack: Codable, Identifiable, Sendable, Equatable {
41 let id: String
42 let title: String
43 let genre: String
44 let duration: Double
45 let audio: String
46 let sha256: String
47 let byteCount: Int
48
49 func resolvedURL(relativeTo catalogURL: URL) throws -> URL {
50 guard let url = URL(string: audio, relativeTo: catalogURL)?.absoluteURL else { throw RadioError.invalidCatalog }
51 if catalogURL.isFileURL {
52 let directory = catalogURL.deletingLastPathComponent().resolvingSymlinksInPath().path + "/"
53 guard url.isFileURL, url.resolvingSymlinksInPath().path.hasPrefix(directory) else { throw RadioError.invalidCatalog }
54 } else {
55 guard url.scheme == "https", url.host != nil, url.user == nil, url.password == nil else { throw RadioError.invalidCatalog }
56 }
57 return url
58 }
59}
60
61struct RadioCatalog: Codable, Sendable {
62 let version: Int
63 let title: String
64 let tracks: [RadioTrack]
65
66 static func decode(_ data: Data, from url: URL) throws -> RadioCatalog {
67 guard data.count <= 2_000_000 else { throw RadioError.invalidCatalog }
68 let catalog = try JSONDecoder().decode(Self.self, from: data)
69 guard catalog.version == 1, !catalog.title.isEmpty,
70 catalog.tracks.count <= 500, Set(catalog.tracks.map(\.id)).count == catalog.tracks.count else { throw RadioError.invalidCatalog }
71 for track in catalog.tracks {
72 guard UUID(uuidString: track.id) != nil, !track.title.isEmpty,
73 track.duration.isFinite, track.duration > 0, track.duration <= 7200,
74 (1...100_000_000).contains(track.byteCount), track.sha256.count == 64,
75 track.sha256.allSatisfy({ $0.isHexDigit && $0.isASCII }) else { throw RadioError.invalidCatalog }
76 _ = try track.resolvedURL(relativeTo: url)
77 }
78 return catalog
79 }
80}
81
82/// Keep enough source information to replay a favorite after changing stations
83/// or relaunching. Song identities are independent of visualizer favorites.
84struct FavoriteRadioSong: Codable, Identifiable, Sendable, Equatable {
85 let track: RadioTrack
86 let sourceURL: URL
87 let catalogURL: URL
88 let stationID: String
89 let folderBookmark: Data?
90 var id: String { track.id }
91
92 var isValid: Bool {
93 guard sourceURL.isFileURL || (sourceURL.scheme == "https" && sourceURL.host != nil && sourceURL.user == nil && sourceURL.password == nil),
94 sourceURL.isFileURL == catalogURL.isFileURL,
95 let data = try? JSONEncoder().encode(RadioCatalog(version: 1, title: "Favorite", tracks: [track])) else { return false }
96 return (try? RadioCatalog.decode(data, from: catalogURL)) != nil
97 }
98}
99
100enum RadioError: LocalizedError {
101 case invalidCatalog, download, integrity, allUnavailable
102 var errorDescription: String? {
103 switch self {
104 case .invalidCatalog: return String(localized: "This radio catalog is invalid. Choose a version 1 catalog with HTTPS audio URLs.")
105 case .download: return String(localized: "The radio library could not be downloaded. Check your connection and catalog URL.")
106 case .integrity: return String(localized: "A radio track did not match the catalog. Refresh the library and try again.")
107 case .allUnavailable: return String(localized: "None of the radio tracks could be played. Check the library and try again.")
108 }
109 }
110}
111
112/// Content-addressed files remain available offline and never contain R2 credentials.
113actor RadioLibrary {
114 private let directory: URL
115 init(directory: URL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
116 .appendingPathComponent("PulseCanvas/Radio/Audio", isDirectory: true)) { self.directory = directory }
117
118 /// A private Radio-only copy: no server catalog changes, cloud uploads, or Studio imports.
119 func importMusicFolder(_ folder: URL, into root: URL = PersonalRadioMusic.directory) async throws -> (url: URL, skipped: Int) {
120 let lease = SecurityScopedAccess(url: folder)
121 defer { withExtendedLifetime(lease) {} }
122 let fm = FileManager.default
123 let destination = root.appendingPathComponent(UUID().uuidString, isDirectory: true)
124 try fm.createDirectory(at: destination, withIntermediateDirectories: true)
125 var committed = false
126 defer { if !committed { try? fm.removeItem(at: destination) } }
127 guard let enumerator = fm.enumerator(at: folder, includingPropertiesForKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey],
128 options: [.skipsHiddenFiles, .skipsPackageDescendants]) else {
129 throw PersonalRadioMusic.FolderError.unreadable
130 }
131 var candidates: [URL] = []
132 let extensions: Set<String> = ["mp3", "m4a", "aac", "wav", "aif", "aiff", "caf", "flac", "mp4", "alac"]
133 for case let file as URL in enumerator {
134 try Task.checkCancellation()
135 let values = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
136 if values.isSymbolicLink == true { enumerator.skipDescendants(); continue }
137 guard values.isRegularFile == true, extensions.contains(file.pathExtension.lowercased()) else { continue }
138 candidates.append(file)
139 guard candidates.count <= 500 else { throw PersonalRadioMusic.FolderError.tooMany }
140 }
141 var tracks: [RadioTrack] = []
142 var skipped = 0
143 for file in candidates.sorted(by: { $0.path.localizedStandardCompare($1.path) == .orderedAscending }) {
144 try Task.checkCancellation()
145 let id = UUID().uuidString
146 let copy = destination.appendingPathComponent(id + "." + file.pathExtension.lowercased())
147 do {
148 let size = try file.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
149 guard (1...100_000_000).contains(size) else { skipped += 1; continue }
150 try fm.copyItem(at: file, to: copy)
151 let asset = AVURLAsset(url: copy)
152 let duration = try await asset.load(.duration).seconds
153 guard duration.isFinite, duration > 0, duration <= 7200,
154 !(try await asset.loadTracks(withMediaType: .audio)).isEmpty else {
155 try? fm.removeItem(at: copy); skipped += 1; continue
156 }
157 let data = try Data(contentsOf: copy, options: .mappedIfSafe)
158 tracks.append(RadioTrack(id: id, title: file.deletingPathExtension().lastPathComponent,
159 genre: "My music", duration: duration, audio: copy.lastPathComponent,
160 sha256: SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(), byteCount: data.count))
161 } catch is CancellationError { throw CancellationError() }
162 catch { try? fm.removeItem(at: copy); skipped += 1 }
163 }
164 try Task.checkCancellation()
165 guard !tracks.isEmpty else { throw PersonalRadioMusic.FolderError.empty }
166 let url = destination.appendingPathComponent("catalog.json")
167 let data = try JSONEncoder().encode(RadioCatalog(version: 1, title: folder.lastPathComponent, tracks: tracks))
168 _ = try RadioCatalog.decode(data, from: url)
169 try data.write(to: url, options: .atomic)
170 committed = true
171 return (url, skipped)
172 }
173
174 func removePersonalCopy(at url: URL?, within root: URL = PersonalRadioMusic.directory) {
175 guard let url, url.lastPathComponent == "catalog.json",
176 UUID(uuidString: url.deletingLastPathComponent().lastPathComponent) != nil,
177 url.deletingLastPathComponent().deletingLastPathComponent().standardizedFileURL.path == root.standardizedFileURL.path else { return }
178 try? FileManager.default.removeItem(at: url.deletingLastPathComponent())
179 }
180
181 func catalog(at url: URL) async throws -> RadioCatalog {
182 try RadioCatalog.decode(await document(at: url), from: url)
183 }
184
185 func stations(at url: URL) async throws -> RadioStationDirectory {
186 try RadioStationDirectory.decode(await document(at: url), from: url)
187 }
188
189 /// Only a complete library can prove a song was removed. Genre subsets and
190 /// failed requests must never delete favorites from other stations.
191 func completeCatalog(at source: URL) async throws -> (catalog: RadioCatalog, url: URL, stationID: String) {
192 if source.lastPathComponent == "stations.json" {
193 let directory = try await stations(at: source)
194 guard let all = directory.stations.first(where: { $0.id == "all-music" })
195 ?? (directory.stations.count == 1 ? directory.stations.first : nil) else { throw RadioError.invalidCatalog }
196 let url = try all.resolvedURL(relativeTo: source)
197 return (try await catalog(at: url), url, all.id)
198 }
199 return (try await catalog(at: source), source, "all-music")
200 }
201
202 private func document(at url: URL) async throws -> Data {
203 let data: Data
204 if url.isFileURL { data = try Data(contentsOf: url) }
205 else {
206 guard url.scheme == "https", url.host != nil, url.user == nil, url.password == nil else { throw RadioError.invalidCatalog }
207 let request = URLRequest(url: url, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval: 30)
208 let (body, response) = try await URLSession.shared.data(for: request)
209 guard let response = response as? HTTPURLResponse, response.statusCode == 200,
210 response.url?.scheme == "https" else { throw RadioError.download }
211 data = body
212 }
213 try Task.checkCancellation()
214 guard data.count <= 2_000_000 else { throw RadioError.invalidCatalog }
215 return data
216 }
217
218 func localAudio(for track: RadioTrack, catalogURL: URL) async throws -> URL {
219 let source = try track.resolvedURL(relativeTo: catalogURL)
220 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
221 let destination = directory.appendingPathComponent(track.sha256.lowercased() + ".m4a")
222 if let data = try? Data(contentsOf: destination), valid(data, track: track) { return destination }
223 let temporary: URL
224 if source.isFileURL { temporary = source }
225 else {
226 let request = URLRequest(url: source, timeoutInterval: 90)
227 let (downloaded, response) = try await URLSession.shared.download(for: request)
228 guard let response = response as? HTTPURLResponse, response.statusCode == 200,
229 response.url?.scheme == "https" else {
230 try? FileManager.default.removeItem(at: downloaded)
231 throw RadioError.download
232 }
233 temporary = downloaded
234 }
235 defer { if !source.isFileURL { try? FileManager.default.removeItem(at: temporary) } }
236 try Task.checkCancellation()
237 guard try temporary.resourceValues(forKeys: [.fileSizeKey]).fileSize == track.byteCount else { throw RadioError.integrity }
238 let data = try Data(contentsOf: temporary, options: .mappedIfSafe)
239 guard valid(data, track: track) else { throw RadioError.integrity }
240 try data.write(to: destination, options: .atomic)
241 return destination
242 }
243
244 private func valid(_ data: Data, track: RadioTrack) -> Bool {
245 data.count == track.byteCount && SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() == track.sha256.lowercased()
246 }
247}
248
249/// Browsing Studio music never switches Radio's station or starts its player.
250@MainActor final class StudioMusicCatalog: ObservableObject {
251 @Published private(set) var tracks: [RadioTrack] = []
252 @Published private(set) var loading = false
253 @Published private(set) var error: String?
254 private let library: RadioLibrary
255 private let source: URL
256 private var catalogURL: URL?
257 private let access: SecurityScopedAccess?
258
259 init(source: URL, folderBookmark: Data? = nil, library: RadioLibrary = RadioLibrary()) {
260 self.library = library
261 let folder = SecurityScopedAccess.resolve(bookmark: folderBookmark, fallback: source.deletingLastPathComponent())
262 self.source = source.isFileURL ? folder.appendingPathComponent(source.lastPathComponent) : source
263 access = source.isFileURL ? SecurityScopedAccess(url: folder) : nil
264 }
265
266 func load() async {
267 guard !loading else { return }
268 loading = true; error = nil
269 defer { loading = false }
270 do {
271 let complete = try await library.completeCatalog(at: source)
272 try Task.checkCancellation()
273 tracks = complete.catalog.tracks.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending }
274 catalogURL = complete.url
275 } catch is CancellationError { }
276 catch { self.error = error.localizedDescription }
277 }
278
279 func matching(search: String, favoritesOnly: Bool, favoriteIDs: Set<String>) -> [RadioTrack] {
280 let query = search.trimmingCharacters(in: .whitespacesAndNewlines)
281 return tracks.filter { track in
282 (!favoritesOnly || favoriteIDs.contains(track.id)) &&
283 (query.isEmpty || track.title.localizedStandardContains(query) || track.genre.localizedStandardContains(query))
284 }
285 }
286
287 func audio(for track: RadioTrack) async throws -> URL {
288 guard tracks.contains(track), let catalogURL else { throw RadioError.invalidCatalog }
289 return try await library.localAudio(for: track, catalogURL: catalogURL)
290 }
291}
292
293/// A Studio project owns its soundtrack copy, independent of Radio cache cleanup.
294enum StudioMusicStorage {
295 static func copy(_ source: URL, title: String, into directory: URL) throws -> URL {
296 let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: " -_()"))
297 let name = String(title.components(separatedBy: allowed.inverted).joined(separator: " ").prefix(100))
298 .trimmingCharacters(in: .whitespacesAndNewlines)
299 let folder = directory.appendingPathComponent(UUID().uuidString, isDirectory: true)
300 let destination = folder.appendingPathComponent(name.isEmpty ? "Soundtrack" : name).appendingPathExtension(source.pathExtension)
301 do {
302 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
303 try FileManager.default.copyItem(at: source, to: destination)
304 return destination
305 } catch { try? FileManager.default.removeItem(at: folder); throw error }
306 }
307}
308
309/// Shuffle deals every track once before starting another round.
310struct RadioQueue {
311 private var remaining: [Int] = []
312 mutating func reset() { remaining = [] }
313 mutating func next(count: Int, current: Int?, shuffle: Bool, prioritized: Set<Int> = []) -> Int? {
314 guard count > 0 else { return nil }
315 if !shuffle { return current.map { ($0 + 1) % count } ?? 0 }
316 // A manually selected song can still be in the bag. Count it as heard.
317 if remaining.count == 1, remaining.last == current, count > 1 { remaining = [] }
318 if remaining.isEmpty {
319 let favorites = (0..<count).filter { prioritized.contains($0) }.shuffled()
320 let others = (0..<count).filter { !prioritized.contains($0) }.shuffled()
321 remaining = others + favorites
322 }
323 if count > 1, remaining.last == current,
324 let alternate = remaining.indices.reversed().first(where: { remaining[$0] != current && prioritized.contains(remaining[$0]) == prioritized.contains(current ?? -1) })
325 ?? remaining.indices.reversed().first(where: { remaining[$0] != current }) {
326 remaining.swapAt(alternate, remaining.count - 1)
327 }
328 return remaining.popLast()
329 }
330}
331
332/// Deal favorites once per song, then fill with non-favorites. Studio is independent.
333enum RadioVisualSchedule {
334 static func make(plan: SongSegmentation, pool: [Int], bars: Int,
335 favorites: Set<Int> = [], played: Set<Int> = [], previous: Int? = nil, repeatFavorites: Bool = false) -> [StudioSegment] {
336 guard !pool.isEmpty else { return [] }
337 let available = Array(Set(pool)).sorted()
338 var preferred = available.filter { favorites.contains($0) && !played.contains($0) }.shuffled()
339 let fillers = repeatFavorites ? available : available.filter { !favorites.contains($0) }
340 var bag: [Int] = [], previous = previous, result: [StudioSegment] = []
341 for (start, end) in zip(plan.boundaries, plan.boundaries.dropFirst()) {
342 let scene: Int
343 if preferred.last == previous,
344 let alternate = preferred.firstIndex(where: { $0 != previous }) {
345 preferred.swapAt(alternate, preferred.count - 1)
346 }
347 // A lone favorite can be the outgoing song's last visual. Open with
348 // a different design, then deal that favorite later in the song.
349 if let favorite = preferred.last, favorite != previous || available.count == 1 {
350 scene = preferred.removeLast()
351 }
352 else {
353 // If the entire gallery is favorited, hold the last design once
354 // its unique choices run out rather than repeating favorites.
355 guard !fillers.isEmpty else {
356 if let last = result.popLast() { result.append(StudioSegment(start: last.start, end: end, scene: last.scene, bars: last.bars)) }
357 continue
358 }
359 if bag.isEmpty {
360 bag = fillers.shuffled()
361 if bag.count > 1, bag.last == previous { bag.swapAt(0, bag.count - 1) }
362 }
363 scene = bag.removeLast()
364 }
365 result.append(StudioSegment(start: start, end: end, scene: scene, bars: bars))
366 previous = scene
367 }
368 return result
369 }
370}
371
372/// Separate storage and preferences keep personal playlists out of Studio's catalog picker.
373enum PersonalRadioMusic {
374 static var directory: URL {
375 UserDataStorage.support.appendingPathComponent("PersonalRadio", isDirectory: true)
376 }
377 static let catalogKey = "PulseCanvas.radio.personalCatalog.v1"
378 static let activeKey = "PulseCanvas.radio.personalActive.v1"
379 enum FolderError: LocalizedError {
380 case unreadable, empty, tooMany
381 var errorDescription: String? {
382 switch self {
383 case .unreadable: return String(localized: "This folder couldn't be opened. Choose a downloaded music folder and try again.")
384 case .empty: return String(localized: "No playable songs found. Use MP3, M4A, WAV, AIFF, AAC, CAF or FLAC files up to 100 MB and two hours each.")
385 case .tooMany: return String(localized: "Choose a folder with up to 500 songs, including its subfolders.")
386 }
387 }
388 }
389}