diff --git a/Shared/Objects/Typings.swift b/Shared/Objects/Typings.swift index 878bd8dd..7d7e6f83 100644 --- a/Shared/Objects/Typings.swift +++ b/Shared/Objects/Typings.swift @@ -10,6 +10,7 @@ import Combine import Foundation import JellyfinAPI +// TODO: Look at refactoring everything in this file, probably move to JellyfinAPI struct LibraryFilters: Codable, Hashable { var filters: [ItemFilter] = [] var sortOrder: [APISortOrder] = [.ascending] @@ -25,9 +26,11 @@ public enum SortBy: String, Codable, CaseIterable { case premiereDate = "PremiereDate" case name = "SortName" case dateAdded = "DateCreated" + case random = "Random" } extension SortBy { + // TODO: Localize var localized: String { switch self { case .premiereDate: @@ -36,6 +39,8 @@ extension SortBy { return "Name" case .dateAdded: return "Date added" + case .random: + return "Random" } } } @@ -45,6 +50,7 @@ extension ItemFilter { [.isUnplayed, isPlayed, .isFavorite, .likes] } + // TODO: Localize var localized: String { switch self { case .isUnplayed: @@ -62,6 +68,7 @@ extension ItemFilter { } extension APISortOrder { + // TODO: Localize var localized: String { switch self { case .ascending: @@ -72,6 +79,7 @@ extension APISortOrder { } } +// TODO: Remove enum ItemType: String { case episode = "Episode" case movie = "Movie" diff --git a/Shared/ViewModels/LibraryViewModel.swift b/Shared/ViewModels/LibraryViewModel.swift index 6b9eb078..36e6ff1f 100644 --- a/Shared/ViewModels/LibraryViewModel.swift +++ b/Shared/ViewModels/LibraryViewModel.swift @@ -69,6 +69,8 @@ final class LibraryViewModel: ViewModel { if replaceCurrentItems { self.items = [] + self.currentPage = 0 + self.hasNextPage = true } let personIDs: [String] = [person].compactMap(\.?.id) @@ -93,8 +95,17 @@ final class LibraryViewModel: ViewModel { includeItemTypes = [.movie, .series, .boxSet] } + let excludedIDs: [String]? + + if filters.sortBy == [.random] { + excludedIDs = items.compactMap(\.id) + } else { + excludedIDs = nil + } + ItemsAPI.getItemsByUserId( userId: SessionManager.main.currentLogin.user.id, + excludeItemIds: excludedIDs, startIndex: currentPage * pageItemSize, limit: pageItemSize, recursive: true, @@ -121,7 +132,20 @@ final class LibraryViewModel: ViewModel { return } - self?.items.append(contentsOf: response.items ?? []) + let items: [BaseItemDto] + + // There is a bug either with the request construction or the server when using + // "Random" sort which causes duplicate items to be sent even though we send the + // excluded ids. This causes shorter item additions when using "Random" over + // consecutive calls. Investigation needs to be done to find the root of the problem. + // Only filter for "Random" as an optimization. + if filters.sortBy == [.random] { + items = response.items?.filter { !(self?.items.contains($0) ?? true) } ?? [] + } else { + items = response.items ?? [] + } + + self?.items.append(contentsOf: items) }) .store(in: &cancellables) }