yattee/Model/HistoryModel.swift

113 lines
3.2 KiB
Swift
Raw Normal View History

import CoreData
import CoreMedia
import Defaults
import Foundation
2022-11-10 17:11:28 +00:00
import SwiftyJSON
extension PlayerModel {
func historyVideo(_ id: String) -> Video? {
historyVideos.first { $0.videoID == id }
}
func loadHistoryVideoDetails(_ id: Video.ID) {
guard historyVideo(id).isNil else {
return
}
2022-11-10 17:11:28 +00:00
if !Video.VideoID.isValid(id), let url = URL(string: id) {
historyVideos.append(.local(url))
return
}
playerAPI.video(id)
.load()
2022-11-10 21:51:34 +00:00
.onSuccess { [weak self] response in
guard let self else { return }
2022-11-10 17:11:28 +00:00
2022-11-10 21:51:34 +00:00
if let video: Video = response.typedContent() {
self.historyVideos.append(video)
}
}
2022-11-10 21:51:34 +00:00
.onCompletion { _ in
self.logger.info("LOADED history details: \(id)")
2022-11-10 21:51:34 +00:00
if self.historyItemBeingLoaded == id {
self.logger.info("setting no history loaded")
self.historyItemBeingLoaded = nil
}
2022-11-10 17:11:28 +00:00
2022-11-10 21:51:34 +00:00
if let id = self.historyItemsToLoad.popLast() {
self.loadHistoryVideoDetails(id)
}
2022-11-10 17:11:28 +00:00
}
}
func updateWatch(finished: Bool = false) {
2022-02-16 20:23:11 +00:00
guard let id = currentVideo?.videoID,
Defaults[.saveHistory]
else {
return
}
2022-02-16 20:23:11 +00:00
let time = backend.currentTime
let seconds = time?.seconds ?? 0
let watchFetchRequest = Watch.fetchRequest()
watchFetchRequest.predicate = NSPredicate(format: "videoID = %@", id as String)
let results = try? backgroundContext.fetch(watchFetchRequest)
backgroundContext.perform { [weak self] in
2022-12-04 11:07:06 +00:00
guard let self, finished || self.backend.isPlaying else {
return
}
let watch: Watch!
if results?.isEmpty ?? true {
if seconds < 1 {
return
}
watch = Watch(context: self.backgroundContext)
watch.videoID = id
} else {
watch = results?.first
}
2022-12-04 11:07:06 +00:00
let duration = self.playerTime.duration.seconds
if duration.isFinite, duration > 0 {
watch.videoDuration = duration
}
2022-12-04 11:07:06 +00:00
if watch.finished {
if !finished, self.resetWatchedStatusOnPlaying, seconds.isFinite, seconds > 0 {
watch.stoppedAt = seconds
}
} else if seconds.isFinite, seconds > 0 {
watch.stoppedAt = seconds
}
watch.watchedAt = Date()
try? self.backgroundContext.save()
}
}
2022-11-15 11:22:27 +00:00
func removeHistory() {
removeAllWatches()
CacheModel.shared.removeAll()
}
func removeWatch(_ watch: Watch) {
context.delete(watch)
try? context.save()
}
func removeAllWatches() {
let watchesFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Watch")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: watchesFetchRequest)
_ = try? context.execute(deleteRequest)
_ = try? context.save()
}
}