NCAutoUpload.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. //
  2. // NCAutoUpload.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 27/01/21.
  6. // Copyright © 2021 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. import CoreLocation
  25. import NCCommunication
  26. class NCAutoUpload: NSObject, CLLocationManagerDelegate {
  27. @objc static let shared: NCAutoUpload = {
  28. let instance = NCAutoUpload()
  29. return instance
  30. }()
  31. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. public var locationManager: CLLocationManager?
  33. private var hud: CCHud?
  34. private var endForAssetToUpload: Bool = false
  35. // MARK: -
  36. func startSignificantChangeUpdates() {
  37. if locationManager == nil {
  38. locationManager = CLLocationManager.init()
  39. locationManager?.delegate = self
  40. locationManager?.requestAlwaysAuthorization()
  41. }
  42. locationManager?.startMonitoringSignificantLocationChanges()
  43. }
  44. @objc func stopSignificantChangeUpdates() {
  45. locationManager?.stopMonitoringSignificantLocationChanges()
  46. }
  47. func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
  48. let location = locations.last
  49. let latitude = String(describing: location?.coordinate.latitude)
  50. let longitude = String(describing: location?.coordinate.longitude)
  51. NCCommunicationCommon.shared.writeLog("update location manager: latitude " + latitude + ", longitude " + longitude)
  52. if let account = NCManageDatabase.shared.getAccountActive() {
  53. if account.autoUpload && account.autoUploadBackground && UIApplication.shared.applicationState == UIApplication.State.background {
  54. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: nil) { (hasPermission) in
  55. if hasPermission {
  56. self.uploadAssetsNewAndFull(viewController: nil, selector: NCBrandGlobal.shared.selectorUploadAutoUpload)
  57. }
  58. }
  59. }
  60. }
  61. }
  62. func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
  63. NCManageDatabase.shared.setAccountAutoUploadProperty("autoUploadBackground", state: false)
  64. self.stopSignificantChangeUpdates()
  65. }
  66. func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
  67. NCManageDatabase.shared.setAccountAutoUploadProperty("autoUploadBackground", state: false)
  68. self.stopSignificantChangeUpdates()
  69. }
  70. // MARK: -
  71. @objc func initAutoUpload(viewController: UIViewController?) {
  72. if let account = NCManageDatabase.shared.getAccountActive() {
  73. if account.autoUpload {
  74. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { (hasPermission) in
  75. if hasPermission {
  76. self.uploadAssetsNewAndFull(viewController:viewController, selector: NCBrandGlobal.shared.selectorUploadAutoUpload)
  77. if account.autoUploadBackground {
  78. NCAskAuthorization.shared.askAuthorizationLocationManager(viewController: viewController) { (hasPermissions) in
  79. if hasPermissions {
  80. self.startSignificantChangeUpdates()
  81. } else {
  82. NCManageDatabase.shared.setAccountAutoUploadProperty("autoUploadBackground", state: false)
  83. self.stopSignificantChangeUpdates()
  84. }
  85. }
  86. }
  87. } else {
  88. NCManageDatabase.shared.setAccountAutoUploadProperty("autoUpload", state: false)
  89. self.stopSignificantChangeUpdates()
  90. }
  91. }
  92. }
  93. } else {
  94. stopSignificantChangeUpdates()
  95. }
  96. }
  97. @objc func autoUploadFullPhotos(viewController: UIViewController?) {
  98. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: appDelegate.window.rootViewController) { (hasPermission) in
  99. if hasPermission {
  100. self.uploadAssetsNewAndFull(viewController: viewController, selector: NCBrandGlobal.shared.selectorUploadAutoUploadAll)
  101. }
  102. }
  103. }
  104. private func uploadAssetsNewAndFull(viewController: UIViewController?, selector: String) {
  105. if appDelegate.account == nil || appDelegate.account.count == 0 { return }
  106. guard let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", appDelegate.account)) else { return }
  107. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: account.urlBase, account: account.account)
  108. var counterLivePhoto: Int = 0
  109. var metadataFull: [tableMetadata] = []
  110. self.getCameraRollAssets(viewController: viewController, account: account, selector: selector, alignPhotoLibrary: false) { (assets) in
  111. if assets == nil || assets?.count == 0 {
  112. NCCommunicationCommon.shared.writeLog("Automatic upload, no new assets found")
  113. return
  114. } else {
  115. NCCommunicationCommon.shared.writeLog("Automatic upload, new \(assets?.count ?? 0) assets found")
  116. }
  117. guard let assets = assets else { return }
  118. if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  119. DispatchQueue.main.async {
  120. self.hud = CCHud.init(view: self.appDelegate.window.rootViewController)
  121. NCContentPresenter.shared.messageNotification("_attention_", description: "_create_full_upload_", delay: NCBrandGlobal.shared.dismissAfterSecondLong, type: .info, errorCode: 0, forced: true)
  122. self.hud?.visibleHudTitle(NSLocalizedString("_wait_", comment: ""), mode: MBProgressHUDMode.indeterminate, color: NCBrandColor.shared.brand)
  123. }
  124. }
  125. // Create the folder for auto upload & if request the subfolders
  126. if NCNetworking.shared.createFolder(assets: assets, selector: selector, useSubFolder: account.autoUploadCreateSubfolder, account: account.account, urlBase: account.urlBase) {
  127. if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  128. DispatchQueue.main.async {
  129. NCContentPresenter.shared.messageNotification("_error_", description: "_error_createsubfolders_upload_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: .error, errorCode: NCBrandGlobal.shared.ErrorInternalError, forced: true)
  130. self.hud?.hideHud()
  131. }
  132. return
  133. }
  134. }
  135. self.endForAssetToUpload = false
  136. for asset in assets {
  137. var livePhoto = false
  138. var session: String = ""
  139. guard let assetDate = asset.creationDate else { continue }
  140. let assetMediaType = asset.mediaType
  141. var formatter = DateFormatter()
  142. var serverUrl: String = ""
  143. let fileName = CCUtility.createFileName(asset.value(forKey: "filename") as? String, fileDate: assetDate, fileType: assetMediaType, keyFileName: NCBrandGlobal.shared.keyFileNameAutoUploadMask, keyFileNameType: NCBrandGlobal.shared.keyFileNameAutoUploadType, keyFileNameOriginal: NCBrandGlobal.shared.keyFileNameOriginalAutoUpload)!
  144. if (asset.mediaSubtypes.rawValue == PHAssetMediaSubtype.photoLive.rawValue || asset.mediaSubtypes.rawValue == (PHAssetMediaSubtype.photoHDR.rawValue + PHAssetMediaSubtype.photoLive.rawValue)) && CCUtility.getLivePhoto() {
  145. livePhoto = true
  146. }
  147. if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  148. session = NCCommunicationCommon.shared.sessionIdentifierUpload
  149. } else {
  150. if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto == false { session = NCNetworking.shared.sessionIdentifierBackground }
  151. else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo == false { session = NCNetworking.shared.sessionIdentifierBackground }
  152. else if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto { session = NCNetworking.shared.sessionIdentifierBackgroundWWan }
  153. else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo { session = NCNetworking.shared.sessionIdentifierBackgroundWWan }
  154. else { session = NCNetworking.shared.sessionIdentifierBackground }
  155. }
  156. formatter.dateFormat = "yyyy"
  157. let yearString = formatter.string(from: assetDate)
  158. formatter.dateFormat = "MM"
  159. let monthString = formatter.string(from: assetDate)
  160. if account.autoUploadCreateSubfolder {
  161. serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
  162. } else {
  163. serverUrl = autoUploadPath
  164. }
  165. if let metadata = NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account.account, serverUrl, fileName)) {
  166. if selector == NCBrandGlobal.shared.selectorUploadAutoUpload {
  167. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  168. }
  169. } else {
  170. }
  171. }
  172. self.endForAssetToUpload = true
  173. if counterLivePhoto == 0 && selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  174. DispatchQueue.main.async {
  175. NCManageDatabase.shared.addMetadatas(metadataFull)
  176. self.hud?.hideHud()
  177. }
  178. }
  179. }
  180. }
  181. // MARK: -
  182. @objc func alignPhotoLibrary(viewController: UIViewController?) {
  183. if let account = NCManageDatabase.shared.getAccountActive() {
  184. getCameraRollAssets(viewController: viewController, account: account, selector: NCBrandGlobal.shared.selectorUploadAutoUploadAll, alignPhotoLibrary: true) { (assets) in
  185. NCManageDatabase.shared.clearTable(tablePhotoLibrary.self, account: account.account)
  186. if let assets = assets {
  187. NCManageDatabase.shared.addPhotoLibrary(assets, account: account.account)
  188. NCCommunicationCommon.shared.writeLog("Align Photo Library \(assets.count)")
  189. }
  190. }
  191. }
  192. }
  193. private func getCameraRollAssets(viewController: UIViewController?, account: tableAccount, selector: String, alignPhotoLibrary: Bool, completion: @escaping (_ assets: [PHAsset]?)->()) {
  194. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { (hasPermission) in
  195. if hasPermission {
  196. let assetCollection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil)
  197. if assetCollection.count > 0 {
  198. let predicateImage = NSPredicate(format: "mediaType == %i", PHAssetMediaType.image.rawValue)
  199. let predicateVideo = NSPredicate(format: "mediaType == %i", PHAssetMediaType.video.rawValue)
  200. var predicate: NSPredicate?
  201. let fetchOptions = PHFetchOptions()
  202. var newAssets: [PHAsset] = []
  203. if alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo) {
  204. predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicateImage, predicateVideo])
  205. } else if account.autoUploadImage {
  206. predicate = predicateImage
  207. } else if account.autoUploadVideo {
  208. predicate = predicateVideo
  209. } else {
  210. completion(nil)
  211. return
  212. }
  213. fetchOptions.predicate = predicate
  214. let assets: PHFetchResult<PHAsset> = PHAsset.fetchAssets(in: assetCollection.firstObject!, options: fetchOptions)
  215. if selector == NCBrandGlobal.shared.selectorUploadAutoUpload {
  216. var creationDate = ""
  217. var idAsset = ""
  218. let idsAsset = NCManageDatabase.shared.getPhotoLibraryIdAsset(image: account.autoUploadImage, video: account.autoUploadVideo, account: account.account)
  219. assets.enumerateObjects { (asset, _, _) in
  220. if asset.creationDate != nil { creationDate = String(describing: asset.creationDate) }
  221. idAsset = account.account + asset.localIdentifier + creationDate
  222. if !(idsAsset?.contains(idAsset) ?? false) {
  223. newAssets.append(asset)
  224. }
  225. }
  226. } else {
  227. assets.enumerateObjects { (asset, _, _) in
  228. newAssets.append(asset)
  229. }
  230. }
  231. completion(newAssets)
  232. } else {
  233. completion(nil)
  234. }
  235. } else {
  236. completion(nil)
  237. }
  238. }
  239. }
  240. }