Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Synchronization/SyncEngine.swift3// Description: Keeps the local library and the cluster in step.4import Foundation56public struct SyncReport: Sendable, Equatable {7 public var full = false8 public var tracksChanged = 09 public var removed = 010 public var operationsSent = 011 public var operationsWaiting = 012 public var conflicts = 013 public var playsSent = 014 public var downloadsQueued = 015}1617/// Keeps the local library and the cluster in step.18///19/// One pass: (1) send the changes made on this Mac (favourites, playlists), oldest first; (2) pull the catalogue20/// changes since the last revision seen — or everything, when asked or when the counts disagree; (3) pull the21/// account's playlists and favourites, unless local changes are still waiting; (4) send and pull listening history;22/// (5) queue the downloads that pinned collections now need. Audio is never fetched here.23public actor SyncEngine {24 private let store: LibraryStore25 private let api: APIClient26 private let downloads: DownloadManager?27 private let artwork: ArtworkStore?28 private var running: Task<SyncReport, Error>?29 public private(set) var lastSync: Date?30 public private(set) var lastError: String?31 private static let fullEvery: TimeInterval = 24 * 36003233 public init(store: LibraryStore, api: APIClient, downloads: DownloadManager? = nil, artwork: ArtworkStore? = nil) {34 self.store = store; self.api = api; self.downloads = downloads; self.artwork = artwork35 }3637 public var isSyncing: Bool { running != nil }3839 /// Runs one pass; a call made while a pass is running waits for that pass instead of starting another.40 @discardableResult41 public func sync(full: Bool = false) async throws -> SyncReport {42 if let running { return try await running.value }43 let task = Task { try await self.pass(forceFull: full) }44 running = task45 defer { running = nil }46 do { let r = try await task.value; lastSync = Date(); lastError = nil; return r }47 catch { lastError = APIClient.isOffline(error) ? nil : String(describing: error); throw error }48 }4950 private func pass(forceFull: Bool) async throws -> SyncReport {51 var report = SyncReport()52 try await flushOperations(&report)5354 let lastFull = Double(await store.value("library.lastFull") ?? "0") ?? 055 let knownRevision = await store.libraryRevision56 let wantFull = forceFull || Date().timeIntervalSince1970 - lastFull > Self.fullEvery || knownRevision == 057 let serverCounts = try await pullLibrary(full: wantFull, &report)58 if !report.full, await disagrees(serverCounts) { _ = try await pullLibrary(full: true, &report) }5960 report.operationsWaiting = await store.pendingOpCount()61 if report.operationsWaiting == 0 {62 let me: WireUserSnapshot = try await api.get("library/sync/me")63 try await store.apply(me)64 }6566 let plays = await store.unsyncedPlays()67 if !plays.isEmpty {68 let events: [[String: Any]] = plays.map { ["id": $0.id, "trackId": $0.trackID, "playedAt": APIClient.iso($0.playedAt), "listenedMs": $0.listenedMs, "completed": $0.completed, "source": $0.source] }69 let _: WireOK = try await api.send("POST", "library/history", json: ["events": events])70 await store.markPlaysSynced(plays.map(\.id)); report.playsSent = plays.count71 }72 if let page: WirePlayPage = try? await api.get("library/history", query: ["limit": "200"]) { await store.mergeServerPlays(page.items) }7374 if let downloads {75 report.downloadsQueued = await downloads.enqueue(await store.missingPinnedTrackIDs())76 await downloads.kick()77 }78 if let artwork {79 let ids = await store.albumArtworkIDs()80 Task.detached(priority: .utility) { await artwork.prefetch(ids) }81 }82 return report83 }8485 private func disagrees(_ server: WireCounts) async -> Bool {86 let local = await store.counts()87 if local.tracks != server.tracks { return true }88 // Rows kept for downloaded tracks that left the cluster make the album and artist counts legitimately differ.89 if await store.removedTrackCount() > 0 { return false }90 return local != server91 }9293 private func pullLibrary(full: Bool, _ report: inout SyncReport) async throws -> WireCounts {94 var since: Int64 = full ? 0 : await store.libraryRevision95 var artists = Set<String>(), albums = Set<String>(), tracks = Set<String>()96 var counts = WireCounts(artists: 0, albums: 0, tracks: 0)97 while true {98 let d: WireLibraryDelta = try await api.get("library/sync", query: ["since": String(since)])99 try await store.apply(d)100 report.tracksChanged += d.tracks.count; report.removed += d.deleted.count101 if full { artists.formUnion(d.artists.map(\.id)); albums.formUnion(d.albums.map(\.id)); tracks.formUnion(d.tracks.map(\.id)) }102 counts = d.counts103 guard d.more, d.rev > since else { break }104 since = d.rev105 }106 if full {107 try await store.prune(keepingArtists: artists, albums: albums, tracks: tracks)108 await store.setValue("library.lastFull", String(Date().timeIntervalSince1970))109 report.full = true110 }111 return counts112 }113114 // MARK: Local changes → cluster115116 private func snapshotPlaylists() async throws -> [String: WirePlaylist] {117 let me: WireUserSnapshot = try await api.get("library/sync/me")118 return Dictionary(uniqueKeysWithValues: me.playlists.map { ($0.id, $0) })119 }120121 private var playlistSnapshot: [String: WirePlaylist]?122 private func cachedPlaylists() async throws -> [String: WirePlaylist] {123 if let playlistSnapshot { return playlistSnapshot }124 let s = try await snapshotPlaylists(); playlistSnapshot = s; return s125 }126127 private func flushOperations(_ report: inout SyncReport) async throws {128 playlistSnapshot = nil129130 for op in await store.pendingOps() {131 do {132 let pid = op.payload["playlistID"] ?? ""133 switch op.kind {134 case .favorite:135 do { let _: WireOK = try await api.send(op.payload["on"] == "1" ? "PUT" : "DELETE", "library/favorites/\(op.payload["kind"] ?? "track")/\(op.payload["id"] ?? "")") }136 catch let e as APIError where e.isNotFound { /* the item left the cluster: nothing to mark */ }137138 case .playlistCreate:139 guard let lp = await store.localPlaylist(pid) else { break }140 let created: WireCreated = try await api.send("POST", "library/playlists", json: ["name": lp.name, "trackIds": Array(lp.trackIDs.prefix(500))])141 var stamp = created.updatedAt142 var rest = Array(lp.trackIDs.dropFirst(500))143 while !rest.isEmpty {144 let r: WireUpdated = try await api.send("POST", "library/playlists/\(created.id)/tracks", json: ["trackIds": Array(rest.prefix(500))])145 stamp = r.updatedAt ?? stamp; rest = Array(rest.dropFirst(500))146 }147 try await store.adoptPlaylistID(local: pid, remote: created.id, updatedAt: stamp)148 playlistSnapshot = nil149150 case .playlistRename:151 guard let lp = await store.localPlaylist(pid) else { break }152 var body: [String: Any] = ["name": op.payload["name"] ?? lp.name]153 if let base = lp.baseUpdatedAt { body["baseUpdatedAt"] = base }154 do { let r: WireUpdated = try await api.send("PATCH", "library/playlists/\(pid)", json: body); await store.setPlaylistBase(pid, updatedAt: r.updatedAt); playlistSnapshot = nil }155 catch let e as APIError where e.isConflict {156 report.conflicts += 1157 await store.addNotice("La liste « \(lp.name) » a été modifiée sur un autre appareil : son nom n’a pas été remplacé.")158 } catch let e as APIError where e.isNotFound { await store.forgetPlaylist(pid) }159160 case .playlistDelete:161 guard let lp = await store.localPlaylist(pid) else { break }162 guard let remote = try await cachedPlaylists()[pid] else { await store.forgetPlaylist(pid); break }163 if let base = lp.baseUpdatedAt, base != APIClient.iso(remote.updatedAt) {164 report.conflicts += 1165 await store.restorePlaylist(pid)166 await store.addNotice("La liste « \(lp.name) » a été modifiée sur un autre appareil depuis sa suppression ici : elle a été conservée.")167 } else {168 do { let _: WireOK = try await api.send("DELETE", "library/playlists/\(pid)") } catch let e as APIError where e.isNotFound {}169 await store.forgetPlaylist(pid); playlistSnapshot = nil170 }171172 case .playlistAdd:173 guard try await cachedPlaylists()[pid] != nil else { await store.forgetPlaylist(pid); break }174 do { let r: WireUpdated = try await api.send("POST", "library/playlists/\(pid)/tracks", json: ["trackIds": op.list]); await store.setPlaylistBase(pid, updatedAt: r.updatedAt); playlistSnapshot = nil }175 catch let e as APIError where e.isNotFound { /* none of these tracks exists any more */ }176177 case .playlistSet:178 guard let lp = await store.localPlaylist(pid) else { break }179 guard let remote = try await cachedPlaylists()[pid] else {180 await store.forgetPlaylist(pid)181 await store.addNotice("La liste « \(lp.name) » a été supprimée sur un autre appareil ; vos modifications hors ligne n’ont pas été appliquées.")182 break183 }184 let desired = op.list185 if let base = lp.baseUpdatedAt, base != APIClient.iso(remote.updatedAt) { try await keepBoth(lp, desired: desired, &report); playlistSnapshot = nil; break }186 // Tracks wanted more times than the cluster's list holds them are added first.187 var have: [String: Int] = [:]; for e in remote.entries { have[e.trackId, default: 0] += 1 }188 var missing: [String] = []189 for t in desired { if let n = have[t], n > 0 { have[t] = n - 1 } else { missing.append(t) } }190 var stamp: Date? = remote.updatedAt191 var entries = remote.entries192 if !missing.isEmpty {193 let r: WireUpdated = try await api.send("POST", "library/playlists/\(pid)/tracks", json: ["trackIds": Array(missing.prefix(500))])194 stamp = r.updatedAt ?? stamp195 entries = try await snapshotPlaylists()[pid]?.entries ?? entries196 }197 var pool: [String: [String]] = [:]; for e in entries.sorted(by: { $0.position < $1.position }) { pool[e.trackId, default: []].append(e.entryId) }198 var order: [String] = []199 for t in desired { if var ids = pool[t], !ids.isEmpty { order.append(ids.removeFirst()); pool[t] = ids } }200 var body: [String: Any] = ["entryIds": order]201 if let stamp { body["baseUpdatedAt"] = APIClient.iso(stamp) }202 do { let r: WireUpdated = try await api.send("PUT", "library/playlists/\(pid)/order", json: body); await store.setPlaylistBase(pid, updatedAt: r.updatedAt) }203 catch let e as APIError where e.isConflict { try await keepBoth(lp, desired: desired, &report) }204 playlistSnapshot = nil205 }206 await store.removeOp(op.id); report.operationsSent += 1207 } catch {208 // Unreachable or signed out: everything stays queued, in order. Anything else: this operation is retried a few times, then dropped with a notice.209 if APIClient.isOffline(error) || (error as? APIError) == .unauthenticated { throw error }210 if op.attempts >= 4 {211 await store.removeOp(op.id)212 await store.addNotice("Une modification faite hors ligne n’a pas pu être envoyée au serveur et a été abandonnée.")213 } else { await store.failOp(op.id, error: String(describing: error)) }214 }215 }216 }217218 /// The same playlist was changed here (offline) and elsewhere: neither version is overwritten. The cluster's219 /// version stays under its name; this Mac's version is saved next to it as a copy.220 private func keepBoth(_ lp: LibraryStore.LocalPlaylist, desired: [String], _ report: inout SyncReport) async throws {221 report.conflicts += 1222 let name = String("\(lp.name) (copie de ce Mac)".prefix(120))223 let created: WireCreated = try await api.send("POST", "library/playlists", json: ["name": name, "trackIds": Array(desired.prefix(500))])224 var rest = Array(desired.dropFirst(500))225 while !rest.isEmpty {226 let _: WireUpdated = try await api.send("POST", "library/playlists/\(created.id)/tracks", json: ["trackIds": Array(rest.prefix(500))]); rest = Array(rest.dropFirst(500))227 }228 await store.addNotice("La liste « \(lp.name) » a été modifiée ici et sur un autre appareil. Les deux versions ont été conservées : la vôtre s’appelle « \(name) ».")229 }230}231