NCAutoUploadModel.swift 9.9 KB

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