NCAutoUpload.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. DispatchQueue.global(qos: .background).async {
  111. self.getCameraRollAssets(viewController: viewController, account: account, selector: selector, alignPhotoLibrary: false) { (assets) in
  112. if assets == nil || assets?.count == 0 {
  113. NCCommunicationCommon.shared.writeLog("Automatic upload, no new assets found")
  114. return
  115. } else {
  116. NCCommunicationCommon.shared.writeLog("Automatic upload, new \(assets?.count ?? 0) assets found")
  117. }
  118. guard let assets = assets else { return }
  119. if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  120. DispatchQueue.main.async {
  121. //self.hud = CCHud.init(view: self.appDelegate.window.rootViewController)
  122. NCContentPresenter.shared.messageNotification("_attention_", description: "_create_full_upload_", delay: NCBrandGlobal.shared.dismissAfterSecondLong, type: .info, errorCode: 0, forced: true)
  123. //self.hud?.visibleHudTitle(NSLocalizedString("_wait_", comment: ""), mode: MBProgressHUDMode.indeterminate, color: NCBrandColor.shared.brand)
  124. }
  125. }
  126. // Create the folder for auto upload & if request the subfolders
  127. if NCNetworking.shared.createFolder(assets: assets, selector: selector, useSubFolder: account.autoUploadCreateSubfolder, account: account.account, urlBase: account.urlBase) {
  128. if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  129. DispatchQueue.main.async {
  130. NCContentPresenter.shared.messageNotification("_error_", description: "_error_createsubfolders_upload_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: .error, errorCode: NCBrandGlobal.shared.ErrorInternalError, forced: true)
  131. self.hud?.hideHud()
  132. }
  133. return
  134. }
  135. }
  136. self.endForAssetToUpload = false
  137. for asset in assets {
  138. var livePhoto = false
  139. var session: String = ""
  140. guard let assetDate = asset.creationDate else { continue }
  141. let assetMediaType = asset.mediaType
  142. let formatter = DateFormatter()
  143. var serverUrl: String = ""
  144. 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)!
  145. if (asset.mediaSubtypes.rawValue == PHAssetMediaSubtype.photoLive.rawValue || asset.mediaSubtypes.rawValue == (PHAssetMediaSubtype.photoHDR.rawValue + PHAssetMediaSubtype.photoLive.rawValue)) && CCUtility.getLivePhoto() {
  146. livePhoto = true
  147. }
  148. if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  149. session = NCCommunicationCommon.shared.sessionIdentifierUpload
  150. } else {
  151. if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto == false { session = NCNetworking.shared.sessionIdentifierBackground }
  152. else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo == false { session = NCNetworking.shared.sessionIdentifierBackground }
  153. else if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto { session = NCNetworking.shared.sessionIdentifierBackgroundWWan }
  154. else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo { session = NCNetworking.shared.sessionIdentifierBackgroundWWan }
  155. else { session = NCNetworking.shared.sessionIdentifierBackground }
  156. }
  157. formatter.dateFormat = "yyyy"
  158. let yearString = formatter.string(from: assetDate)
  159. formatter.dateFormat = "MM"
  160. let monthString = formatter.string(from: assetDate)
  161. if account.autoUploadCreateSubfolder {
  162. serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
  163. } else {
  164. serverUrl = autoUploadPath
  165. }
  166. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account.account, serverUrl, fileName)) != nil {
  167. if selector == NCBrandGlobal.shared.selectorUploadAutoUpload {
  168. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  169. }
  170. } else {
  171. /* INSERT METADATA FOR UPLOAD */
  172. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: account.account, fileName: fileName, ocId: NSUUID().uuidString, serverUrl: serverUrl, urlBase: account.urlBase, url: "", contentType: "", livePhoto: livePhoto)
  173. metadataForUpload.assetLocalIdentifier = asset.localIdentifier
  174. metadataForUpload.session = session
  175. metadataForUpload.sessionSelector = selector
  176. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(asset: asset)
  177. metadataForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload
  178. if assetMediaType == PHAssetMediaType.video {
  179. metadataForUpload.typeFile = NCBrandGlobal.shared.metadataTypeFileVideo
  180. } else if (assetMediaType == PHAssetMediaType.image) {
  181. metadataForUpload.typeFile = NCBrandGlobal.shared.metadataTypeFileImage
  182. }
  183. if selector == NCBrandGlobal.shared.selectorUploadAutoUpload {
  184. NCCommunicationCommon.shared.writeLog("Automatic upload added \(metadataForUpload.fileNameView) (\(metadataForUpload.size) bytes) with Identifier \(metadataForUpload.assetLocalIdentifier)")
  185. NCManageDatabase.shared.addMetadataForAutoUpload(metadataForUpload)
  186. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  187. } else if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  188. metadataFull.append(metadataForUpload)
  189. }
  190. /* INSERT METADATA MOV LIVE PHOTO FOR UPLOAD */
  191. if livePhoto {
  192. counterLivePhoto += 1
  193. let fileName = (fileName as NSString).deletingPathExtension + ".mov"
  194. let ocId = NSUUID().uuidString
  195. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  196. CCUtility.extractLivePhotoAsset(asset, filePath: filePath) { (url) in
  197. if url != nil {
  198. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: account.account, fileName: fileName, ocId: ocId, serverUrl: serverUrl, urlBase: account.urlBase, url: "", contentType: "", livePhoto: livePhoto)
  199. metadataForUpload.session = session
  200. metadataForUpload.sessionSelector = selector
  201. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  202. metadataForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload
  203. metadataForUpload.typeFile = NCBrandGlobal.shared.metadataTypeFileVideo
  204. if selector == NCBrandGlobal.shared.selectorUploadAutoUpload {
  205. NCCommunicationCommon.shared.writeLog("Automatic upload added Live Photo \(metadataForUpload.fileNameView) (\(metadataForUpload.size) bytes) with Identifier \(metadataForUpload.assetLocalIdentifier)")
  206. NCManageDatabase.shared.addMetadataForAutoUpload(metadataForUpload)
  207. } else if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  208. metadataFull.append(metadataForUpload)
  209. }
  210. }
  211. }
  212. counterLivePhoto -= 1
  213. if self.endForAssetToUpload && counterLivePhoto == 0 && selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  214. DispatchQueue.main.async {
  215. NCManageDatabase.shared.addMetadatas(metadataFull)
  216. self.hud?.hideHud()
  217. }
  218. }
  219. }
  220. }
  221. }
  222. self.endForAssetToUpload = true
  223. if counterLivePhoto == 0 && selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  224. DispatchQueue.main.async {
  225. NCManageDatabase.shared.addMetadatas(metadataFull)
  226. self.hud?.hideHud()
  227. }
  228. }
  229. } // END
  230. } // END DispatchQueue.global(qos: .background).async
  231. }
  232. // MARK: -
  233. @objc func alignPhotoLibrary(viewController: UIViewController?) {
  234. if let account = NCManageDatabase.shared.getAccountActive() {
  235. getCameraRollAssets(viewController: viewController, account: account, selector: NCBrandGlobal.shared.selectorUploadAutoUploadAll, alignPhotoLibrary: true) { (assets) in
  236. NCManageDatabase.shared.clearTable(tablePhotoLibrary.self, account: account.account)
  237. if let assets = assets {
  238. NCManageDatabase.shared.addPhotoLibrary(assets, account: account.account)
  239. NCCommunicationCommon.shared.writeLog("Align Photo Library \(assets.count)")
  240. }
  241. }
  242. }
  243. }
  244. private func getCameraRollAssets(viewController: UIViewController?, account: tableAccount, selector: String, alignPhotoLibrary: Bool, completion: @escaping (_ assets: [PHAsset]?)->()) {
  245. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { (hasPermission) in
  246. if hasPermission {
  247. let assetCollection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil)
  248. if assetCollection.count > 0 {
  249. let predicateImage = NSPredicate(format: "mediaType == %i", PHAssetMediaType.image.rawValue)
  250. let predicateVideo = NSPredicate(format: "mediaType == %i", PHAssetMediaType.video.rawValue)
  251. var predicate: NSPredicate?
  252. let fetchOptions = PHFetchOptions()
  253. var newAssets: [PHAsset] = []
  254. if alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo) {
  255. predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicateImage, predicateVideo])
  256. } else if account.autoUploadImage {
  257. predicate = predicateImage
  258. } else if account.autoUploadVideo {
  259. predicate = predicateVideo
  260. } else {
  261. completion(nil)
  262. return
  263. }
  264. fetchOptions.predicate = predicate
  265. let assets: PHFetchResult<PHAsset> = PHAsset.fetchAssets(in: assetCollection.firstObject!, options: fetchOptions)
  266. if selector == NCBrandGlobal.shared.selectorUploadAutoUpload {
  267. var creationDate = ""
  268. var idAsset = ""
  269. let idsAsset = NCManageDatabase.shared.getPhotoLibraryIdAsset(image: account.autoUploadImage, video: account.autoUploadVideo, account: account.account)
  270. assets.enumerateObjects { (asset, _, _) in
  271. if asset.creationDate != nil { creationDate = String(describing: asset.creationDate!) }
  272. idAsset = account.account + asset.localIdentifier + creationDate
  273. if !(idsAsset?.contains(idAsset) ?? false) {
  274. newAssets.append(asset)
  275. }
  276. }
  277. } else {
  278. assets.enumerateObjects { (asset, _, _) in
  279. newAssets.append(asset)
  280. }
  281. }
  282. completion(newAssets)
  283. } else {
  284. completion(nil)
  285. }
  286. } else {
  287. completion(nil)
  288. }
  289. }
  290. }
  291. }