From 9a52eaa5658ecc0b00b13a360cf13b4dfb6f35fb Mon Sep 17 00:00:00 2001 From: Balazs Perlaki-Horvath Date: Thu, 2 Jan 2025 15:38:41 +0100 Subject: [PATCH] Fix categories parsing, when eTag 304 is used --- ViewModel/LibraryViewModel.swift | 42 +++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/ViewModel/LibraryViewModel.swift b/ViewModel/LibraryViewModel.swift index 5aee1e13d..e277568fc 100644 --- a/ViewModel/LibraryViewModel.swift +++ b/ViewModel/LibraryViewModel.swift @@ -87,9 +87,29 @@ final class LibraryViewModel: ObservableObject { // refresh library guard let data = try await fetchData() else { - error = nil - process.state = .complete - return + // this is the case when we have no new data (304 http) + // but we still need to refresh the memory only stored + // zimfile categories to languages dictionary + if CategoriesToLanguages.allCategories().count < 2 { + let context = Database.shared.viewContext + if let zimFiles: [ZimFile] = try? context.fetch(ZimFile.fetchRequest()) { + saveCategoryAvailableInLanguages(fromDBZimFiles: zimFiles) + // populate library language code if there isn't one set already + await setDefaultContentFilterLanguage() + + error = nil + process.state = .complete + return + } else { + error = LibraryRefreshError.process + process.state = .error + return + } + } else { + error = nil + process.state = .complete + return + } } let parser = try await parse(data: data) // delete all old ISO Lang Code entries if needed, by passing in an empty parser @@ -138,6 +158,22 @@ final class LibraryViewModel: ObservableObject { } CategoriesToLanguages.save(dictionary) } + + private func saveCategoryAvailableInLanguages(fromDBZimFiles zimFiles: [ZimFile]) { + var dictionary: [Category: Set] = [:] + for zimFile in zimFiles { + let category = Category(rawValue: zimFile.category) ?? .other + let allLanguagesForCategory: Set + let categoryLanguages: Set = Set(zimFile.languageCode.components(separatedBy: ",")) + if let existingLanguages = dictionary[category] { + allLanguagesForCategory = existingLanguages.union(categoryLanguages) + } else { + allLanguagesForCategory = categoryLanguages + } + dictionary[category] = allLanguagesForCategory + } + CategoriesToLanguages.save(dictionary) + } /// The fetched content is filtered by the languages set in settings. /// We need to make sure, whatever was set by the user is