NCAutoUploadModel.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. //
  2. // NCAutoUploadModel.swift
  3. // Nextcloud
  4. //
  5. // Created by Aditya Tyagi on 08/03/24.
  6. // Created by Marino Faggiana on 30/05/24.
  7. // Copyright © 2024 Marino Faggiana. All rights reserved.
  8. //
  9. // Author Aditya Tyagi <adityagi02@yahoo.com>
  10. //
  11. // This program is free software: you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published by
  13. // the Free Software Foundation, either version 3 of the License, or
  14. // (at your option) any later version.
  15. //
  16. // This program is distributed in the hope that it will be useful,
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. // GNU General Public License for more details.
  20. //
  21. // You should have received a copy of the GNU General Public License
  22. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. //
  24. import Foundation
  25. import UIKit
  26. import Photos
  27. import NextcloudKit
  28. /// A model that allows the user to configure the `auto upload settings for Nextcloud`
  29. class NCAutoUploadModel: ObservableObject, ViewOnAppearHandling {
  30. /// A state variable that indicates whether auto upload is enabled or not
  31. @Published var autoUpload: Bool = false
  32. /// A state variable that indicates whether to open NCSelect View or not
  33. @Published var autoUploadFolder: Bool = false
  34. /// A state variable that indicates whether auto upload for photos is enabled or not
  35. @Published var autoUploadImage: Bool = false
  36. /// A state variable that indicates whether auto upload for photos is restricted to Wi-Fi only or not
  37. @Published var autoUploadWWAnPhoto: Bool = false
  38. /// A state variable that indicates whether auto upload for videos is enabled or not
  39. @Published var autoUploadVideo: Bool = false
  40. /// A state variable that indicates whether auto upload for videos is enabled or not
  41. @Published var autoUploadWWAnVideo: Bool = false
  42. /// A state variable that indicates whether only assets marked as favorites should be uploaded
  43. @Published var autoUploadFavoritesOnly: Bool = false
  44. /// A state variable that indicates whether auto upload for full resolution photos is enabled or not
  45. @Published var autoUploadFull: Bool = false
  46. /// A state variable that indicates whether auto upload creates subfolders based on date or not
  47. @Published var autoUploadCreateSubfolder: Bool = false
  48. /// A state variable that indicates the granularity of the subfolders, either daily, monthly, or yearly
  49. @Published var autoUploadSubfolderGranularity: Granularity = .monthly
  50. /// A state variable that shows error in view in case of an error
  51. @Published var showErrorAlert: Bool = false
  52. @Published var sectionName = ""
  53. @Published var isAuthorized: Bool = false
  54. /// A string variable that contains error text
  55. @Published var error: String = ""
  56. let database = NCManageDatabase.shared
  57. @Published var autoUploadPath = "\(NCManageDatabase.shared.getAccountAutoUploadFileName())"
  58. /// Root View Controller
  59. var controller: NCMainTabBarController?
  60. /// A variable user for change the auto upload directory
  61. var serverUrl: String = ""
  62. /// Get session
  63. var session: NCSession.Session {
  64. NCSession.shared.getSession(controller: controller)
  65. }
  66. /// Initialization code to set up the ViewModel with the active account
  67. init(controller: NCMainTabBarController?) {
  68. self.controller = controller
  69. onViewAppear()
  70. }
  71. /// Triggered when the view appears.
  72. func onViewAppear() {
  73. if let tableAccount = self.database.getTableAccount(predicate: NSPredicate(format: "account == %@", session.account)) {
  74. autoUpload = tableAccount.autoUpload
  75. autoUploadImage = tableAccount.autoUploadImage
  76. autoUploadWWAnPhoto = tableAccount.autoUploadWWAnPhoto
  77. autoUploadVideo = tableAccount.autoUploadVideo
  78. autoUploadWWAnVideo = tableAccount.autoUploadWWAnVideo
  79. autoUploadFavoritesOnly = tableAccount.autoUploadFavoritesOnly
  80. autoUploadFull = tableAccount.autoUploadFull
  81. autoUploadCreateSubfolder = tableAccount.autoUploadCreateSubfolder
  82. autoUploadSubfolderGranularity = Granularity(rawValue: tableAccount.autoUploadSubfolderGranularity) ?? .monthly
  83. }
  84. serverUrl = NCUtilityFileSystem().getHomeServer(session: session)
  85. if autoUpload {
  86. requestAuthorization { value in
  87. self.autoUpload = value
  88. self.updateAccountProperty(\.autoUpload, value: value)
  89. }
  90. }
  91. }
  92. // MARK: - All functions
  93. func requestAuthorization(completion: @escaping (Bool) -> Void = { _ in }) {
  94. PHPhotoLibrary.requestAuthorization { status in
  95. DispatchQueue.main.async {
  96. let value = (status == .authorized)
  97. if !value {
  98. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: NSLocalizedString("_access_photo_not_enabled_msg_", comment: ""), responseData: nil)
  99. NCContentPresenter().messageNotification("_error_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: .error)
  100. } else if UIApplication.shared.backgroundRefreshStatus != .available {
  101. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: NSLocalizedString("_access_background_app_refresh_denied_", comment: ""), responseData: nil)
  102. NCContentPresenter().messageNotification("_info_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: .info)
  103. }
  104. completion(value)
  105. }
  106. }
  107. }
  108. /// Updates the auto-upload setting.
  109. func handleAutoUploadChange(newValue: Bool) {
  110. if newValue {
  111. requestAuthorization { value in
  112. self.autoUpload = value
  113. self.updateAccountProperty(\.autoUpload, value: value)
  114. self.database.setAccountAutoUploadFileName("")
  115. self.database.setAccountAutoUploadDirectory("", session: self.session)
  116. NCAutoUpload.shared.alignPhotoLibrary(controller: self.controller, account: self.session.account)
  117. }
  118. } else {
  119. updateAccountProperty(\.autoUpload, value: newValue)
  120. updateAccountProperty(\.autoUploadFull, value: newValue)
  121. self.database.clearMetadatasUpload(account: session.account)
  122. }
  123. }
  124. /// Updates the auto-upload image setting.
  125. func handleAutoUploadImageChange(newValue: Bool) {
  126. updateAccountProperty(\.autoUploadImage, value: newValue)
  127. if newValue {
  128. NCAutoUpload.shared.alignPhotoLibrary(controller: controller, account: session.account)
  129. }
  130. }
  131. /// Updates the auto-upload image over WWAN setting.
  132. func handleAutoUploadWWAnPhotoChange(newValue: Bool) {
  133. updateAccountProperty(\.autoUploadWWAnPhoto, value: newValue)
  134. }
  135. /// Updates the auto-upload video setting.
  136. func handleAutoUploadVideoChange(newValue: Bool) {
  137. updateAccountProperty(\.autoUploadVideo, value: newValue)
  138. if newValue {
  139. NCAutoUpload.shared.alignPhotoLibrary(controller: controller, account: session.account)
  140. }
  141. }
  142. /// Updates the auto-upload video over WWAN setting.
  143. func handleAutoUploadWWAnVideoChange(newValue: Bool) {
  144. updateAccountProperty(\.autoUploadWWAnVideo, value: newValue)
  145. }
  146. /// Updates the auto-upload favorite only.
  147. func handleAutoUploadFavoritesOnlyChange(newValue: Bool) {
  148. updateAccountProperty(\.autoUploadFavoritesOnly, value: newValue)
  149. if newValue {
  150. NCAutoUpload.shared.alignPhotoLibrary(controller: controller, account: session.account)
  151. }
  152. }
  153. /// Updates the auto-upload full content setting.
  154. func handleAutoUploadFullChange(newValue: Bool) {
  155. updateAccountProperty(\.autoUploadFull, value: newValue)
  156. if newValue {
  157. NCAutoUpload.shared.autoUploadFullPhotos(controller: self.controller, log: "Auto upload full", account: session.account)
  158. } else {
  159. self.database.clearMetadatasUpload(account: session.account)
  160. }
  161. }
  162. /// Updates the auto-upload create subfolder setting.
  163. func handleAutoUploadCreateSubfolderChange(newValue: Bool) {
  164. updateAccountProperty(\.autoUploadCreateSubfolder, value: newValue)
  165. }
  166. /// Updates the auto-upload subfolder granularity setting.
  167. func handleAutoUploadSubfolderGranularityChange(newValue: Granularity) {
  168. updateAccountProperty(\.autoUploadSubfolderGranularity, value: newValue.rawValue)
  169. }
  170. /// Updates a property of the active account in the database.
  171. private func updateAccountProperty<T>(_ keyPath: ReferenceWritableKeyPath<tableAccount, T>, value: T) {
  172. guard let activeAccount = self.database.getActiveTableAccount() else { return }
  173. activeAccount[keyPath: keyPath] = value
  174. self.database.updateAccount(activeAccount)
  175. }
  176. /// Returns the path for auto-upload based on the active account's settings.
  177. ///
  178. /// - Returns: The path for auto-upload.
  179. func returnPath() -> String {
  180. let autoUploadPath = self.database.getAccountAutoUploadDirectory(session: session) + "/" + self.database.getAccountAutoUploadFileName()
  181. let homeServer = NCUtilityFileSystem().getHomeServer(session: session)
  182. let path = autoUploadPath.replacingOccurrences(of: homeServer, with: "")
  183. return path
  184. }
  185. /// Sets the auto-upload directory based on the provided server URL.
  186. ///
  187. /// - Parameter
  188. /// serverUrl: The server URL to set as the auto-upload directory.
  189. func setAutoUploadDirectory(serverUrl: String?) {
  190. guard let serverUrl else { return }
  191. let home = NCUtilityFileSystem().getHomeServer(session: session)
  192. if home != serverUrl {
  193. let fileName = (serverUrl as NSString).lastPathComponent
  194. self.database.setAccountAutoUploadFileName(fileName)
  195. if let path = NCUtilityFileSystem().deleteLastPath(serverUrlPath: serverUrl, home: home) {
  196. self.database.setAccountAutoUploadDirectory(path, session: session)
  197. }
  198. }
  199. onViewAppear()
  200. }
  201. }
  202. /// An enum that represents the granularity of the subfolders for auto upload
  203. enum Granularity: Int {
  204. /// Daily granularity, meaning the subfolders are named by day
  205. case daily = 2
  206. /// Monthly granularity, meaning the subfolders are named by month
  207. case monthly = 1
  208. /// Yearly granularity, meaning the subfolders are named by year
  209. case yearly = 0
  210. }