1
0
mirror of https://github.com/yattee/yattee.git synced 2024-12-12 21:30:32 +05:30
yattee/Model/FeedModel.swift

305 lines
9.6 KiB
Swift
Raw Permalink Normal View History

2022-12-12 14:51:46 +05:30
import Cache
2022-12-13 05:09:50 +05:30
import CoreData
2023-02-25 21:12:18 +05:30
import Defaults
2022-12-10 07:31:59 +05:30
import Foundation
import Siesta
2022-12-12 14:51:46 +05:30
import SwiftyJSON
2022-12-10 07:31:59 +05:30
2022-12-12 14:51:46 +05:30
final class FeedModel: ObservableObject, CacheModel {
static let shared = FeedModel()
2022-12-10 07:31:59 +05:30
@Published var isLoading = false
@Published var videos = [Video]()
@Published private var page = 1
2023-04-22 21:29:28 +05:30
@Published var watchedUUID = UUID()
2022-12-10 07:31:59 +05:30
2022-12-17 02:56:14 +05:30
private var feedCount = UnwatchedFeedCountModel.shared
2022-12-13 05:09:50 +05:30
private var cacheModel = FeedCacheModel.shared
2022-12-10 07:31:59 +05:30
private var accounts = AccountsModel.shared
2022-12-12 14:51:46 +05:30
var storage: Storage<String, JSON>?
2022-12-16 14:05:10 +05:30
@Published var error: RequestError?
2022-12-13 05:09:50 +05:30
private var backgroundContext = PersistenceController.shared.container.newBackgroundContext()
2022-12-10 07:31:59 +05:30
var feed: Resource? {
accounts.api.feed(page)
}
func loadResources(force: Bool = false, onCompletion: @escaping () -> Void = {}) {
DispatchQueue.global(qos: .background).async { [weak self] in
guard let self else { return }
2022-12-11 20:45:42 +05:30
if force || self.videos.isEmpty {
2022-12-10 07:31:59 +05:30
self.loadCachedFeed()
}
if self.accounts.app == .invidious {
// Invidious for some reason won't refresh feed until homepage is loaded
DispatchQueue.main.async { [weak self] in
guard let self, let home = self.accounts.api.home else { return }
self.request(home, force: force)?
.onCompletion { _ in
self.loadFeed(force: force, onCompletion: onCompletion)
}
}
} else {
self.loadFeed(force: force, onCompletion: onCompletion)
}
}
}
func loadFeed(force: Bool = false, paginating: Bool = false, onCompletion: @escaping () -> Void = {}) {
DispatchQueue.main.async { [weak self] in
guard let self,
!self.isLoading,
let account = self.accounts.current
else {
self?.isLoading = false
onCompletion()
return
}
if paginating {
self.page += 1
} else {
self.page = 1
}
let feedBeforeLoad = self.feed
var request: Request?
if let feedBeforeLoad {
request = self.request(feedBeforeLoad, force: force)
}
if request != nil {
self.isLoading = true
}
request?
.onCompletion { _ in
self.isLoading = false
onCompletion()
}
.onSuccess { response in
2022-12-16 14:05:10 +05:30
self.error = nil
2022-12-10 07:31:59 +05:30
if let videos: [Video] = response.typedContent() {
if paginating {
self.videos.append(contentsOf: videos)
} else {
self.videos = videos
2022-12-13 05:09:50 +05:30
self.cacheModel.storeFeed(account: account, videos: self.videos)
self.calculateUnwatchedFeed()
2022-12-10 07:31:59 +05:30
}
}
}
2022-12-16 14:05:10 +05:30
.onFailure { self.error = $0 }
2022-12-10 07:31:59 +05:30
}
}
func reset() {
videos.removeAll()
page = 1
}
func loadNextPage() {
guard accounts.app.paginatesSubscriptions, !isLoading else { return }
loadFeed(force: true, paginating: true)
}
2022-12-14 21:53:04 +05:30
func onAccountChange() {
reset()
2022-12-21 04:21:04 +05:30
error = nil
2022-12-14 21:53:04 +05:30
loadResources(force: true)
calculateUnwatchedFeed()
}
2022-12-13 05:09:50 +05:30
func calculateUnwatchedFeed() {
2023-04-22 21:29:28 +05:30
guard let account = accounts.current, accounts.signedIn else { return }
2022-12-13 05:09:50 +05:30
let feed = cacheModel.retrieveFeed(account: account)
backgroundContext.perform { [weak self] in
guard let self else { return }
let watched = self.watchFetchRequestResult(feed, context: self.backgroundContext).filter(\.finished)
2022-12-13 17:44:20 +05:30
let unwatched = feed.filter { video in !watched.contains { $0.videoID == video.videoID } }
2022-12-14 17:35:36 +05:30
let unwatchedCount = max(0, feed.count - watched.count)
2022-12-13 05:09:50 +05:30
DispatchQueue.main.async { [weak self] in
guard let self else { return }
2022-12-17 02:56:14 +05:30
if unwatchedCount != self.feedCount.unwatched[account] {
self.feedCount.unwatched[account] = unwatchedCount
2022-12-13 05:09:50 +05:30
}
2022-12-13 17:44:20 +05:30
let byChannel = Dictionary(grouping: unwatched) { $0.channel.id }.mapValues(\.count)
2022-12-17 02:56:14 +05:30
self.feedCount.unwatchedByChannel[account] = byChannel
2023-04-22 21:29:28 +05:30
self.watchedUUID = UUID()
2022-12-13 05:09:50 +05:30
}
}
}
func markAllFeedAsWatched() {
2022-12-13 17:44:20 +05:30
let mark = { [weak self] in
2023-04-22 21:29:28 +05:30
guard let self else { return }
self.markVideos(self.videos, watched: true, watchedAt: Date(timeIntervalSince1970: 0))
2022-12-13 17:44:20 +05:30
}
if videos.isEmpty {
loadCachedFeed { mark() }
} else {
mark()
2022-12-13 05:09:50 +05:30
}
}
2022-12-13 17:44:20 +05:30
var canMarkAllFeedAsWatched: Bool {
guard let account = accounts.current, accounts.signedIn else { return false }
2022-12-17 02:56:14 +05:30
return (feedCount.unwatched[account] ?? 0) > 0
2022-12-13 17:44:20 +05:30
}
func canMarkChannelAsWatched(_ channelID: Channel.ID) -> Bool {
guard let account = accounts.current, accounts.signedIn else { return false }
2022-12-17 02:56:14 +05:30
return feedCount.unwatchedByChannel[account]?.keys.contains(channelID) ?? false
}
func markChannelAsWatched(_ channelID: Channel.ID) {
guard accounts.signedIn else { return }
2022-12-13 05:09:50 +05:30
2022-12-13 17:44:20 +05:30
let mark = { [weak self] in
guard let self else { return }
self.markVideos(self.videos.filter { $0.channel.id == channelID }, watched: true)
}
2022-12-13 05:09:50 +05:30
if videos.isEmpty {
loadCachedFeed { mark() }
} else {
mark()
}
}
2022-12-13 05:09:50 +05:30
func markChannelAsUnwatched(_ channelID: Channel.ID) {
guard accounts.signedIn else { return }
2022-12-13 05:09:50 +05:30
let mark = { [weak self] in
guard let self else { return }
self.markVideos(self.videos.filter { $0.channel.id == channelID }, watched: false)
2022-12-13 17:44:20 +05:30
}
if videos.isEmpty {
loadCachedFeed { mark() }
} else {
mark()
2022-12-13 05:09:50 +05:30
}
}
func markAllFeedAsUnwatched() {
guard accounts.current != nil else { return }
let mark = { [weak self] in
guard let self else { return }
self.markVideos(self.videos, watched: false)
}
if videos.isEmpty {
loadCachedFeed { mark() }
} else {
mark()
}
}
2023-04-22 21:29:28 +05:30
func markVideos(_ videos: [Video], watched: Bool, watchedAt: Date? = nil) {
guard accounts.signedIn, let account = accounts.current else { return }
backgroundContext.perform { [weak self] in
guard let self else { return }
if watched {
2023-04-22 21:29:28 +05:30
videos.forEach { Watch.markAsWatched(videoID: $0.videoID, account: account, duration: $0.length, watchedAt: watchedAt, context: self.backgroundContext) }
} else {
let watches = self.watchFetchRequestResult(videos, context: self.backgroundContext)
watches.forEach { self.backgroundContext.delete($0) }
}
try? self.backgroundContext.save()
self.calculateUnwatchedFeed()
2023-05-25 17:58:29 +05:30
WatchModel.shared.watchesChanged()
}
2022-12-13 05:09:50 +05:30
}
func playUnwatchedFeed() {
guard let account = accounts.current, accounts.signedIn else { return }
2022-12-13 05:09:50 +05:30
let videos = cacheModel.retrieveFeed(account: account)
guard !videos.isEmpty else { return }
let watches = watchFetchRequestResult(videos, context: backgroundContext)
let watchesIDs = watches.map(\.videoID)
let unwatched = videos.filter { video in
2023-02-25 21:12:18 +05:30
if Defaults[.hideShorts], video.short {
return false
}
2022-12-13 05:09:50 +05:30
if !watchesIDs.contains(video.videoID) {
return true
}
if let watch = watches.first(where: { $0.videoID == video.videoID }),
watch.finished
{
return false
}
return true
}
guard !unwatched.isEmpty else { return }
PlayerModel.shared.play(unwatched)
}
2022-12-13 17:44:20 +05:30
var canPlayUnwatchedFeed: Bool {
guard let account = accounts.current, accounts.signedIn else { return false }
2022-12-17 02:56:14 +05:30
return (feedCount.unwatched[account] ?? 0) > 0
2022-12-13 17:44:20 +05:30
}
2023-04-22 21:29:28 +05:30
var watchedId: String {
watchedUUID.uuidString
}
2022-12-10 07:31:59 +05:30
var feedTime: Date? {
if let account = accounts.current {
2022-12-13 05:09:50 +05:30
return cacheModel.getFeedTime(account: account)
2022-12-10 07:31:59 +05:30
}
return nil
}
var formattedFeedTime: String {
2022-12-12 14:51:46 +05:30
getFormattedDate(feedTime)
2022-12-10 07:31:59 +05:30
}
2022-12-13 17:44:20 +05:30
private func loadCachedFeed(_ onCompletion: @escaping () -> Void = {}) {
guard let account = accounts.current, accounts.signedIn else { return }
2022-12-13 05:09:50 +05:30
let cache = cacheModel.retrieveFeed(account: account)
2022-12-10 07:31:59 +05:30
if !cache.isEmpty {
2022-12-11 20:45:42 +05:30
DispatchQueue.main.async(qos: .userInteractive) { [weak self] in
2022-12-10 07:31:59 +05:30
self?.videos = cache
2022-12-13 17:44:20 +05:30
onCompletion()
2022-12-10 07:31:59 +05:30
}
}
}
private func request(_ resource: Resource, force: Bool = false) -> Request? {
if force {
return resource.load()
}
return resource.loadIfNeeded()
}
private func watchFetchRequestResult(_ videos: [Video], context: NSManagedObjectContext) -> [Watch] {
let watchFetchRequest = Watch.fetchRequest()
watchFetchRequest.predicate = NSPredicate(format: "videoID IN %@", videos.map(\.videoID) as [String])
return (try? context.fetch(watchFetchRequest)) ?? []
}
2022-12-10 07:31:59 +05:30
}