Files
mowesta/ios-app/app/Task/SyncTask.swift
T
Marcus Handte 8f7d88bcdd
LocationBasedServices/mowesta/pipeline/head There was a failure building this commit
Fix ios and android app compilation.
2024-03-05 17:09:36 +01:00

189 lines
7.4 KiB
Swift

//
// SyncTask.swift
// App
//
// Created by Marcus Handte on 22.07.22.
//
import Foundation
import class MoWeStaApi.DefaultAPI
import class MoWeStaApi.Settings
import class MoWeStaApi.LocationReference
public class SyncTask: BaseTask {
/// The persistence context
let context = PersistenceController.shared.container.newBackgroundContext()
/// The app state
let state = AppState.shared
/// The user credentials
let credential = AppState.shared.credentials
override func executeAsync() -> Bool {
print("Performing favorite synchronization.")
if let cs = credential {
if let settings = SettingDownloader(cs).getSettings() {
context.performAndWait { [context] in
let fetch = Favorite.fetchRequest()
if let favorites = try? fetch.execute() {
/// create a diff
var localOnlyFavorites = favorites
var localAndServerFavorites: [LocationReference:Favorite] = [:]
var remoteOnlyFavorites = settings.locations
ref: for ref in settings.locations {
for idx in localOnlyFavorites.indices {
let fav = localOnlyFavorites[idx]
if (fav.identifier == ref.id && fav.getLocationReferenceType() == ref.type) {
localAndServerFavorites.updateValue(fav, forKey: ref)
localOnlyFavorites.remove(at: idx)
remoteOnlyFavorites.removeAll() { r in
return ref.id == r.id && ref.type == r.type
}
continue ref
}
}
}
// handle favorites available remotely
var newFavorties: [Favorite] = []
var deletedFavorites: [Favorite] = []
var changedFavorites: [Favorite] = []
var newState = settings.locations
var deleted = 0
for idx in settings.locations.indices {
let i = idx - deleted
let ref = newState[i]
if let fav = localAndServerFavorites[ref] {
if fav.removed {
newState.remove(at: i)
deletedFavorites.append(fav)
context.delete(fav)
deleted += 1
} else {
fav.position = Int16(i)
fav.added = true
changedFavorites.append(fav)
}
} else {
let fav = Favorite(context: context)
fav.setLocationReferenceType(type: ref.type)
fav.added = true
fav.identifier = ref.id
fav.position = Int16(i)
context.insert(fav)
newFavorties.append(fav)
}
}
/// handle local only favorties
for fav in localOnlyFavorites {
if fav.removed || fav.added {
context.delete(fav)
deletedFavorites.append(fav)
} else {
let ref = LocationReference(type: fav.getLocationReferenceType(), id: fav.identifier)
fav.position = Int16(newState.count)
fav.added = true
newState.append(ref)
changedFavorites.append(fav)
}
}
/// apply the state to the server
let newSettings = Settings(id: settings.id, creationTime: settings.creationTime, modificationTime: settings.modificationTime, deleted: false, locations: newState)
if SettingUploader(cs, newSettings).setSettings() {
print("Saving local favorite changes since upload completed.")
try? context.save()
} else {
print("Resetting local favorite changes since upload failed.")
context.reset()
}
}
}
} else {
return false
}
return !isCanceled()
} else {
print("Skipping sync since user is not logged in.")
return true
}
}
}
/// A class to perform a blocking download of the settings
class SettingDownloader {
let credential: UserCredentials
var settings: Settings? = nil
init(_ credential: UserCredentials) {
self.credential = credential
}
public func getSettings() -> Settings? {
print("Loading user settings.")
let group = DispatchGroup()
group.enter()
let rb = DefaultAPI.getCurrentUserSettingsWithRequestBuilder()
rb.addHeaders(ApiHeader.create(credential))
rb.execute() { result in
switch result {
case let .success(response):
print("Loaded user setttings.")
self.settings = response.body
case let .failure(.error(code, _, _, _)):
print("Failed to load user settings.")
if code == 403 {
DispatchQueue.main.async {
AppState.shared.credentialFailure = true
}
}
}
group.leave()
}
group.wait()
print("Returning user settings: \(settings == nil)")
return settings
}
}
/// A class to perform a blocking upload of the settings
class SettingUploader {
let credential: UserCredentials
let settings: Settings
var success = false
init(_ credential: UserCredentials, _ settings: Settings) {
self.credential = credential
self.settings = settings
}
public func setSettings() -> Bool {
print("Uploading user settings.")
let group = DispatchGroup()
group.enter()
let rb = DefaultAPI.setCurrentUserSettingsWithRequestBuilder(settings: settings)
rb.addHeaders(ApiHeader.create(credential))
rb.execute() { result in
switch result {
case .success:
print("Uploaded user setttings.")
self.success = true
case let .failure(.error(code, _, _, _)):
print("Failed to upload user settings.")
if code == 403 {
DispatchQueue.main.async {
AppState.shared.credentialFailure = true
}
}
}
group.leave()
}
group.wait()
print("Returning upload settings: \(success)")
return success
}
}