Implement Milestone 7.2 offline audio downloads

This commit is contained in:
diyaa
2026-05-30 07:11:20 +02:00
parent 6e73c1878e
commit 56f030e651
19 changed files with 1822 additions and 31 deletions
@@ -6,6 +6,7 @@ import VelodyPersistence
public protocol RemoteLibraryRepository: Actor {
func loadCachedRemoteTracks() async throws -> [RemoteTrack]
func syncRemoteTracks(deviceId: String) async throws -> [RemoteTrack]
func downloadAudioAsset(assetId: String, deviceId: String) async throws -> Data
}
public actor DefaultRemoteLibraryRepository: RemoteLibraryRepository {
@@ -30,4 +31,11 @@ public actor DefaultRemoteLibraryRepository: RemoteLibraryRepository {
try await store.replaceRemoteTracks(tracks)
return tracks
}
public func downloadAudioAsset(
assetId: String,
deviceId: String
) async throws -> Data {
try await apiClient.downloadAudioAsset(assetId: assetId, deviceId: deviceId)
}
}
@@ -1,18 +1,184 @@
import Foundation
import VelodyDomain
import VelodyPersistence
public actor RemoteLibrarySyncService {
private let repository: any RemoteLibraryRepository
private let downloadStateStore: any RemoteTrackDownloadStateStore
private let audioFileStore: any OfflineAudioFileStore
public init(repository: any RemoteLibraryRepository) {
public init(
repository: any RemoteLibraryRepository,
downloadStateStore: any RemoteTrackDownloadStateStore,
audioFileStore: any OfflineAudioFileStore
) {
self.repository = repository
self.downloadStateStore = downloadStateStore
self.audioFileStore = audioFileStore
}
public func loadCachedRemoteTracks() async throws -> [RemoteTrack] {
try await repository.loadCachedRemoteTracks()
}
public func loadDownloadStates() async throws -> [RemoteTrackDownloadState] {
let states = try await downloadStateStore.loadDownloadStates()
return try await reconcileDownloadedLocalFilePaths(in: states)
}
public func syncRemoteLibrary(deviceId: String) async throws -> [RemoteTrack] {
try await repository.syncRemoteTracks(deviceId: deviceId)
let tracks = try await repository.syncRemoteTracks(deviceId: deviceId)
try await ensureDownloadStates(for: tracks)
return tracks
}
public func downloadTrack(
_ track: RemoteTrack,
deviceId: String
) async throws -> RemoteTrackDownloadState {
let currentState = try await currentDownloadState(for: track)
if currentState.downloadStatus == .downloaded,
currentState.assetId == track.assetId,
currentState.hasLocalFile,
await audioFileStore.fileExists(at: currentState.localFilePath)
{
return currentState
}
let downloadingState = RemoteTrackDownloadState(
remoteTrackId: track.trackId,
assetId: track.assetId,
localFilePath: currentState.assetId == track.assetId ? currentState.localFilePath : "",
downloadedAt: currentState.assetId == track.assetId ? currentState.downloadedAt : nil,
downloadStatus: .downloading,
lastDownloadError: nil
)
try await downloadStateStore.saveDownloadState(downloadingState)
do {
let audioData = try await repository.downloadAudioAsset(
assetId: track.assetId,
deviceId: deviceId
)
let localFilePath = try await audioFileStore.saveAudioFile(
audioData,
assetId: track.assetId,
sha256: track.sha256
)
let downloadedState = RemoteTrackDownloadState(
remoteTrackId: track.trackId,
assetId: track.assetId,
localFilePath: localFilePath,
downloadedAt: Date(),
downloadStatus: .downloaded,
lastDownloadError: nil
)
try await downloadStateStore.saveDownloadState(downloadedState)
return downloadedState
} catch {
let failedState = RemoteTrackDownloadState(
remoteTrackId: track.trackId,
assetId: track.assetId,
localFilePath: "",
downloadedAt: nil,
downloadStatus: .failed,
lastDownloadError: error.localizedDescription
)
try await downloadStateStore.saveDownloadState(failedState)
throw error
}
}
private func ensureDownloadStates(for tracks: [RemoteTrack]) async throws {
guard !tracks.isEmpty else {
return
}
var statesByTrackID = Dictionary(
uniqueKeysWithValues: try await loadDownloadStates()
.map { ($0.remoteTrackId, $0) }
)
var didChange = false
for track in tracks {
guard var existingState = statesByTrackID[track.trackId] else {
statesByTrackID[track.trackId] = RemoteTrackDownloadState(
remoteTrackId: track.trackId,
assetId: track.assetId,
downloadStatus: .notDownloaded
)
didChange = true
continue
}
if existingState.assetId != track.assetId {
existingState.assetId = track.assetId
existingState.localFilePath = ""
existingState.downloadedAt = nil
existingState.downloadStatus = .notDownloaded
existingState.lastDownloadError = nil
statesByTrackID[track.trackId] = existingState
didChange = true
}
}
if didChange {
try await downloadStateStore.saveDownloadStates(Array(statesByTrackID.values))
}
}
private func currentDownloadState(
for track: RemoteTrack
) async throws -> RemoteTrackDownloadState {
if let existingState = try await loadDownloadStates()
.first(where: { $0.remoteTrackId == track.trackId })
{
if existingState.assetId == track.assetId {
return existingState
}
}
return RemoteTrackDownloadState(
remoteTrackId: track.trackId,
assetId: track.assetId,
downloadStatus: .notDownloaded
)
}
private func reconcileDownloadedLocalFilePaths(
in states: [RemoteTrackDownloadState]
) async throws -> [RemoteTrackDownloadState] {
guard !states.isEmpty else {
return states
}
var reconciledStates = states
var didChange = false
for index in reconciledStates.indices {
let state = reconciledStates[index]
guard state.downloadStatus == .downloaded else {
continue
}
guard let resolvedLocalFilePath = await audioFileStore.resolveLocalFilePath(
persistedLocalFilePath: state.localFilePath,
assetId: state.assetId
) else {
continue
}
if state.localFilePath != resolvedLocalFilePath {
reconciledStates[index].localFilePath = resolvedLocalFilePath
didChange = true
}
}
if didChange {
try await downloadStateStore.saveDownloadStates(reconciledStates)
}
return reconciledStates
}
}
@@ -1,3 +1,4 @@
import CryptoKit
import Foundation
import XCTest
import VelodyDomain
@@ -8,6 +9,7 @@ import VelodyPersistence
final class RemoteLibrarySyncServiceTests: XCTestCase {
func testSuccessfulSyncPersistsRemoteTracks() async throws {
let store = InMemoryRemoteLibraryStore()
let downloadStateStore = InMemoryRemoteTrackDownloadStateStore()
let service = RemoteLibrarySyncService(
repository: DefaultRemoteLibraryRepository(
apiClient: MockVelodyAPIClient(
@@ -27,15 +29,19 @@ final class RemoteLibrarySyncServiceTests: XCTestCase {
)
),
store: store
)
),
downloadStateStore: downloadStateStore,
audioFileStore: InMemoryOfflineAudioFileStore()
)
let tracks = try await service.syncRemoteLibrary(deviceId: "device-123")
let cachedTracks = try await service.loadCachedRemoteTracks()
let downloadStates = try await service.loadDownloadStates()
XCTAssertEqual(tracks.count, 1)
XCTAssertEqual(cachedTracks, tracks)
XCTAssertEqual(cachedTracks.first?.trackId, "track-123")
XCTAssertEqual(downloadStates.first?.downloadStatus, .notDownloaded)
}
func testEmptyResponseClearsCachedRemoteLibrary() async throws {
@@ -53,20 +59,33 @@ final class RemoteLibrarySyncServiceTests: XCTestCase {
),
]
)
let downloadStateStore = InMemoryRemoteTrackDownloadStateStore(
states: [
RemoteTrackDownloadState(
remoteTrackId: "track-123",
assetId: "asset-123",
downloadStatus: .downloaded
),
]
)
let service = RemoteLibrarySyncService(
repository: DefaultRemoteLibraryRepository(
apiClient: MockVelodyAPIClient(
remoteLibraryResponse: RemoteLibraryResponseDTO(tracks: [])
),
store: store
)
),
downloadStateStore: downloadStateStore,
audioFileStore: InMemoryOfflineAudioFileStore()
)
let tracks = try await service.syncRemoteLibrary(deviceId: "device-123")
let cachedTracks = try await service.loadCachedRemoteTracks()
let downloadStates = try await service.loadDownloadStates()
XCTAssertEqual(tracks, [])
XCTAssertEqual(cachedTracks, [])
XCTAssertEqual(downloadStates.count, 1)
}
func testNetworkFailureLeavesCachedRemoteLibraryIntact() async throws {
@@ -81,13 +100,16 @@ final class RemoteLibrarySyncServiceTests: XCTestCase {
updatedAt: "2026-05-29T08:05:00.000Z"
)
let store = InMemoryRemoteLibraryStore(tracks: [cachedTrack])
let downloadStateStore = InMemoryRemoteTrackDownloadStateStore()
let service = RemoteLibrarySyncService(
repository: DefaultRemoteLibraryRepository(
apiClient: MockVelodyAPIClient(
remoteLibraryError: VelodyAPIError.requestFailed("Offline")
),
store: store
)
),
downloadStateStore: downloadStateStore,
audioFileStore: InMemoryOfflineAudioFileStore()
)
await XCTAssertThrowsErrorAsync {
@@ -97,18 +119,159 @@ final class RemoteLibrarySyncServiceTests: XCTestCase {
let cachedTracks = try await service.loadCachedRemoteTracks()
XCTAssertEqual(cachedTracks, [cachedTrack])
}
func testDownloadTrackPersistsDownloadedStateAndFile() async throws {
let downloadStateStore = InMemoryRemoteTrackDownloadStateStore()
let audioFileStore = InMemoryOfflineAudioFileStore()
let service = RemoteLibrarySyncService(
repository: DefaultRemoteLibraryRepository(
apiClient: MockVelodyAPIClient(
remoteLibraryResponse: RemoteLibraryResponseDTO(tracks: []),
audioAssetData: sampleMp3Data(seed: "download-success")
),
store: InMemoryRemoteLibraryStore()
),
downloadStateStore: downloadStateStore,
audioFileStore: audioFileStore
)
let track = RemoteTrack(
trackId: "track-123",
title: "Remote Title",
artist: "Remote Artist",
durationSeconds: 245,
sha256: sha256Hex(sampleMp3Data(seed: "download-success")),
assetId: "asset-456",
createdAt: "2026-05-29T08:00:00.000Z",
updatedAt: "2026-05-29T08:05:00.000Z"
)
let state = try await service.downloadTrack(track, deviceId: "device-123")
let storedStates = try await service.loadDownloadStates()
let fileExists = await audioFileStore.fileExists(at: state.localFilePath)
XCTAssertEqual(state.downloadStatus, .downloaded)
XCTAssertEqual(state.assetId, "asset-456")
XCTAssertFalse(state.localFilePath.isEmpty)
XCTAssertEqual(storedStates.first?.downloadStatus, .downloaded)
XCTAssertTrue(fileExists)
}
func testDownloadTrackPersistsFailureState() async throws {
let service = RemoteLibrarySyncService(
repository: DefaultRemoteLibraryRepository(
apiClient: MockVelodyAPIClient(
remoteLibraryResponse: RemoteLibraryResponseDTO(tracks: []),
downloadError: VelodyAPIError.server(statusCode: 404, message: "Missing")
),
store: InMemoryRemoteLibraryStore()
),
downloadStateStore: InMemoryRemoteTrackDownloadStateStore(),
audioFileStore: InMemoryOfflineAudioFileStore()
)
let track = RemoteTrack(
trackId: "track-123",
title: "Remote Title",
artist: "Remote Artist",
durationSeconds: 245,
sha256: sha256Hex(sampleMp3Data(seed: "download-failure")),
assetId: "asset-456",
createdAt: "2026-05-29T08:00:00.000Z",
updatedAt: "2026-05-29T08:05:00.000Z"
)
await XCTAssertThrowsErrorAsync {
_ = try await service.downloadTrack(track, deviceId: "device-123")
}
let storedStates = try await service.loadDownloadStates()
XCTAssertEqual(storedStates.first?.downloadStatus, .failed)
XCTAssertEqual(storedStates.first?.remoteTrackId, "track-123")
}
func testLoadDownloadStatesRepairsStaleLocalFilePathAfterStoreRecreation() async throws {
let fileManager = FileManager.default
let tempDirectory = fileManager.temporaryDirectory.appendingPathComponent(
UUID().uuidString,
isDirectory: true
)
let firstAudioDirectory = tempDirectory.appendingPathComponent("audio-v1", isDirectory: true)
let secondAudioDirectory = tempDirectory.appendingPathComponent("audio-v2", isDirectory: true)
let stateFileURL = tempDirectory.appendingPathComponent("remote-download-states.json")
let audioData = sampleMp3Data(seed: "relaunch-repair")
let track = RemoteTrack(
trackId: "track-123",
title: "1 Mai 2026",
artist: "Remote Artist",
durationSeconds: 245,
sha256: sha256Hex(audioData),
assetId: "asset-456",
createdAt: "2026-05-29T08:00:00.000Z",
updatedAt: "2026-05-29T08:05:00.000Z"
)
defer {
try? fileManager.removeItem(at: tempDirectory)
}
let firstService = RemoteLibrarySyncService(
repository: DefaultRemoteLibraryRepository(
apiClient: MockVelodyAPIClient(
remoteLibraryResponse: RemoteLibraryResponseDTO(tracks: []),
audioAssetData: audioData
),
store: InMemoryRemoteLibraryStore()
),
downloadStateStore: try FileRemoteTrackDownloadStateStore(fileURL: stateFileURL),
audioFileStore: try FileOfflineAudioFileStore(baseDirectoryURL: firstAudioDirectory)
)
let originalState = try await firstService.downloadTrack(track, deviceId: "device-123")
let originalFileURL = URL(fileURLWithPath: originalState.localFilePath)
let recreatedStoreFileURL = secondAudioDirectory.appendingPathComponent("asset-456.mp3")
try fileManager.createDirectory(at: secondAudioDirectory, withIntermediateDirectories: true)
try fileManager.moveItem(at: originalFileURL, to: recreatedStoreFileURL)
let relaunchedAudioStore = try FileOfflineAudioFileStore(baseDirectoryURL: secondAudioDirectory)
let relaunchedService = RemoteLibrarySyncService(
repository: DefaultRemoteLibraryRepository(
apiClient: MockVelodyAPIClient(remoteLibraryResponse: RemoteLibraryResponseDTO(tracks: [])),
store: InMemoryRemoteLibraryStore()
),
downloadStateStore: try FileRemoteTrackDownloadStateStore(fileURL: stateFileURL),
audioFileStore: relaunchedAudioStore
)
let restoredStates = try await relaunchedService.loadDownloadStates()
let restoredState = try XCTUnwrap(restoredStates.first)
let restoredBytes = try await relaunchedAudioStore.readAudioFile(at: restoredState.localFilePath)
let persistedRestoredState = try await FileRemoteTrackDownloadStateStore(fileURL: stateFileURL)
.loadDownloadStates()
.first
XCTAssertEqual(restoredState.downloadStatus, .downloaded)
XCTAssertEqual(restoredState.localFilePath, recreatedStoreFileURL.standardizedFileURL.path)
XCTAssertEqual(persistedRestoredState?.localFilePath, recreatedStoreFileURL.standardizedFileURL.path)
XCTAssertTrue(fileManager.fileExists(atPath: restoredState.localFilePath))
XCTAssertEqual(restoredBytes, audioData)
}
}
private struct MockVelodyAPIClient: VelodyAPIClient {
let remoteLibraryResponse: RemoteLibraryResponseDTO?
let remoteLibraryError: VelodyAPIError?
let audioAssetData: Data?
let downloadError: VelodyAPIError?
init(
remoteLibraryResponse: RemoteLibraryResponseDTO? = nil,
remoteLibraryError: VelodyAPIError? = nil
remoteLibraryError: VelodyAPIError? = nil,
audioAssetData: Data? = nil,
downloadError: VelodyAPIError? = nil
) {
self.remoteLibraryResponse = remoteLibraryResponse
self.remoteLibraryError = remoteLibraryError
self.audioAssetData = audioAssetData
self.downloadError = downloadError
}
func registerDevice(
@@ -154,6 +317,20 @@ private struct MockVelodyAPIClient: VelodyAPIClient {
return remoteLibraryResponse ?? RemoteLibraryResponseDTO(tracks: [])
}
func downloadAudioAsset(
assetId: String,
deviceId: String
) async throws -> Data {
_ = assetId
_ = deviceId
if let downloadError {
throw downloadError
}
return audioAssetData ?? Data()
}
func prepareUpload(
_ payload: UploadPrepareRequest
) async throws -> UploadPrepareResponse {
@@ -202,6 +379,16 @@ private struct MockVelodyAPIClient: VelodyAPIClient {
}
}
private func sampleMp3Data(seed: String) -> Data {
Data([
0x49, 0x44, 0x33, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21,
] + Array(seed.utf8))
}
private func sha256Hex(_ data: Data) -> String {
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
private func XCTAssertThrowsErrorAsync(
_ expression: @escaping () async throws -> Void,
file: StaticString = #filePath,