NCAutoUploadModel.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 Photos
  26. import NextcloudKit
  27. /// A model that allows the user to configure the `auto upload settings for Nextcloud`
  28. class NCAutoUploadModel: ObservableObject, ViewOnAppearHandling {
  29. /// AppDelegate
  30. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  31. /// A state variable that indicates whether auto upload is enabled or not
  32. @Published var autoUpload: Bool = false
  33. /// A state variable that indicates whether to open NCSelect View or not
  34. @Published var autoUploadFolder: Bool = false
  35. /// A state variable that indicates whether auto upload for photos is enabled or not
  36. @Published var autoUploadImage: Bool = false
  37. /// A state variable that indicates whether auto upload for photos is restricted to Wi-Fi only or not
  38. @Published var autoUploadWWAnPhoto: Bool = false
  39. /// A state variable that indicates whether auto upload for videos is enabled or not
  40. @Published var autoUploadVideo: Bool = false
  41. /// A state variable that indicates whether auto upload for videos is enabled or not
  42. @Published var autoUploadWWAnVideo: Bool = false
  43. /// A state variable that indicates whether auto upload for full resolution photos is enabled or not
  44. @Published var autoUploadFull: Bool = false
  45. /// A state variable that indicates whether auto upload creates subfolders based on date or not
  46. @Published var autoUploadCreateSubfolder: Bool = false
  47. /// A state variable that indicates the granularity of the subfolders, either daily, monthly, or yearly
  48. @Published var autoUploadSubfolderGranularity: Granularity = .monthly
  49. /// A state variable that shows error in view in case of an error
  50. @Published var showErrorAlert: Bool = false
  51. @Published var sectionName = ""
  52. @Published var isAuthorized: Bool = false
  53. /// A string variable that contains error text
  54. @Published var error: String = ""
  55. private let manageDatabase = NCManageDatabase.shared
  56. @Published var autoUploadPath = "\(NCManageDatabase.shared.getAccountAutoUploadFileName())"
  57. /// Root View Controller
  58. var controller: NCMainTabBarController?
  59. /// A variable user for change the auto upload directory
  60. var serverUrl: String = ""
  61. /// Initialization code to set up the ViewModel with the active account
  62. init(controller: NCMainTabBarController?) {
  63. self.controller = controller
  64. onViewAppear()
  65. }
  66. /// Triggered when the view appears.
  67. func onViewAppear() {
  68. let activeAccount: tableAccount? = manageDatabase.getActiveAccount()
  69. if let account = activeAccount {
  70. autoUpload = account.autoUpload
  71. autoUploadImage = account.autoUploadImage
  72. autoUploadWWAnPhoto = account.autoUploadWWAnPhoto
  73. autoUploadVideo = account.autoUploadVideo
  74. autoUploadWWAnVideo = account.autoUploadWWAnVideo
  75. autoUploadFull = account.autoUploadFull
  76. autoUploadCreateSubfolder = account.autoUploadCreateSubfolder
  77. autoUploadSubfolderGranularity = Granularity(rawValue: account.autoUploadSubfolderGranularity) ?? .monthly
  78. serverUrl = NCUtilityFileSystem().getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  79. }
  80. if autoUpload {
  81. requestAuthorization { value in
  82. self.autoUpload = value
  83. self.updateAccountProperty(\.autoUpload, value: value)
  84. }
  85. }
  86. }
  87. // MARK: - All functions
  88. func requestAuthorization(completion: @escaping (Bool) -> Void = { _ in }) {
  89. PHPhotoLibrary.requestAuthorization { status in
  90. DispatchQueue.main.async {
  91. let value = (status == .authorized)
  92. if !value {
  93. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: NSLocalizedString("_access_photo_not_enabled_msg_", comment: ""), responseData: nil)
  94. NCContentPresenter().messageNotification("_error_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: .error)
  95. } else if UIApplication.shared.backgroundRefreshStatus != .available {
  96. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: NSLocalizedString("_access_background_app_refresh_denied_", comment: ""), responseData: nil)
  97. NCContentPresenter().messageNotification("_info_", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: .info)
  98. }
  99. completion(value)
  100. }
  101. }
  102. }
  103. /// Updates the auto-upload setting.
  104. func handleAutoUploadChange(newValue: Bool) {
  105. if newValue {
  106. requestAuthorization { value in
  107. self.autoUpload = value
  108. self.updateAccountProperty(\.autoUpload, value: value)
  109. NCManageDatabase.shared.setAccountAutoUploadFileName("")
  110. NCManageDatabase.shared.setAccountAutoUploadDirectory("", urlBase: self.appDelegate.urlBase, userId: self.appDelegate.userId, account: self.appDelegate.account)
  111. NCAutoUpload.shared.alignPhotoLibrary(viewController: self.controller)
  112. }
  113. } else {
  114. updateAccountProperty(\.autoUpload, value: newValue)
  115. updateAccountProperty(\.autoUploadFull, value: newValue)
  116. NCManageDatabase.shared.clearMetadatasUpload(account: appDelegate.account)
  117. }
  118. }
  119. /// Updates the auto-upload image setting.
  120. func handleAutoUploadImageChange(newValue: Bool) {
  121. updateAccountProperty(\.autoUploadImage, value: newValue)
  122. if newValue {
  123. NCAutoUpload.shared.alignPhotoLibrary(viewController: controller)
  124. }
  125. }
  126. /// Updates the auto-upload image over WWAN setting.
  127. func handleAutoUploadWWAnPhotoChange(newValue: Bool) {
  128. updateAccountProperty(\.autoUploadWWAnPhoto, value: newValue)
  129. }
  130. /// Updates the auto-upload video setting.
  131. func handleAutoUploadVideoChange(newValue: Bool) {
  132. updateAccountProperty(\.autoUploadVideo, value: newValue)
  133. if newValue {
  134. NCAutoUpload.shared.alignPhotoLibrary(viewController: controller)
  135. }
  136. }
  137. /// Updates the auto-upload video over WWAN setting.
  138. func handleAutoUploadWWAnVideoChange(newValue: Bool) {
  139. updateAccountProperty(\.autoUploadWWAnVideo, value: newValue)
  140. }
  141. /// Updates the auto-upload full content setting.
  142. func handleAutoUploadFullChange(newValue: Bool) {
  143. updateAccountProperty(\.autoUploadFull, value: newValue)
  144. if newValue {
  145. NCAutoUpload.shared.autoUploadFullPhotos(viewController: self.controller, log: "Auto upload full")
  146. } else {
  147. NCManageDatabase.shared.clearMetadatasUpload(account: appDelegate.account)
  148. }
  149. }
  150. /// Updates the auto-upload create subfolder setting.
  151. func handleAutoUploadCreateSubfolderChange(newValue: Bool) {
  152. updateAccountProperty(\.autoUploadCreateSubfolder, value: newValue)
  153. }
  154. /// Updates the auto-upload subfolder granularity setting.
  155. func handleAutoUploadSubfolderGranularityChange(newValue: Granularity) {
  156. updateAccountProperty(\.autoUploadSubfolderGranularity, value: newValue.rawValue)
  157. }
  158. /// Updates a property of the active account in the database.
  159. private func updateAccountProperty<T>(_ keyPath: ReferenceWritableKeyPath<tableAccount, T>, value: T) {
  160. guard let activeAccount = manageDatabase.getActiveAccount() else { return }
  161. activeAccount[keyPath: keyPath] = value
  162. manageDatabase.updateAccount(activeAccount)
  163. }
  164. /// Returns the path for auto-upload based on the active account's settings.
  165. ///
  166. /// - Returns: The path for auto-upload.
  167. func returnPath() -> String {
  168. let autoUploadPath = manageDatabase.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account) + "/" + manageDatabase.getAccountAutoUploadFileName()
  169. let homeServer = NCUtilityFileSystem().getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  170. let path = autoUploadPath.replacingOccurrences(of: homeServer, with: "")
  171. return path
  172. }
  173. /// Sets the auto-upload directory based on the provided server URL.
  174. ///
  175. /// - Parameter
  176. /// serverUrl: The server URL to set as the auto-upload directory.
  177. func setAutoUploadDirectory(serverUrl: String?) {
  178. guard let serverUrl = serverUrl else { return }
  179. let home = NCUtilityFileSystem().getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  180. if home != serverUrl {
  181. let fileName = (serverUrl as NSString).lastPathComponent
  182. NCManageDatabase.shared.setAccountAutoUploadFileName(fileName)
  183. if let path = NCUtilityFileSystem().deleteLastPath(serverUrlPath: serverUrl, home: home) {
  184. NCManageDatabase.shared.setAccountAutoUploadDirectory(path, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)
  185. }
  186. }
  187. onViewAppear()
  188. }
  189. }
  190. /// An enum that represents the granularity of the subfolders for auto upload
  191. enum Granularity: Int {
  192. /// Daily granularity, meaning the subfolders are named by day
  193. case daily = 2
  194. /// Monthly granularity, meaning the subfolders are named by month
  195. case monthly = 1
  196. /// Yearly granularity, meaning the subfolders are named by year
  197. case yearly = 0
  198. }