@@ -50,6 +50,7 @@
|
|||||||
A977D0DE2B600300009783A9 /* SearchTabView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A977D0DD2B600300009783A9 /* SearchTabView.swift */; };
|
A977D0DE2B600300009783A9 /* SearchTabView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A977D0DD2B600300009783A9 /* SearchTabView.swift */; };
|
||||||
A977D0E02B600318009783A9 /* RecipeTabView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A977D0DF2B600318009783A9 /* RecipeTabView.swift */; };
|
A977D0E02B600318009783A9 /* RecipeTabView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A977D0DF2B600318009783A9 /* RecipeTabView.swift */; };
|
||||||
A977D0E22B60034E009783A9 /* GroceryListTabView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A977D0E12B60034E009783A9 /* GroceryListTabView.swift */; };
|
A977D0E22B60034E009783A9 /* GroceryListTabView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A977D0E12B60034E009783A9 /* GroceryListTabView.swift */; };
|
||||||
|
A99DC7BC2B6411A7000118AA /* SimilaritySearchKit in Frameworks */ = {isa = PBXBuildFile; productRef = A99DC7BB2B6411A7000118AA /* SimilaritySearchKit */; };
|
||||||
A9CA6CEF2B4C086100F78AB5 /* RecipeExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA6CEE2B4C086100F78AB5 /* RecipeExporter.swift */; };
|
A9CA6CEF2B4C086100F78AB5 /* RecipeExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9CA6CEE2B4C086100F78AB5 /* RecipeExporter.swift */; };
|
||||||
A9CA6CF62B4C63F200F78AB5 /* TPPDF in Frameworks */ = {isa = PBXBuildFile; productRef = A9CA6CF52B4C63F200F78AB5 /* TPPDF */; };
|
A9CA6CF62B4C63F200F78AB5 /* TPPDF in Frameworks */ = {isa = PBXBuildFile; productRef = A9CA6CF52B4C63F200F78AB5 /* TPPDF */; };
|
||||||
A9D89AB02B4FE97800F49D92 /* TimerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9D89AAF2B4FE97800F49D92 /* TimerView.swift */; };
|
A9D89AB02B4FE97800F49D92 /* TimerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9D89AAF2B4FE97800F49D92 /* TimerView.swift */; };
|
||||||
@@ -131,6 +132,7 @@
|
|||||||
buildActionMask = 2147483647;
|
buildActionMask = 2147483647;
|
||||||
files = (
|
files = (
|
||||||
A74D33BE2AF82AAE00D06555 /* SwiftSoup in Frameworks */,
|
A74D33BE2AF82AAE00D06555 /* SwiftSoup in Frameworks */,
|
||||||
|
A99DC7BC2B6411A7000118AA /* SimilaritySearchKit in Frameworks */,
|
||||||
A9CA6CF62B4C63F200F78AB5 /* TPPDF in Frameworks */,
|
A9CA6CF62B4C63F200F78AB5 /* TPPDF in Frameworks */,
|
||||||
);
|
);
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
@@ -180,7 +182,7 @@
|
|||||||
A70171812AA8E71900064C43 /* Nextcloud_Cookbook_iOS_ClientApp.swift */,
|
A70171812AA8E71900064C43 /* Nextcloud_Cookbook_iOS_ClientApp.swift */,
|
||||||
A70171C72AB4C4A100064C43 /* Data */,
|
A70171C72AB4C4A100064C43 /* Data */,
|
||||||
A70171BA2AB4980100064C43 /* Views */,
|
A70171BA2AB4980100064C43 /* Views */,
|
||||||
A70171B72AB2445700064C43 /* ViewModels */,
|
A70171B72AB2445700064C43 /* Models */,
|
||||||
A70171B22AB211F000064C43 /* Network */,
|
A70171B22AB211F000064C43 /* Network */,
|
||||||
A781E75F2AF8228100452F6F /* RecipeImport */,
|
A781E75F2AF8228100452F6F /* RecipeImport */,
|
||||||
A9CA6CED2B4C084100F78AB5 /* RecipeExport */,
|
A9CA6CED2B4C084100F78AB5 /* RecipeExport */,
|
||||||
@@ -223,6 +225,7 @@
|
|||||||
A70171B22AB211F000064C43 /* Network */ = {
|
A70171B22AB211F000064C43 /* Network */ = {
|
||||||
isa = PBXGroup;
|
isa = PBXGroup;
|
||||||
children = (
|
children = (
|
||||||
|
A79AA8EA2B062E15007D25F2 /* ApiRequest.swift */,
|
||||||
A79AA8EE2B063B33007D25F2 /* NextcloudApi */,
|
A79AA8EE2B063B33007D25F2 /* NextcloudApi */,
|
||||||
A79AA8E72B062DB6007D25F2 /* CookbookApi */,
|
A79AA8E72B062DB6007D25F2 /* CookbookApi */,
|
||||||
A70171B32AB2122900064C43 /* NetworkRequests.swift */,
|
A70171B32AB2122900064C43 /* NetworkRequests.swift */,
|
||||||
@@ -232,13 +235,13 @@
|
|||||||
path = Network;
|
path = Network;
|
||||||
sourceTree = "<group>";
|
sourceTree = "<group>";
|
||||||
};
|
};
|
||||||
A70171B72AB2445700064C43 /* ViewModels */ = {
|
A70171B72AB2445700064C43 /* Models */ = {
|
||||||
isa = PBXGroup;
|
isa = PBXGroup;
|
||||||
children = (
|
children = (
|
||||||
A70171AC2AA8EF4700064C43 /* AppState.swift */,
|
A70171AC2AA8EF4700064C43 /* AppState.swift */,
|
||||||
A79AA8E12AFF8C14007D25F2 /* RecipeEditViewModel.swift */,
|
A79AA8E12AFF8C14007D25F2 /* RecipeEditViewModel.swift */,
|
||||||
);
|
);
|
||||||
path = ViewModels;
|
path = Models;
|
||||||
sourceTree = "<group>";
|
sourceTree = "<group>";
|
||||||
};
|
};
|
||||||
A70171BA2AB4980100064C43 /* Views */ = {
|
A70171BA2AB4980100064C43 /* Views */ = {
|
||||||
@@ -295,7 +298,6 @@
|
|||||||
A79AA8E72B062DB6007D25F2 /* CookbookApi */ = {
|
A79AA8E72B062DB6007D25F2 /* CookbookApi */ = {
|
||||||
isa = PBXGroup;
|
isa = PBXGroup;
|
||||||
children = (
|
children = (
|
||||||
A79AA8EA2B062E15007D25F2 /* ApiRequest.swift */,
|
|
||||||
A79AA8E32B02A961007D25F2 /* CookbookApi.swift */,
|
A79AA8E32B02A961007D25F2 /* CookbookApi.swift */,
|
||||||
A79AA8E82B062DD1007D25F2 /* CookbookApiV1.swift */,
|
A79AA8E82B062DD1007D25F2 /* CookbookApiV1.swift */,
|
||||||
);
|
);
|
||||||
@@ -394,6 +396,7 @@
|
|||||||
packageProductDependencies = (
|
packageProductDependencies = (
|
||||||
A74D33BD2AF82AAE00D06555 /* SwiftSoup */,
|
A74D33BD2AF82AAE00D06555 /* SwiftSoup */,
|
||||||
A9CA6CF52B4C63F200F78AB5 /* TPPDF */,
|
A9CA6CF52B4C63F200F78AB5 /* TPPDF */,
|
||||||
|
A99DC7BB2B6411A7000118AA /* SimilaritySearchKit */,
|
||||||
);
|
);
|
||||||
productName = "Nextcloud Cookbook iOS Client";
|
productName = "Nextcloud Cookbook iOS Client";
|
||||||
productReference = A701717E2AA8E71900064C43 /* Nextcloud Cookbook iOS Client.app */;
|
productReference = A701717E2AA8E71900064C43 /* Nextcloud Cookbook iOS Client.app */;
|
||||||
@@ -473,6 +476,7 @@
|
|||||||
packageReferences = (
|
packageReferences = (
|
||||||
A74D33BC2AF82AAE00D06555 /* XCRemoteSwiftPackageReference "SwiftSoup" */,
|
A74D33BC2AF82AAE00D06555 /* XCRemoteSwiftPackageReference "SwiftSoup" */,
|
||||||
A9CA6CF42B4C63F200F78AB5 /* XCRemoteSwiftPackageReference "TPPDF" */,
|
A9CA6CF42B4C63F200F78AB5 /* XCRemoteSwiftPackageReference "TPPDF" */,
|
||||||
|
A99DC7BA2B6411A7000118AA /* XCRemoteSwiftPackageReference "similarity-search-kit" */,
|
||||||
);
|
);
|
||||||
productRefGroup = A701717F2AA8E71900064C43 /* Products */;
|
productRefGroup = A701717F2AA8E71900064C43 /* Products */;
|
||||||
projectDirPath = "";
|
projectDirPath = "";
|
||||||
@@ -738,7 +742,7 @@
|
|||||||
LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";
|
LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";
|
||||||
"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";
|
"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";
|
||||||
MACOSX_DEPLOYMENT_TARGET = 14.0;
|
MACOSX_DEPLOYMENT_TARGET = 14.0;
|
||||||
MARKETING_VERSION = 1.8.1;
|
MARKETING_VERSION = 1.9.0;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = "VincentMeilinger.Nextcloud-Cookbook-iOS-Client";
|
PRODUCT_BUNDLE_IDENTIFIER = "VincentMeilinger.Nextcloud-Cookbook-iOS-Client";
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SDKROOT = auto;
|
SDKROOT = auto;
|
||||||
@@ -781,7 +785,7 @@
|
|||||||
LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";
|
LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";
|
||||||
"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";
|
"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";
|
||||||
MACOSX_DEPLOYMENT_TARGET = 14.0;
|
MACOSX_DEPLOYMENT_TARGET = 14.0;
|
||||||
MARKETING_VERSION = 1.8.1;
|
MARKETING_VERSION = 1.9.0;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = "VincentMeilinger.Nextcloud-Cookbook-iOS-Client";
|
PRODUCT_BUNDLE_IDENTIFIER = "VincentMeilinger.Nextcloud-Cookbook-iOS-Client";
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SDKROOT = auto;
|
SDKROOT = auto;
|
||||||
@@ -937,6 +941,14 @@
|
|||||||
minimumVersion = 2.6.1;
|
minimumVersion = 2.6.1;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
A99DC7BA2B6411A7000118AA /* XCRemoteSwiftPackageReference "similarity-search-kit" */ = {
|
||||||
|
isa = XCRemoteSwiftPackageReference;
|
||||||
|
repositoryURL = "https://github.com/ZachNagengast/similarity-search-kit";
|
||||||
|
requirement = {
|
||||||
|
kind = upToNextMajorVersion;
|
||||||
|
minimumVersion = 0.0.13;
|
||||||
|
};
|
||||||
|
};
|
||||||
A9CA6CF42B4C63F200F78AB5 /* XCRemoteSwiftPackageReference "TPPDF" */ = {
|
A9CA6CF42B4C63F200F78AB5 /* XCRemoteSwiftPackageReference "TPPDF" */ = {
|
||||||
isa = XCRemoteSwiftPackageReference;
|
isa = XCRemoteSwiftPackageReference;
|
||||||
repositoryURL = "https://github.com/techprimate/TPPDF.git";
|
repositoryURL = "https://github.com/techprimate/TPPDF.git";
|
||||||
@@ -953,6 +965,11 @@
|
|||||||
package = A74D33BC2AF82AAE00D06555 /* XCRemoteSwiftPackageReference "SwiftSoup" */;
|
package = A74D33BC2AF82AAE00D06555 /* XCRemoteSwiftPackageReference "SwiftSoup" */;
|
||||||
productName = SwiftSoup;
|
productName = SwiftSoup;
|
||||||
};
|
};
|
||||||
|
A99DC7BB2B6411A7000118AA /* SimilaritySearchKit */ = {
|
||||||
|
isa = XCSwiftPackageProductDependency;
|
||||||
|
package = A99DC7BA2B6411A7000118AA /* XCRemoteSwiftPackageReference "similarity-search-kit" */;
|
||||||
|
productName = SimilaritySearchKit;
|
||||||
|
};
|
||||||
A9CA6CF52B4C63F200F78AB5 /* TPPDF */ = {
|
A9CA6CF52B4C63F200F78AB5 /* TPPDF */ = {
|
||||||
isa = XCSwiftPackageProductDependency;
|
isa = XCSwiftPackageProductDependency;
|
||||||
package = A9CA6CF42B4C63F200F78AB5 /* XCRemoteSwiftPackageReference "TPPDF" */;
|
package = A9CA6CF42B4C63F200F78AB5 /* XCRemoteSwiftPackageReference "TPPDF" */;
|
||||||
|
|||||||
@@ -1,5 +1,14 @@
|
|||||||
{
|
{
|
||||||
"pins" : [
|
"pins" : [
|
||||||
|
{
|
||||||
|
"identity" : "similarity-search-kit",
|
||||||
|
"kind" : "remoteSourceControl",
|
||||||
|
"location" : "https://github.com/ZachNagengast/similarity-search-kit",
|
||||||
|
"state" : {
|
||||||
|
"revision" : "ddc8e458d0e826b2fe5dbce6f6eac96a8935e8eb",
|
||||||
|
"version" : "0.0.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"identity" : "swiftsoup",
|
"identity" : "swiftsoup",
|
||||||
"kind" : "remoteSourceControl",
|
"kind" : "remoteSourceControl",
|
||||||
|
|||||||
Binary file not shown.
@@ -10,7 +10,7 @@ import SwiftUI
|
|||||||
|
|
||||||
class DataStore {
|
class DataStore {
|
||||||
let fileManager = FileManager.default
|
let fileManager = FileManager.default
|
||||||
|
static let shared = DataStore()
|
||||||
|
|
||||||
private static func fileURL(appending: String) throws -> URL {
|
private static func fileURL(appending: String) throws -> URL {
|
||||||
try FileManager.default.url(
|
try FileManager.default.url(
|
||||||
@@ -87,7 +87,28 @@ class DataStore {
|
|||||||
return true
|
return true
|
||||||
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SimilarityIndex loading and saving
|
||||||
|
import SimilaritySearchKit
|
||||||
|
extension DataStore {
|
||||||
|
func loadIndex() async -> [IndexItem]? {
|
||||||
|
do {
|
||||||
|
let indexItems = try await SimilarityIndex().loadIndex(fromDirectory: Self.fileURL(appending: "similarity_index"))
|
||||||
|
return indexItems
|
||||||
|
} catch {
|
||||||
|
print("Unable to load SimilarityIndex")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func saveIndex(_ index: SimilarityIndex) {
|
||||||
|
do {
|
||||||
|
try index.saveIndex(toDirectory: Self.fileURL(appending: "similarity_index"))
|
||||||
|
} catch {
|
||||||
|
print("Unable to save SimilarityIndex")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -43,6 +43,12 @@ class UserSettings: ObservableObject {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Published var cookbookApiVersion: CookbookApiVersion {
|
||||||
|
didSet {
|
||||||
|
UserDefaults.standard.set(cookbookApiVersion, forKey: "cookbookApiVersion")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Published var onboarding: Bool {
|
@Published var onboarding: Bool {
|
||||||
didSet {
|
didSet {
|
||||||
UserDefaults.standard.set(onboarding, forKey: "onboarding")
|
UserDefaults.standard.set(onboarding, forKey: "onboarding")
|
||||||
@@ -115,6 +121,7 @@ class UserSettings: ObservableObject {
|
|||||||
self.authString = UserDefaults.standard.object(forKey: "authString") as? String ?? ""
|
self.authString = UserDefaults.standard.object(forKey: "authString") as? String ?? ""
|
||||||
self.serverAddress = UserDefaults.standard.object(forKey: "serverAddress") as? String ?? ""
|
self.serverAddress = UserDefaults.standard.object(forKey: "serverAddress") as? String ?? ""
|
||||||
self.serverProtocol = UserDefaults.standard.object(forKey: "serverProtocol") as? String ?? "https://"
|
self.serverProtocol = UserDefaults.standard.object(forKey: "serverProtocol") as? String ?? "https://"
|
||||||
|
self.cookbookApiVersion = UserDefaults.standard.object(forKey: "cookbookApiVersion") as? CookbookApiVersion ?? .v1
|
||||||
self.onboarding = UserDefaults.standard.object(forKey: "onboarding") as? Bool ?? true
|
self.onboarding = UserDefaults.standard.object(forKey: "onboarding") as? Bool ?? true
|
||||||
self.defaultCategory = UserDefaults.standard.object(forKey: "defaultCategory") as? String ?? ""
|
self.defaultCategory = UserDefaults.standard.object(forKey: "defaultCategory") as? String ?? ""
|
||||||
self.language = UserDefaults.standard.object(forKey: "language") as? String ?? SupportedLanguage.DEVICE.rawValue
|
self.language = UserDefaults.standard.object(forKey: "language") as? String ?? SupportedLanguage.DEVICE.rawValue
|
||||||
@@ -134,15 +141,14 @@ class UserSettings: ObservableObject {
|
|||||||
authString = loginData.base64EncodedString()
|
authString = loginData.base64EncodedString()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func setAuthString() -> String {
|
func setAuthString() {
|
||||||
if token != "" && username != "" {
|
if token != "" && username != "" {
|
||||||
let loginString = "\(self.username):\(self.token)"
|
let loginString = "\(self.username):\(self.token)"
|
||||||
let loginData = loginString.data(using: String.Encoding.utf8)!
|
let loginData = loginString.data(using: String.Encoding.utf8)!
|
||||||
return loginData.base64EncodedString()
|
self.authString = loginData.base64EncodedString()
|
||||||
} else {
|
|
||||||
return ""
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3180,6 +3180,9 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"Username: %@" : {
|
||||||
|
|
||||||
},
|
},
|
||||||
"Validate" : {
|
"Validate" : {
|
||||||
"localizations" : {
|
"localizations" : {
|
||||||
|
|||||||
@@ -19,13 +19,10 @@ import UIKit
|
|||||||
var imagesNeedUpdate: [Int: [String: Bool]] = [:]
|
var imagesNeedUpdate: [Int: [String: Bool]] = [:]
|
||||||
var lastUpdates: [String: Date] = [:]
|
var lastUpdates: [String: Date] = [:]
|
||||||
|
|
||||||
|
|
||||||
private let api: CookbookApi.Type
|
|
||||||
private let dataStore: DataStore
|
private let dataStore: DataStore
|
||||||
|
|
||||||
init(apiVersion api: CookbookApi.Type = CookbookApiV1.self) {
|
init() {
|
||||||
print("Created MainViewModel")
|
print("Created MainViewModel")
|
||||||
self.api = api
|
|
||||||
self.dataStore = DataStore()
|
self.dataStore = DataStore()
|
||||||
|
|
||||||
if UserSettings.shared.authString == "" {
|
if UserSettings.shared.authString == "" {
|
||||||
@@ -48,7 +45,7 @@ import UIKit
|
|||||||
- Important: This function assumes that the server address, authentication string, and API have been properly configured in the `MainViewModel` instance.
|
- Important: This function assumes that the server address, authentication string, and API have been properly configured in the `MainViewModel` instance.
|
||||||
*/
|
*/
|
||||||
func getCategories() async {
|
func getCategories() async {
|
||||||
let (categories, _) = await api.getCategories(
|
let (categories, _) = await cookbookApi.getCategories(
|
||||||
auth: UserSettings.shared.authString
|
auth: UserSettings.shared.authString
|
||||||
)
|
)
|
||||||
if let categories = categories {
|
if let categories = categories {
|
||||||
@@ -96,7 +93,7 @@ import UIKit
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getServer(store: Bool = false) async -> Bool {
|
func getServer(store: Bool = false) async -> Bool {
|
||||||
let (recipes, _) = await api.getCategory(
|
let (recipes, _) = await cookbookApi.getCategory(
|
||||||
auth: UserSettings.shared.authString,
|
auth: UserSettings.shared.authString,
|
||||||
named: categoryString
|
named: categoryString
|
||||||
)
|
)
|
||||||
@@ -158,7 +155,7 @@ import UIKit
|
|||||||
let recipes = await mainViewModel.getRecipes()
|
let recipes = await mainViewModel.getRecipes()
|
||||||
*/
|
*/
|
||||||
func getRecipes() async -> [Recipe] {
|
func getRecipes() async -> [Recipe] {
|
||||||
let (recipes, error) = await api.getRecipes(
|
let (recipes, error) = await cookbookApi.getRecipes(
|
||||||
auth: UserSettings.shared.authString
|
auth: UserSettings.shared.authString
|
||||||
)
|
)
|
||||||
if let recipes = recipes {
|
if let recipes = recipes {
|
||||||
@@ -198,7 +195,7 @@ import UIKit
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getServer() async -> RecipeDetail? {
|
func getServer() async -> RecipeDetail? {
|
||||||
let (recipe, error) = await api.getRecipe(
|
let (recipe, error) = await cookbookApi.getRecipe(
|
||||||
auth: UserSettings.shared.authString,
|
auth: UserSettings.shared.authString,
|
||||||
id: id
|
id: id
|
||||||
)
|
)
|
||||||
@@ -291,7 +288,7 @@ import UIKit
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getServer() async -> UIImage? {
|
func getServer() async -> UIImage? {
|
||||||
let (image, _) = await api.getImage(
|
let (image, _) = await cookbookApi.getImage(
|
||||||
auth: UserSettings.shared.authString,
|
auth: UserSettings.shared.authString,
|
||||||
id: id,
|
id: id,
|
||||||
size: size
|
size: size
|
||||||
@@ -367,7 +364,7 @@ import UIKit
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getServer() async -> [RecipeKeyword]? {
|
func getServer() async -> [RecipeKeyword]? {
|
||||||
let (tags, _) = await api.getTags(
|
let (tags, _) = await cookbookApi.getTags(
|
||||||
auth: UserSettings.shared.authString
|
auth: UserSettings.shared.authString
|
||||||
)
|
)
|
||||||
return tags
|
return tags
|
||||||
@@ -420,7 +417,7 @@ import UIKit
|
|||||||
let requestResult = await mainViewModel.deleteRecipe(withId: 123, categoryName: "Desserts")
|
let requestResult = await mainViewModel.deleteRecipe(withId: 123, categoryName: "Desserts")
|
||||||
*/
|
*/
|
||||||
func deleteRecipe(withId id: Int, categoryName: String) async -> RequestAlert? {
|
func deleteRecipe(withId id: Int, categoryName: String) async -> RequestAlert? {
|
||||||
let (error) = await api.deleteRecipe(
|
let (error) = await cookbookApi.deleteRecipe(
|
||||||
auth: UserSettings.shared.authString,
|
auth: UserSettings.shared.authString,
|
||||||
id: id
|
id: id
|
||||||
)
|
)
|
||||||
@@ -451,7 +448,7 @@ import UIKit
|
|||||||
let isConnected = await mainViewModel.checkServerConnection()
|
let isConnected = await mainViewModel.checkServerConnection()
|
||||||
*/
|
*/
|
||||||
func checkServerConnection() async -> Bool {
|
func checkServerConnection() async -> Bool {
|
||||||
let (categories, _) = await api.getCategories(
|
let (categories, _) = await cookbookApi.getCategories(
|
||||||
auth: UserSettings.shared.authString
|
auth: UserSettings.shared.authString
|
||||||
)
|
)
|
||||||
if let categories = categories {
|
if let categories = categories {
|
||||||
@@ -480,12 +477,12 @@ import UIKit
|
|||||||
func uploadRecipe(recipeDetail: RecipeDetail, createNew: Bool) async -> RequestAlert? {
|
func uploadRecipe(recipeDetail: RecipeDetail, createNew: Bool) async -> RequestAlert? {
|
||||||
var error: NetworkError? = nil
|
var error: NetworkError? = nil
|
||||||
if createNew {
|
if createNew {
|
||||||
error = await api.createRecipe(
|
error = await cookbookApi.createRecipe(
|
||||||
auth: UserSettings.shared.authString,
|
auth: UserSettings.shared.authString,
|
||||||
recipe: recipeDetail
|
recipe: recipeDetail
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
error = await api.updateRecipe(
|
error = await cookbookApi.updateRecipe(
|
||||||
auth: UserSettings.shared.authString,
|
auth: UserSettings.shared.authString,
|
||||||
recipe: recipeDetail
|
recipe: recipeDetail
|
||||||
)
|
)
|
||||||
@@ -498,7 +495,7 @@ import UIKit
|
|||||||
|
|
||||||
func importRecipe(url: String) async -> (RecipeDetail?, RequestAlert?) {
|
func importRecipe(url: String) async -> (RecipeDetail?, RequestAlert?) {
|
||||||
guard let data = JSONEncoder.safeEncode(RecipeImportRequest(url: url)) else { return (nil, .REQUEST_DROPPED) }
|
guard let data = JSONEncoder.safeEncode(RecipeImportRequest(url: url)) else { return (nil, .REQUEST_DROPPED) }
|
||||||
let (recipeDetail, error) = await api.importRecipe(
|
let (recipeDetail, error) = await cookbookApi.importRecipe(
|
||||||
auth: UserSettings.shared.authString,
|
auth: UserSettings.shared.authString,
|
||||||
data: data
|
data: data
|
||||||
)
|
)
|
||||||
@@ -16,7 +16,6 @@ struct ApiRequest {
|
|||||||
let body: Data?
|
let body: Data?
|
||||||
|
|
||||||
/// The path to the Cookbook application on the nextcloud server.
|
/// The path to the Cookbook application on the nextcloud server.
|
||||||
let cookbookPath = "/index.php/apps/cookbook"
|
|
||||||
|
|
||||||
init(
|
init(
|
||||||
path: String,
|
path: String,
|
||||||
@@ -32,11 +31,11 @@ struct ApiRequest {
|
|||||||
self.body = body
|
self.body = body
|
||||||
}
|
}
|
||||||
|
|
||||||
func send() async -> (Data?, NetworkError?) {
|
func send(pathCompletion: Bool = true) async -> (Data?, NetworkError?) {
|
||||||
Logger.network.debug("\(method.rawValue) \(path) sending ...")
|
Logger.network.debug("\(method.rawValue) \(path) sending ...")
|
||||||
|
|
||||||
// Prepare URL
|
// Prepare URL
|
||||||
let urlString = UserSettings.shared.serverProtocol + UserSettings.shared.serverAddress + cookbookPath + path
|
let urlString = pathCompletion ? UserSettings.shared.serverProtocol + UserSettings.shared.serverAddress + path : path
|
||||||
print("Full path: \(urlString)")
|
print("Full path: \(urlString)")
|
||||||
//Logger.network.debug("Full path: \(urlString)")
|
//Logger.network.debug("Full path: \(urlString)")
|
||||||
guard let urlStringSanitized = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return (nil, .unknownError) }
|
guard let urlStringSanitized = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return (nil, .unknownError) }
|
||||||
@@ -78,9 +77,10 @@ struct ApiRequest {
|
|||||||
return (nil, error)
|
return (nil, error)
|
||||||
}
|
}
|
||||||
if let data = data {
|
if let data = data {
|
||||||
print(data, String(data: data, encoding: .utf8))
|
print(data, String(data: data, encoding: .utf8) as Any)
|
||||||
|
return (data, nil)
|
||||||
}
|
}
|
||||||
return (data!, nil)
|
return (nil, .unknownError)
|
||||||
} catch {
|
} catch {
|
||||||
let error = decodeURLResponse(response: response as? HTTPURLResponse)
|
let error = decodeURLResponse(response: response as? HTTPURLResponse)
|
||||||
Logger.network.debug("\(method.rawValue) \(path) FAILURE: \(error.debugDescription)")
|
Logger.network.debug("\(method.rawValue) \(path) FAILURE: \(error.debugDescription)")
|
||||||
@@ -10,7 +10,24 @@ import OSLog
|
|||||||
import UIKit
|
import UIKit
|
||||||
|
|
||||||
|
|
||||||
|
/// The Cookbook API class used for requests to the Nextcloud Cookbook service.
|
||||||
|
let cookbookApi: CookbookApi.Type = {
|
||||||
|
switch UserSettings.shared.cookbookApiVersion {
|
||||||
|
case .v1:
|
||||||
|
return CookbookApiV1.self
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
/// The Cookbook API version.
|
||||||
|
enum CookbookApiVersion: String {
|
||||||
|
case v1 = "v1"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// A protocol defining common API endpoints that are likely to remain the same over future Cookbook API versions.
|
||||||
protocol CookbookApi {
|
protocol CookbookApi {
|
||||||
|
static var basePath: String { get }
|
||||||
|
|
||||||
/// Not implemented yet.
|
/// Not implemented yet.
|
||||||
static func importRecipe(
|
static func importRecipe(
|
||||||
auth: String,
|
auth: String,
|
||||||
|
|||||||
@@ -10,9 +10,11 @@ import UIKit
|
|||||||
|
|
||||||
|
|
||||||
class CookbookApiV1: CookbookApi {
|
class CookbookApiV1: CookbookApi {
|
||||||
|
static let basePath: String = "/index.php/apps/cookbook/api/v1"
|
||||||
|
|
||||||
static func importRecipe(auth: String, data: Data) async -> (RecipeDetail?, NetworkError?) {
|
static func importRecipe(auth: String, data: Data) async -> (RecipeDetail?, NetworkError?) {
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/import",
|
path: basePath + "/import",
|
||||||
method: .POST,
|
method: .POST,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON), HeaderField.contentType(value: .JSON)]
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON), HeaderField.contentType(value: .JSON)]
|
||||||
@@ -26,7 +28,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
static func getImage(auth: String, id: Int, size: RecipeImage.RecipeImageSize) async -> (UIImage?, NetworkError?) {
|
static func getImage(auth: String, id: Int, size: RecipeImage.RecipeImageSize) async -> (UIImage?, NetworkError?) {
|
||||||
let imageSize = (size == .FULL ? "full" : "thumb")
|
let imageSize = (size == .FULL ? "full" : "thumb")
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/recipes/\(id)/image?size=\(imageSize)",
|
path: basePath + "/recipes/\(id)/image?size=\(imageSize)",
|
||||||
method: .GET,
|
method: .GET,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .IMAGE)]
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .IMAGE)]
|
||||||
@@ -39,7 +41,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
|
|
||||||
static func getRecipes(auth: String) async -> ([Recipe]?, NetworkError?) {
|
static func getRecipes(auth: String) async -> ([Recipe]?, NetworkError?) {
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/recipes",
|
path: basePath + "/recipes",
|
||||||
method: .GET,
|
method: .GET,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
||||||
@@ -56,7 +58,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/recipes",
|
path: basePath + "/recipes",
|
||||||
method: .POST,
|
method: .POST,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON), HeaderField.contentType(value: .JSON)],
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON), HeaderField.contentType(value: .JSON)],
|
||||||
@@ -80,7 +82,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
|
|
||||||
static func getRecipe(auth: String, id: Int) async -> (RecipeDetail?, NetworkError?) {
|
static func getRecipe(auth: String, id: Int) async -> (RecipeDetail?, NetworkError?) {
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/recipes/\(id)",
|
path: basePath + "/recipes/\(id)",
|
||||||
method: .GET,
|
method: .GET,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
||||||
@@ -96,7 +98,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
return .dataError
|
return .dataError
|
||||||
}
|
}
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/recipes/\(recipe.id)",
|
path: basePath + "/recipes/\(recipe.id)",
|
||||||
method: .PUT,
|
method: .PUT,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON), HeaderField.contentType(value: .JSON)],
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON), HeaderField.contentType(value: .JSON)],
|
||||||
@@ -120,7 +122,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
|
|
||||||
static func deleteRecipe(auth: String, id: Int) async -> (NetworkError?) {
|
static func deleteRecipe(auth: String, id: Int) async -> (NetworkError?) {
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/recipes/\(id)",
|
path: basePath + "/recipes/\(id)",
|
||||||
method: .DELETE,
|
method: .DELETE,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
||||||
@@ -133,7 +135,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
|
|
||||||
static func getCategories(auth: String) async -> ([Category]?, NetworkError?) {
|
static func getCategories(auth: String) async -> ([Category]?, NetworkError?) {
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/categories",
|
path: basePath + "/categories",
|
||||||
method: .GET,
|
method: .GET,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
||||||
@@ -146,7 +148,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
|
|
||||||
static func getCategory(auth: String, named categoryName: String) async -> ([Recipe]?, NetworkError?) {
|
static func getCategory(auth: String, named categoryName: String) async -> ([Recipe]?, NetworkError?) {
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/category/\(categoryName)",
|
path: basePath + "/category/\(categoryName)",
|
||||||
method: .GET,
|
method: .GET,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
||||||
@@ -159,7 +161,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
|
|
||||||
static func renameCategory(auth: String, named categoryName: String, newName: String) async -> (NetworkError?) {
|
static func renameCategory(auth: String, named categoryName: String, newName: String) async -> (NetworkError?) {
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/category/\(categoryName)",
|
path: basePath + "/category/\(categoryName)",
|
||||||
method: .PUT,
|
method: .PUT,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
||||||
@@ -172,7 +174,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
|
|
||||||
static func getTags(auth: String) async -> ([RecipeKeyword]?, NetworkError?) {
|
static func getTags(auth: String) async -> ([RecipeKeyword]?, NetworkError?) {
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/keywords",
|
path: basePath + "/keywords",
|
||||||
method: .GET,
|
method: .GET,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
||||||
@@ -185,7 +187,7 @@ class CookbookApiV1: CookbookApi {
|
|||||||
|
|
||||||
static func getRecipesTagged(auth: String, keyword: String) async -> ([Recipe]?, NetworkError?) {
|
static func getRecipesTagged(auth: String, keyword: String) async -> ([Recipe]?, NetworkError?) {
|
||||||
let request = ApiRequest(
|
let request = ApiRequest(
|
||||||
path: "/api/v1/tags/\(keyword)",
|
path: basePath + "/tags/\(keyword)",
|
||||||
method: .GET,
|
method: .GET,
|
||||||
authString: auth,
|
authString: auth,
|
||||||
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
||||||
|
|||||||
@@ -6,7 +6,117 @@
|
|||||||
//
|
//
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// The `NextcloudApi` class provides functionalities to interact with the Nextcloud API, particularly for user authentication.
|
||||||
class NextcloudApi {
|
class NextcloudApi {
|
||||||
|
|
||||||
|
/// Initiates the login process with Nextcloud using the Login Flow v2.
|
||||||
|
///
|
||||||
|
/// This static function sends a POST request to the Nextcloud server to obtain a `LoginV2Request` object.
|
||||||
|
/// The object contains necessary details for the second step of the authentication process.
|
||||||
|
///
|
||||||
|
/// - Returns: A tuple containing an optional `LoginV2Request` and an optional `NetworkError`.
|
||||||
|
/// - `LoginV2Request?`: An object containing the necessary information for the second step of the login process, if successful.
|
||||||
|
/// - `NetworkError?`: An error encountered during the network request, if any.
|
||||||
|
|
||||||
|
static func loginV2Request() async -> (LoginV2Request?, NetworkError?) {
|
||||||
|
let path = UserSettings.shared.serverProtocol + UserSettings.shared.serverAddress
|
||||||
|
let request = ApiRequest(
|
||||||
|
path: path + "/index.php/login/v2",
|
||||||
|
method: .POST
|
||||||
|
)
|
||||||
|
|
||||||
|
let (data, error) = await request.send(pathCompletion: false)
|
||||||
|
|
||||||
|
if let error = error {
|
||||||
|
return (nil, error)
|
||||||
|
}
|
||||||
|
guard let data = data else {
|
||||||
|
return (nil, NetworkError.dataError)
|
||||||
|
}
|
||||||
|
guard let loginRequest: LoginV2Request = JSONDecoder.safeDecode(data) else {
|
||||||
|
return (nil, NetworkError.decodingFailed)
|
||||||
|
}
|
||||||
|
return (loginRequest, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Completes the user authentication process with Nextcloud using the Login Flow v2.
|
||||||
|
///
|
||||||
|
/// This static function sends a POST request to the Nextcloud server with the login token obtained from `loginV2Request`.
|
||||||
|
/// On successful validation of the token, it returns a `LoginV2Response` object, completing the user login.
|
||||||
|
///
|
||||||
|
/// - Parameter req: A `LoginV2Request` object containing the token and endpoint information for the authentication request.
|
||||||
|
///
|
||||||
|
/// - Returns: A tuple containing an optional `LoginV2Response` and an optional `NetworkError`.
|
||||||
|
/// - `LoginV2Response?`: An object representing the response of the login process, if successful.
|
||||||
|
/// - `NetworkError?`: An error encountered during the network request, if any.
|
||||||
|
|
||||||
|
static func loginV2Response(req: LoginV2Request) async -> (LoginV2Response?, NetworkError?) {
|
||||||
|
let request = ApiRequest(
|
||||||
|
path: req.poll.endpoint,
|
||||||
|
method: .POST,
|
||||||
|
headerFields: [
|
||||||
|
HeaderField.ocsRequest(value: true),
|
||||||
|
HeaderField.accept(value: .JSON),
|
||||||
|
HeaderField.contentType(value: .FORM)
|
||||||
|
],
|
||||||
|
body: "token=\(req.poll.token)".data(using: .utf8)
|
||||||
|
)
|
||||||
|
let (data, error) = await request.send(pathCompletion: false)
|
||||||
|
|
||||||
|
if let error = error {
|
||||||
|
return (nil, error)
|
||||||
|
}
|
||||||
|
guard let data = data else {
|
||||||
|
return (nil, NetworkError.dataError)
|
||||||
|
}
|
||||||
|
guard let loginResponse: LoginV2Response = JSONDecoder.safeDecode(data) else {
|
||||||
|
return (nil, NetworkError.decodingFailed)
|
||||||
|
}
|
||||||
|
return (loginResponse, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func getAvatar() async -> (UIImage?, NetworkError?) {
|
||||||
|
let request = ApiRequest(
|
||||||
|
path: "/index.php/avatar/\(UserSettings.shared.username)/100",
|
||||||
|
method: .GET,
|
||||||
|
authString: UserSettings.shared.authString,
|
||||||
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .IMAGE)]
|
||||||
|
)
|
||||||
|
|
||||||
|
let (data, error) = await request.send()
|
||||||
|
guard let data = data else { return (nil, error) }
|
||||||
|
return (UIImage(data: data), error)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func getHoverCard() async -> (UserData?, NetworkError?) {
|
||||||
|
let request = ApiRequest(
|
||||||
|
path: "/ocs/v2.php/hovercard/v1/\(UserSettings.shared.username)",
|
||||||
|
method: .GET,
|
||||||
|
authString: UserSettings.shared.authString,
|
||||||
|
headerFields: [HeaderField.ocsRequest(value: true), HeaderField.accept(value: .JSON)]
|
||||||
|
)
|
||||||
|
|
||||||
|
let (data, error) = await request.send()
|
||||||
|
guard let data = data else { return (nil, error) }
|
||||||
|
do {
|
||||||
|
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
|
||||||
|
let data = (json?["ocs"] as? [String: Any])?["data"] as? [String: Any]
|
||||||
|
let userData = UserData(
|
||||||
|
userId: data?["userId"] as? String ?? "",
|
||||||
|
userDisplayName: data?["displayName"] as? String ?? ""
|
||||||
|
)
|
||||||
|
print(userData)
|
||||||
|
return (userData, nil)
|
||||||
|
} catch {
|
||||||
|
print(error.localizedDescription)
|
||||||
|
return (nil, NetworkError.decodingFailed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct UserData {
|
||||||
|
let userId: String
|
||||||
|
let userDisplayName: String
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,10 +6,13 @@
|
|||||||
//
|
//
|
||||||
|
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import SimilaritySearchKit
|
||||||
|
|
||||||
struct MainView: View {
|
struct MainView: View {
|
||||||
@StateObject var viewModel = AppState()
|
@StateObject var viewModel = AppState()
|
||||||
@StateObject var groceryList = GroceryList()
|
@StateObject var groceryList = GroceryList()
|
||||||
|
|
||||||
|
// Tab ViewModels
|
||||||
@StateObject var recipeViewModel = RecipeTabView.ViewModel()
|
@StateObject var recipeViewModel = RecipeTabView.ViewModel()
|
||||||
@StateObject var searchViewModel = SearchTabView.ViewModel()
|
@StateObject var searchViewModel = SearchTabView.ViewModel()
|
||||||
|
|
||||||
@@ -69,211 +72,3 @@ struct MainView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/*struct MainView: View {
|
|
||||||
@ObservedObject var viewModel: MainViewModel
|
|
||||||
@StateObject var userSettings: UserSettings = UserSettings.shared
|
|
||||||
|
|
||||||
@State private var selectedCategory: Category? = nil
|
|
||||||
@State private var showEditView: Bool = false
|
|
||||||
@State private var showSearchView: Bool = false
|
|
||||||
@State private var showSettingsView: Bool = false
|
|
||||||
@State private var serverConnection: Bool = false
|
|
||||||
@State private var showLoadingIndicator: Bool = false
|
|
||||||
|
|
||||||
|
|
||||||
var columns: [GridItem] = [GridItem(.adaptive(minimum: 150), spacing: 0)]
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
NavigationSplitView {
|
|
||||||
List(selection: $selectedCategory) {
|
|
||||||
// All recipes
|
|
||||||
NavigationLink {
|
|
||||||
RecipeSearchView(viewModel: viewModel)
|
|
||||||
} label: {
|
|
||||||
HStack(alignment: .center) {
|
|
||||||
Image(systemName: "magnifyingglass")
|
|
||||||
Text("Search")
|
|
||||||
.font(.system(size: 20, weight: .medium, design: .default))
|
|
||||||
}
|
|
||||||
.padding(7)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Categories
|
|
||||||
ForEach(viewModel.categories) { category in
|
|
||||||
if category.recipe_count != 0 {
|
|
||||||
NavigationLink(value: category) {
|
|
||||||
HStack(alignment: .center) {
|
|
||||||
if selectedCategory != nil && category.name == selectedCategory!.name {
|
|
||||||
Image(systemName: "book")
|
|
||||||
} else {
|
|
||||||
Image(systemName: "book.closed.fill")
|
|
||||||
}
|
|
||||||
Text(category.name == "*" ? String(localized: "Other") : category.name)
|
|
||||||
.font(.system(size: 20, weight: .medium, design: .default))
|
|
||||||
Spacer()
|
|
||||||
Text("\(category.recipe_count)")
|
|
||||||
.font(.system(size: 15, weight: .bold, design: .default))
|
|
||||||
.foregroundStyle(Color.background)
|
|
||||||
.frame(width: 25, height: 25, alignment: .center)
|
|
||||||
.minimumScaleFactor(0.5)
|
|
||||||
.background {
|
|
||||||
Circle()
|
|
||||||
.foregroundStyle(Color.secondary)
|
|
||||||
}
|
|
||||||
}.padding(7)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.navigationTitle("Cookbooks")
|
|
||||||
.navigationDestination(isPresented: $showSettingsView) {
|
|
||||||
SettingsView(viewModel: viewModel)
|
|
||||||
}
|
|
||||||
.navigationDestination(isPresented: $showSearchView) {
|
|
||||||
RecipeSearchView(viewModel: viewModel)
|
|
||||||
}
|
|
||||||
.toolbar {
|
|
||||||
MainViewToolBar(
|
|
||||||
viewModel: viewModel,
|
|
||||||
showEditView: $showEditView,
|
|
||||||
showSettingsView: $showSettingsView,
|
|
||||||
serverConnection: $serverConnection,
|
|
||||||
showLoadingIndicator: $showLoadingIndicator
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} detail: {
|
|
||||||
NavigationStack {
|
|
||||||
if let category = selectedCategory {
|
|
||||||
CategoryDetailView(
|
|
||||||
categoryName: category.name,
|
|
||||||
viewModel: viewModel,
|
|
||||||
showEditView: $showEditView
|
|
||||||
)
|
|
||||||
.id(category.id) // Workaround: This is needed to update the detail view when the selection changes
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.tint(.nextcloudBlue)
|
|
||||||
.sheet(isPresented: $showEditView) {
|
|
||||||
RecipeEditView(
|
|
||||||
viewModel:
|
|
||||||
RecipeEditViewModel(
|
|
||||||
mainViewModel: viewModel,
|
|
||||||
uploadNew: true
|
|
||||||
),
|
|
||||||
isPresented: $showEditView
|
|
||||||
)
|
|
||||||
}
|
|
||||||
.task {
|
|
||||||
showLoadingIndicator = true
|
|
||||||
self.serverConnection = await viewModel.checkServerConnection()
|
|
||||||
await viewModel.getCategories()
|
|
||||||
await viewModel.updateAllRecipeDetails()
|
|
||||||
|
|
||||||
// Open detail view for default category
|
|
||||||
if userSettings.defaultCategory != "" {
|
|
||||||
if let cat = viewModel.categories.first(where: { c in
|
|
||||||
if c.name == userSettings.defaultCategory {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}) {
|
|
||||||
self.selectedCategory = cat
|
|
||||||
}
|
|
||||||
}
|
|
||||||
showLoadingIndicator = false
|
|
||||||
}
|
|
||||||
.refreshable {
|
|
||||||
self.serverConnection = await viewModel.checkServerConnection()
|
|
||||||
await viewModel.getCategories()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
struct MainViewToolBar: ToolbarContent {
|
|
||||||
@ObservedObject var viewModel: MainViewModel
|
|
||||||
@Binding var showEditView: Bool
|
|
||||||
@Binding var showSettingsView: Bool
|
|
||||||
@Binding var serverConnection: Bool
|
|
||||||
@Binding var showLoadingIndicator: Bool
|
|
||||||
@State private var presentPopover: Bool = false
|
|
||||||
|
|
||||||
var body: some ToolbarContent {
|
|
||||||
// Top left menu toolbar item
|
|
||||||
ToolbarItem(placement: .topBarLeading) {
|
|
||||||
Menu {
|
|
||||||
Button {
|
|
||||||
self.showSettingsView = true
|
|
||||||
} label: {
|
|
||||||
Text("Settings")
|
|
||||||
Image(systemName: "gearshape")
|
|
||||||
}
|
|
||||||
Button {
|
|
||||||
Task {
|
|
||||||
showLoadingIndicator = true
|
|
||||||
UserSettings.shared.lastUpdate = Date.distantPast
|
|
||||||
await viewModel.getCategories()
|
|
||||||
for category in viewModel.categories {
|
|
||||||
await viewModel.getCategory(named: category.name, fetchMode: .preferServer)
|
|
||||||
}
|
|
||||||
await viewModel.updateAllRecipeDetails()
|
|
||||||
showLoadingIndicator = false
|
|
||||||
}
|
|
||||||
} label: {
|
|
||||||
Text("Refresh all")
|
|
||||||
Image(systemName: "icloud.and.arrow.down")
|
|
||||||
}
|
|
||||||
|
|
||||||
} label: {
|
|
||||||
Image(systemName: "ellipsis.circle")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Server connection indicator
|
|
||||||
ToolbarItem(placement: .topBarTrailing) {
|
|
||||||
Button {
|
|
||||||
print("Check server connection")
|
|
||||||
presentPopover = true
|
|
||||||
} label: {
|
|
||||||
if showLoadingIndicator {
|
|
||||||
ProgressView()
|
|
||||||
} else if serverConnection {
|
|
||||||
Image(systemName: "checkmark.icloud")
|
|
||||||
} else {
|
|
||||||
Image(systemName: "xmark.icloud")
|
|
||||||
}
|
|
||||||
}.popover(isPresented: $presentPopover) {
|
|
||||||
VStack(alignment: .leading) {
|
|
||||||
Text(serverConnection ? LocalizedStringKey("Connected to server.") : LocalizedStringKey("Unable to connect to server."))
|
|
||||||
.bold()
|
|
||||||
|
|
||||||
Text("Last updated: \(DateFormatter.utcToString(date: UserSettings.shared.lastUpdate))")
|
|
||||||
.font(.caption)
|
|
||||||
.foregroundStyle(Color.secondary)
|
|
||||||
}
|
|
||||||
.padding()
|
|
||||||
.presentationCompactAdaptation(.popover)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create new recipes
|
|
||||||
ToolbarItem(placement: .topBarTrailing) {
|
|
||||||
Button {
|
|
||||||
print("Add new recipe")
|
|
||||||
showEditView = true
|
|
||||||
} label: {
|
|
||||||
Image(systemName: "plus.circle.fill")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
*/
|
|
||||||
|
|||||||
@@ -87,44 +87,21 @@ struct TokenLoginView: View {
|
|||||||
showAlert = true
|
showAlert = true
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
let headerFields = [
|
|
||||||
HeaderField.ocsRequest(value: true),
|
|
||||||
]
|
|
||||||
let request = RequestWrapper.customRequest(
|
|
||||||
method: .GET,
|
|
||||||
path: .CATEGORIES,
|
|
||||||
headerFields: headerFields,
|
|
||||||
authenticate: true
|
|
||||||
)
|
|
||||||
|
|
||||||
var (data, error): (Data?, Error?) = (nil, nil)
|
UserSettings.shared.setAuthString()
|
||||||
do {
|
let (data, error) = await cookbookApi.getCategories(auth: UserSettings.shared.authString)
|
||||||
let loginString = "\(userSettings.username):\(userSettings.token)"
|
|
||||||
let loginData = loginString.data(using: String.Encoding.utf8)!
|
|
||||||
let authString = loginData.base64EncodedString()
|
|
||||||
DispatchQueue.main.async {
|
|
||||||
userSettings.authString = authString
|
|
||||||
}
|
|
||||||
(data, error) = try await NetworkHandler.sendHTTPRequest(
|
|
||||||
request,
|
|
||||||
hostPath: "https://\(userSettings.serverAddress)/index.php/apps/cookbook/api/v1/",
|
|
||||||
authString: authString
|
|
||||||
)
|
|
||||||
|
|
||||||
} catch {
|
if let error = error {
|
||||||
print("Error: ", error)
|
alertMessage = "Login failed. Please check your inputs and internet connection."
|
||||||
|
showAlert = true
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
guard let data = data else {
|
guard let data = data else {
|
||||||
alertMessage = "Login failed. Please check your inputs."
|
alertMessage = "Login failed. Please check your inputs."
|
||||||
showAlert = true
|
showAlert = true
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if let testRequest: [Category] = JSONDecoder.safeDecode(data) {
|
|
||||||
print("validationResponse: \(testRequest)")
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
alertMessage = "Login failed. Please check your inputs and internet connection."
|
|
||||||
showAlert = true
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,8 +35,6 @@ struct V2LoginView: View {
|
|||||||
@State var loginStage: V2LoginStage = .login
|
@State var loginStage: V2LoginStage = .login
|
||||||
@State var loginRequest: LoginV2Request? = nil
|
@State var loginRequest: LoginV2Request? = nil
|
||||||
|
|
||||||
@State var userSettings = UserSettings.shared
|
|
||||||
|
|
||||||
// TextField handling
|
// TextField handling
|
||||||
enum Field {
|
enum Field {
|
||||||
case server
|
case server
|
||||||
@@ -73,14 +71,18 @@ struct V2LoginView: View {
|
|||||||
|
|
||||||
HStack {
|
HStack {
|
||||||
Button {
|
Button {
|
||||||
if userSettings.serverAddress == "" {
|
if UserSettings.shared.serverAddress == "" {
|
||||||
alertMessage = "Please enter a valid server address."
|
alertMessage = "Please enter a valid server address."
|
||||||
showAlert = true
|
showAlert = true
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
Task {
|
Task {
|
||||||
await sendLoginV2Request()
|
let error = await sendLoginV2Request()
|
||||||
|
if let error = error {
|
||||||
|
alertMessage = "A network error occured (\(error.rawValue))."
|
||||||
|
showAlert = true
|
||||||
|
}
|
||||||
if let loginRequest = loginRequest {
|
if let loginRequest = loginRequest {
|
||||||
await UIApplication.shared.open(URL(string: loginRequest.login)!)
|
await UIApplication.shared.open(URL(string: loginRequest.login)!)
|
||||||
} else {
|
} else {
|
||||||
@@ -107,20 +109,27 @@ struct V2LoginView: View {
|
|||||||
Button {
|
Button {
|
||||||
// fetch login v2 response
|
// fetch login v2 response
|
||||||
Task {
|
Task {
|
||||||
guard let res = await fetchLoginV2Response() else {
|
let (response, error) = await fetchLoginV2Response()
|
||||||
|
|
||||||
|
if let error = error {
|
||||||
|
alertMessage = "Login failed. Please login via the browser and try again. (\(error.rawValue))"
|
||||||
|
showAlert = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard let response = response else {
|
||||||
alertMessage = "Login failed. Please login via the browser and try again."
|
alertMessage = "Login failed. Please login via the browser and try again."
|
||||||
showAlert = true
|
showAlert = true
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
print("Login successfull for user \(res.loginName)!")
|
print("Login successful for user \(response.loginName)!")
|
||||||
self.userSettings.username = res.loginName
|
UserSettings.shared.username = response.loginName
|
||||||
self.userSettings.token = res.appPassword
|
UserSettings.shared.token = response.appPassword
|
||||||
let loginString = "\(userSettings.username):\(userSettings.token)"
|
let loginString = "\(UserSettings.shared.username):\(UserSettings.shared.token)"
|
||||||
let loginData = loginString.data(using: String.Encoding.utf8)!
|
let loginData = loginString.data(using: String.Encoding.utf8)!
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
userSettings.authString = loginData.base64EncodedString()
|
UserSettings.shared.authString = loginData.base64EncodedString()
|
||||||
}
|
}
|
||||||
self.userSettings.onboarding = false
|
UserSettings.shared.onboarding = false
|
||||||
}
|
}
|
||||||
} label: {
|
} label: {
|
||||||
Text("Validate")
|
Text("Validate")
|
||||||
@@ -141,64 +150,14 @@ struct V2LoginView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func sendLoginV2Request() async {
|
func sendLoginV2Request() async -> NetworkError? {
|
||||||
let hostPath = "https://\(userSettings.serverAddress)"
|
let (req, error) = await NextcloudApi.loginV2Request()
|
||||||
let headerFields: [HeaderField] = [
|
self.loginRequest = req
|
||||||
//HeaderField.ocsRequest(value: true),
|
return error
|
||||||
//HeaderField.accept(value: .JSON)
|
|
||||||
]
|
|
||||||
let request = RequestWrapper.customRequest(
|
|
||||||
method: .POST,
|
|
||||||
path: .LOGINV2REQ,
|
|
||||||
headerFields: headerFields
|
|
||||||
)
|
|
||||||
do {
|
|
||||||
let (data, _): (Data?, Error?) = try await NetworkHandler.sendHTTPRequest(
|
|
||||||
request,
|
|
||||||
hostPath: hostPath,
|
|
||||||
authString: nil
|
|
||||||
)
|
|
||||||
|
|
||||||
guard let data = data else { return }
|
|
||||||
print("Data: \(data)")
|
|
||||||
let loginReq: LoginV2Request? = JSONDecoder.safeDecode(data)
|
|
||||||
self.loginRequest = loginReq
|
|
||||||
} catch {
|
|
||||||
print("Could not establish communication with the server.")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
func fetchLoginV2Response() async -> (LoginV2Response?, NetworkError?) {
|
||||||
|
guard let loginRequest = loginRequest else { return (nil, .parametersNil) }
|
||||||
func fetchLoginV2Response() async -> LoginV2Response? {
|
return await NextcloudApi.loginV2Response(req: loginRequest)
|
||||||
guard let loginRequest = loginRequest else { return nil }
|
|
||||||
let headerFields = [
|
|
||||||
HeaderField.ocsRequest(value: true),
|
|
||||||
HeaderField.accept(value: .JSON),
|
|
||||||
HeaderField.contentType(value: .FORM)
|
|
||||||
]
|
|
||||||
let request = RequestWrapper.customRequest(
|
|
||||||
method: .POST,
|
|
||||||
path: .NONE,
|
|
||||||
headerFields: headerFields,
|
|
||||||
body: "token=\(loginRequest.poll.token)".data(using: .utf8),
|
|
||||||
authenticate: false
|
|
||||||
)
|
|
||||||
|
|
||||||
var (data, error): (Data?, Error?) = (nil, nil)
|
|
||||||
do {
|
|
||||||
(data, error) = try await NetworkHandler.sendHTTPRequest(
|
|
||||||
request,
|
|
||||||
hostPath: loginRequest.poll.endpoint,
|
|
||||||
authString: nil
|
|
||||||
)
|
|
||||||
} catch {
|
|
||||||
print("Error: ", error)
|
|
||||||
}
|
|
||||||
guard let data = data else { return nil }
|
|
||||||
if let loginRes: LoginV2Response = JSONDecoder.safeDecode(data) {
|
|
||||||
return loginRes
|
|
||||||
}
|
|
||||||
print("Could not decode.")
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,22 +15,33 @@ struct CategoryDetailView: View {
|
|||||||
@State var searchText: String = ""
|
@State var searchText: String = ""
|
||||||
@ObservedObject var viewModel: AppState
|
@ObservedObject var viewModel: AppState
|
||||||
@Binding var showEditView: Bool
|
@Binding var showEditView: Bool
|
||||||
|
@State var selectedRecipe: Recipe? = nil
|
||||||
|
@State var presentRecipeView: Bool = false
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
ScrollView(showsIndicators: false) {
|
ScrollView(showsIndicators: false) {
|
||||||
LazyVStack {
|
LazyVStack {
|
||||||
ForEach(recipesFiltered(), id: \.recipe_id) { recipe in
|
ForEach(recipesFiltered(), id: \.recipe_id) { recipe in
|
||||||
NavigationLink(value: recipe) {
|
//NavigationLink(value: recipe) {
|
||||||
RecipeCardView(viewModel: viewModel, recipe: recipe)
|
RecipeCardView(viewModel: viewModel, recipe: recipe)
|
||||||
.shadow(radius: 2)
|
.shadow(radius: 2)
|
||||||
}
|
|
||||||
.buttonStyle(.plain)
|
//}
|
||||||
|
//.buttonStyle(.plain)
|
||||||
|
.onTapGesture {
|
||||||
|
selectedRecipe = recipe
|
||||||
|
presentRecipeView = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
.fullScreenCover(isPresented: $presentRecipeView) {
|
||||||
|
RecipeDetailView(viewModel: viewModel, recipe: selectedRecipe!)
|
||||||
|
}
|
||||||
|
/*
|
||||||
.navigationDestination(for: Recipe.self) { recipe in
|
.navigationDestination(for: Recipe.self) { recipe in
|
||||||
RecipeDetailView(viewModel: viewModel, recipe: recipe)
|
RecipeDetailView(viewModel: viewModel, recipe: recipe)
|
||||||
}
|
}*/
|
||||||
.navigationTitle(categoryName == "*" ? String(localized: "Other") : categoryName)
|
.navigationTitle(categoryName == "*" ? String(localized: "Other") : categoryName)
|
||||||
.toolbar {
|
.toolbar {
|
||||||
ToolbarItem(placement: .topBarTrailing) {
|
ToolbarItem(placement: .topBarTrailing) {
|
||||||
|
|||||||
@@ -11,18 +11,40 @@ import SwiftUI
|
|||||||
|
|
||||||
|
|
||||||
struct SettingsView: View {
|
struct SettingsView: View {
|
||||||
@EnvironmentObject var viewModel: AppState
|
@EnvironmentObject var appState: AppState
|
||||||
@ObservedObject var userSettings = UserSettings.shared
|
@ObservedObject var userSettings = UserSettings.shared
|
||||||
|
@ObservedObject var viewModel = ViewModel()
|
||||||
@State fileprivate var alertType: SettingsAlert = .NONE
|
|
||||||
@State var showAlert: Bool = false
|
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
Form {
|
Form {
|
||||||
|
HStack(alignment: .center) {
|
||||||
|
if let avatarImage = viewModel.avatarImage {
|
||||||
|
Image(uiImage: avatarImage)
|
||||||
|
.resizable()
|
||||||
|
.clipShape(Circle())
|
||||||
|
.frame(width: 100, height: 100)
|
||||||
|
|
||||||
|
}
|
||||||
|
if let userData = viewModel.userData {
|
||||||
|
VStack(alignment: .leading) {
|
||||||
|
Text(userData.userDisplayName)
|
||||||
|
.font(.title)
|
||||||
|
.padding(.leading)
|
||||||
|
Text("Username: \(userData.userId)")
|
||||||
|
.font(.subheadline)
|
||||||
|
.padding(.leading)
|
||||||
|
|
||||||
|
|
||||||
|
// TODO: Add actions
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
|
|
||||||
Section {
|
Section {
|
||||||
Picker("Select a default cookbook", selection: $userSettings.defaultCategory) {
|
Picker("Select a default cookbook", selection: $userSettings.defaultCategory) {
|
||||||
Text("None").tag("None")
|
Text("None").tag("None")
|
||||||
ForEach(viewModel.categories, id: \.name) { category in
|
ForEach(appState.categories, id: \.name) { category in
|
||||||
Text(category.name == "*" ? "Other" : category.name).tag(category)
|
Text(category.name == "*" ? "Other" : category.name).tag(category)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -100,16 +122,16 @@ struct SettingsView: View {
|
|||||||
Section {
|
Section {
|
||||||
Button("Log out") {
|
Button("Log out") {
|
||||||
print("Log out.")
|
print("Log out.")
|
||||||
alertType = .LOG_OUT
|
viewModel.alertType = .LOG_OUT
|
||||||
showAlert = true
|
viewModel.showAlert = true
|
||||||
|
|
||||||
}
|
}
|
||||||
.tint(.red)
|
.tint(.red)
|
||||||
|
|
||||||
Button("Delete local data") {
|
Button("Delete local data") {
|
||||||
print("Clear cache.")
|
print("Clear cache.")
|
||||||
alertType = .DELETE_CACHE
|
viewModel.alertType = .DELETE_CACHE
|
||||||
showAlert = true
|
viewModel.showAlert = true
|
||||||
}
|
}
|
||||||
.tint(.red)
|
.tint(.red)
|
||||||
|
|
||||||
@@ -136,24 +158,27 @@ struct SettingsView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.navigationTitle("Settings")
|
.navigationTitle("Settings")
|
||||||
.alert(alertType.getTitle(), isPresented: $showAlert) {
|
.alert(viewModel.alertType.getTitle(), isPresented: $viewModel.showAlert) {
|
||||||
Button("Cancel", role: .cancel) { }
|
Button("Cancel", role: .cancel) { }
|
||||||
if alertType == .LOG_OUT {
|
if viewModel.alertType == .LOG_OUT {
|
||||||
Button("Log out", role: .destructive) { logOut() }
|
Button("Log out", role: .destructive) { logOut() }
|
||||||
} else if alertType == .DELETE_CACHE {
|
} else if viewModel.alertType == .DELETE_CACHE {
|
||||||
Button("Delete", role: .destructive) { deleteCache() }
|
Button("Delete", role: .destructive) { deleteCache() }
|
||||||
}
|
}
|
||||||
} message: {
|
} message: {
|
||||||
Text(alertType.getMessage())
|
Text(viewModel.alertType.getMessage())
|
||||||
}
|
}
|
||||||
.onDisappear {
|
.onDisappear {
|
||||||
Task {
|
Task {
|
||||||
userSettings.lastUpdate = .distantPast
|
userSettings.lastUpdate = .distantPast
|
||||||
await viewModel.updateAllRecipeDetails()
|
await appState.updateAllRecipeDetails()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.task {
|
||||||
|
await viewModel.getUserData()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func logOut() {
|
func logOut() {
|
||||||
@@ -161,18 +186,24 @@ struct SettingsView: View {
|
|||||||
userSettings.username = ""
|
userSettings.username = ""
|
||||||
userSettings.token = ""
|
userSettings.token = ""
|
||||||
userSettings.authString = ""
|
userSettings.authString = ""
|
||||||
viewModel.deleteAllData()
|
appState.deleteAllData()
|
||||||
userSettings.onboarding = true
|
userSettings.onboarding = true
|
||||||
}
|
}
|
||||||
|
|
||||||
func deleteCache() {
|
func deleteCache() {
|
||||||
viewModel.deleteAllData()
|
appState.deleteAllData()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extension SettingsView {
|
||||||
|
class ViewModel: ObservableObject {
|
||||||
|
@Published var avatarImage: UIImage? = nil
|
||||||
|
@Published var userData: UserData? = nil
|
||||||
|
|
||||||
|
@Published var showAlert: Bool = false
|
||||||
|
fileprivate var alertType: SettingsAlert = .NONE
|
||||||
|
|
||||||
fileprivate enum SettingsAlert {
|
enum SettingsAlert {
|
||||||
case LOG_OUT,
|
case LOG_OUT,
|
||||||
DELETE_CACHE,
|
DELETE_CACHE,
|
||||||
NONE
|
NONE
|
||||||
@@ -193,3 +224,16 @@ fileprivate enum SettingsAlert {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getUserData() async {
|
||||||
|
let (data, _) = await NextcloudApi.getAvatar()
|
||||||
|
avatarImage = data
|
||||||
|
|
||||||
|
let (userData, _) = await NextcloudApi.getHoverCard()
|
||||||
|
self.userData = userData
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -111,6 +111,8 @@ fileprivate struct EmptyGroceryListView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Grocery List Logic
|
||||||
|
|
||||||
|
|
||||||
class GroceryRecipe: Identifiable, Codable {
|
class GroceryRecipe: Identifiable, Codable {
|
||||||
let name: String
|
let name: String
|
||||||
|
|||||||
@@ -95,6 +95,7 @@ struct RecipeTabView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
fileprivate struct RecipeTabViewToolBar: ToolbarContent {
|
fileprivate struct RecipeTabViewToolBar: ToolbarContent {
|
||||||
@EnvironmentObject var mainViewModel: AppState
|
@EnvironmentObject var mainViewModel: AppState
|
||||||
@EnvironmentObject var viewModel: RecipeTabView.ViewModel
|
@EnvironmentObject var viewModel: RecipeTabView.ViewModel
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import SimilaritySearchKit
|
||||||
|
|
||||||
struct SearchTabView: View {
|
struct SearchTabView: View {
|
||||||
@EnvironmentObject var viewModel: SearchTabView.ViewModel
|
@EnvironmentObject var viewModel: SearchTabView.ViewModel
|
||||||
@@ -17,6 +17,13 @@ struct SearchTabView: View {
|
|||||||
NavigationStack {
|
NavigationStack {
|
||||||
VStack {
|
VStack {
|
||||||
ScrollView(showsIndicators: false) {
|
ScrollView(showsIndicators: false) {
|
||||||
|
/*
|
||||||
|
Picker("Topping", selection: $viewModel.searchMode) {
|
||||||
|
ForEach(ViewModel.SearchMode.allCases, id: \.self) { mode in
|
||||||
|
Text(mode.rawValue)
|
||||||
|
}
|
||||||
|
}.pickerStyle(.segmented)
|
||||||
|
*/
|
||||||
LazyVStack {
|
LazyVStack {
|
||||||
ForEach(viewModel.recipesFiltered(), id: \.recipe_id) { recipe in
|
ForEach(viewModel.recipesFiltered(), id: \.recipe_id) { recipe in
|
||||||
NavigationLink(value: recipe) {
|
NavigationLink(value: recipe) {
|
||||||
@@ -47,13 +54,26 @@ struct SearchTabView: View {
|
|||||||
class ViewModel: ObservableObject {
|
class ViewModel: ObservableObject {
|
||||||
@Published var allRecipes: [Recipe] = []
|
@Published var allRecipes: [Recipe] = []
|
||||||
@Published var searchText: String = ""
|
@Published var searchText: String = ""
|
||||||
|
@Published var searchMode: SearchMode = .name
|
||||||
|
|
||||||
|
var similarityIndex: SimilarityIndex? = nil
|
||||||
|
var similaritySearchResults: [SearchResult] = []
|
||||||
|
|
||||||
|
enum SearchMode: String, CaseIterable {
|
||||||
|
case name = "Name & Keywords", ingredient = "Ingredients"
|
||||||
|
}
|
||||||
|
|
||||||
func recipesFiltered() -> [Recipe] {
|
func recipesFiltered() -> [Recipe] {
|
||||||
|
if searchMode == .name {
|
||||||
guard searchText != "" else { return allRecipes }
|
guard searchText != "" else { return allRecipes }
|
||||||
return allRecipes.filter { recipe in
|
return allRecipes.filter { recipe in
|
||||||
recipe.name.lowercased().contains(searchText.lowercased()) || // check name for occurence of search term
|
recipe.name.lowercased().contains(searchText.lowercased()) || // check name for occurence of search term
|
||||||
(recipe.keywords != nil && recipe.keywords!.lowercased().contains(searchText.lowercased())) // check keywords for search term
|
(recipe.keywords != nil && recipe.keywords!.lowercased().contains(searchText.lowercased())) // check keywords for search term
|
||||||
}
|
}
|
||||||
|
} else if searchMode == .ingredient {
|
||||||
|
// TODO: Fuzzy ingredient search
|
||||||
|
}
|
||||||
|
return []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user