Fix server not sending updates every 10 seconds

This commit is contained in:
ronaldheft 2022-08-23 17:32:43 -04:00
parent 6a885b7241
commit 099be648bf
3 changed files with 18 additions and 8 deletions

View file

@ -11,7 +11,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// Override point for customization after application launch.
let configuration = Realm.Configuration(
schemaVersion: 2,
schemaVersion: 3,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
NSLog("Realm schema version was \(oldSchemaVersion)")

View file

@ -31,6 +31,7 @@ class PlaybackSession: Object, Codable, Deletable {
@Persisted var serverConnectionConfigId: String?
@Persisted var serverAddress: String?
@Persisted var isActiveSession = true
@Persisted var serverUpdatedAt: Double = 0
var isLocal: Bool { self.localLibraryItem != nil }
var mediaPlayer: String { "AVPlayer" }

View file

@ -96,11 +96,12 @@ class PlayerProgress {
}
private func updateServerSessionFromLocalSession(_ session: PlaybackSession, rateLimitSync: Bool = false) async {
let nowInMilliseconds = Date().timeIntervalSince1970 * 1000
// If required, rate limit requests based on session last update
if rateLimitSync {
let now = Date().timeIntervalSince1970 * 1000
let lastUpdate = session.updatedAt ?? now
let timeSinceLastSync = now - lastUpdate
let lastUpdateInMilliseconds = session.serverUpdatedAt
let timeSinceLastSync = nowInMilliseconds - lastUpdateInMilliseconds
let timeBetweenSessionSync = PlayerProgress.TIME_BETWEEN_SESSION_SYNC_IN_SECONDS * 1000
guard timeSinceLastSync > timeBetweenSessionSync else {
// Skipping sync since last occurred within session sync time
@ -118,10 +119,18 @@ class PlayerProgress {
success = await ApiClient.reportPlaybackProgress(report: playbackReport, sessionId: session.id)
}
// Remove old sessions after they synced with the server
if success && !session.isActiveSession {
NSLog("Deleting sessionId(\(session.id)) as is no longer active")
session.thaw()?.delete()
if success {
if let session = session.thaw() {
// Update the server sync time, which is different than lastUpdate
session.update {
session.serverUpdatedAt = nowInMilliseconds
}
// Remove old sessions after they synced with the server
if !session.isActiveSession {
session.delete()
}
}
}
}