mirror of
https://github.com/advplyr/audiobookshelf-app.git
synced 2026-08-09 13:28:43 +02:00
API functions to sync local progress
This commit is contained in:
@@ -130,24 +130,36 @@ extension LocalFile {
|
||||
}
|
||||
|
||||
extension LocalMediaProgress {
|
||||
init(localLibraryItem: LocalLibraryItem, episode: PodcastEpisode?, progress: MediaProgress) {
|
||||
init(localLibraryItem: LocalLibraryItem, episode: PodcastEpisode?) {
|
||||
self.id = localLibraryItem.id
|
||||
self.localLibraryItemId = localLibraryItem.id
|
||||
self.libraryItemId = localLibraryItem.libraryItemId
|
||||
|
||||
if let episode = episode {
|
||||
self.id += "-\(episode.id)"
|
||||
self.episodeId = episode.id
|
||||
}
|
||||
|
||||
self.serverAddress = localLibraryItem.serverAddress
|
||||
self.serverUserId = localLibraryItem.serverUserId
|
||||
self.serverConnectionConfigId = localLibraryItem.serverConnectionConfigId
|
||||
|
||||
self.duration = localLibraryItem.getDuration()
|
||||
self.progress = 0.0
|
||||
self.currentTime = 0.0
|
||||
self.isFinished = false
|
||||
self.lastUpdate = Int(Date().timeIntervalSince1970)
|
||||
self.startedAt = 0
|
||||
self.finishedAt = nil
|
||||
|
||||
if let episode = episode {
|
||||
self.id += "-\(episode.id)"
|
||||
self.episodeId = episode.id
|
||||
self.duration = episode.duration ?? 0.0
|
||||
}
|
||||
}
|
||||
|
||||
init(localLibraryItem: LocalLibraryItem, episode: PodcastEpisode?, progress: MediaProgress) {
|
||||
self.init(localLibraryItem: localLibraryItem, episode: episode)
|
||||
self.duration = progress.duration
|
||||
self.progress = progress.progress
|
||||
self.currentTime = progress.currentTime
|
||||
self.isFinished = false
|
||||
self.isFinished = progress.isFinished
|
||||
self.lastUpdate = progress.lastUpdate
|
||||
self.startedAt = progress.startedAt
|
||||
self.finishedAt = progress.finishedAt
|
||||
@@ -157,6 +169,10 @@ extension LocalMediaProgress {
|
||||
if self.isFinished != finished {
|
||||
self.progress = finished ? 1.0 : 0.0
|
||||
}
|
||||
|
||||
if self.startedAt == 0 && finished {
|
||||
self.startedAt = Int(Date().timeIntervalSince1970)
|
||||
}
|
||||
|
||||
self.isFinished = finished
|
||||
self.lastUpdate = Int(Date().timeIntervalSince1970)
|
||||
|
||||
@@ -37,6 +37,7 @@ class ApiClient {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static func postResource(endpoint: String, parameters: [String: String], callback: ((_ success: Bool) -> Void)?) {
|
||||
if (Store.serverConfig == nil) {
|
||||
NSLog("Server config not set")
|
||||
@@ -50,7 +51,7 @@ class ApiClient {
|
||||
|
||||
AF.request("\(Store.serverConfig!.address)/\(endpoint)", method: .post, parameters: parameters, encoder: JSONParameterEncoder.default, headers: headers).response { response in
|
||||
switch response.result {
|
||||
case .success(let _):
|
||||
case .success(_):
|
||||
callback?(true)
|
||||
case .failure(let error):
|
||||
NSLog("api request to \(endpoint) failed")
|
||||
@@ -60,6 +61,30 @@ class ApiClient {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static func patchResource<T:Encodable>(endpoint: String, parameters: T, callback: ((_ success: Bool) -> Void)?) {
|
||||
if (Store.serverConfig == nil) {
|
||||
NSLog("Server config not set")
|
||||
callback?(false)
|
||||
return
|
||||
}
|
||||
|
||||
let headers: HTTPHeaders = [
|
||||
"Authorization": "Bearer \(Store.serverConfig!.token)"
|
||||
]
|
||||
|
||||
AF.request("\(Store.serverConfig!.address)/\(endpoint)", method: .patch, parameters: parameters, encoder: JSONParameterEncoder.default, headers: headers).response { response in
|
||||
switch response.result {
|
||||
case .success(_):
|
||||
callback?(true)
|
||||
case .failure(let error):
|
||||
NSLog("api request to \(endpoint) failed")
|
||||
print(error)
|
||||
callback?(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static func getResource<T: Decodable>(endpoint: String, decodable: T.Type = T.self, callback: ((_ param: T?) -> Void)?) {
|
||||
if (Store.serverConfig == nil) {
|
||||
NSLog("Server config not set")
|
||||
@@ -119,6 +144,41 @@ class ApiClient {
|
||||
try? postResource(endpoint: "api/session/\(sessionId)/sync", parameters: report.asDictionary().mapValues({ value in "\(value)" }), callback: nil)
|
||||
}
|
||||
|
||||
public static func syncMediaProgress(callback: @escaping (_ results: LocalMediaProgressSyncResultsPayload) -> Void) {
|
||||
let localMediaProgressList = Database.shared.getAllLocalMediaProgress().filter {
|
||||
$0.serverConnectionConfigId == Store.serverConfig?.id
|
||||
}
|
||||
|
||||
if ( !localMediaProgressList.isEmpty ) {
|
||||
let payload = LocalMediaProgressSyncPayload(localMediaProgress: localMediaProgressList)
|
||||
NSLog("Sending sync local progress request with \(localMediaProgressList.count) progress items")
|
||||
try? postResource(endpoint: "/api/me/sync-local-progress", parameters: payload.asDictionary(), decodable: MediaProgressSyncResponsePayload.self) { response in
|
||||
|
||||
let resultsPayload = LocalMediaProgressSyncResultsPayload(numLocalMediaProgressForServer: localMediaProgressList.count, numServerProgressUpdates: response.numServerProgressUpdates, numLocalProgressUpdates: response.localProgressUpdates?.count)
|
||||
NSLog("Media Progress Sync | \(String(describing: try? resultsPayload.asDictionary()))")
|
||||
|
||||
if let updates = response.localProgressUpdates {
|
||||
for update in updates {
|
||||
Database.shared.saveLocalMediaProgress(update)
|
||||
}
|
||||
}
|
||||
|
||||
callback(resultsPayload)
|
||||
}
|
||||
} else {
|
||||
NSLog("No local media progress to sync")
|
||||
callback(LocalMediaProgressSyncResultsPayload(numLocalMediaProgressForServer: 0, numServerProgressUpdates: 0, numLocalProgressUpdates: 0))
|
||||
}
|
||||
}
|
||||
|
||||
public static func updateMediaProgress<T:Encodable>(libraryItemId: String, episodeId: String?, payload: T, callback: @escaping () -> Void) {
|
||||
NSLog("updateMediaProgress \(libraryItemId) \(episodeId ?? "NIL") \(payload)")
|
||||
let endpoint = episodeId?.isEmpty ?? true ? "/api/me/progress/\(libraryItemId)" : "/api/me/progress/\(libraryItemId)/\(episodeId ?? "")"
|
||||
patchResource(endpoint: endpoint, parameters: payload) { success in
|
||||
callback()
|
||||
}
|
||||
}
|
||||
|
||||
public static func getLibraryItemWithProgress(libraryItemId:String, episodeId:String?, callback: @escaping (_ param: LibraryItem?) -> Void) {
|
||||
var endpoint = "api/items/\(libraryItemId)?expanded=1&include=progress"
|
||||
if episodeId != nil {
|
||||
@@ -130,3 +190,18 @@ class ApiClient {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LocalMediaProgressSyncPayload: Codable {
|
||||
var localMediaProgress: [LocalMediaProgress]
|
||||
}
|
||||
|
||||
struct MediaProgressSyncResponsePayload: Codable {
|
||||
var numServerProgressUpdates: Int?
|
||||
var localProgressUpdates: [LocalMediaProgress]?
|
||||
}
|
||||
|
||||
struct LocalMediaProgressSyncResultsPayload: Codable {
|
||||
var numLocalMediaProgressForServer: Int?
|
||||
var numServerProgressUpdates: Int?
|
||||
var numLocalProgressUpdates: Int?
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
import RealmSwift
|
||||
import Capacitor
|
||||
|
||||
extension String: Error {}
|
||||
|
||||
@@ -31,6 +31,14 @@ extension Collection where Iterator.Element: Encodable {
|
||||
}
|
||||
}
|
||||
|
||||
extension CAPPluginCall {
|
||||
func getJson<T: Decodable>(_ key: String, type: T.Type) -> T? {
|
||||
guard let value = getString(key) else { return nil }
|
||||
guard let valueData = value.data(using: .utf8) else { return nil }
|
||||
return try? JSONDecoder().decode(type, from: valueData)
|
||||
}
|
||||
}
|
||||
|
||||
extension DispatchQueue {
|
||||
static func runOnMainQueue(callback: @escaping (() -> Void)) {
|
||||
if Thread.isMainThread {
|
||||
|
||||
Reference in New Issue
Block a user