NCAutoUpload.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. @objc func startSignificantChangeUpdates() {
  37. if locationManager == nil {
  38. locationManager = CLLocationManager.init()
  39. locationManager?.delegate = self
  40. locationManager?.distanceFilter = 100
  41. }
  42. locationManager?.requestAlwaysAuthorization()
  43. locationManager?.startMonitoringSignificantLocationChanges()
  44. }
  45. @objc func stopSignificantChangeUpdates() {
  46. locationManager?.stopMonitoringSignificantLocationChanges()
  47. }
  48. func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
  49. let location = locations.last
  50. guard let latitude = location?.coordinate.latitude else { return }
  51. guard let longitude = location?.coordinate.longitude else { return }
  52. NCCommunicationCommon.shared.writeLog("Location manager: latitude \(latitude) longitude \(longitude)")
  53. if let account = NCManageDatabase.shared.getAccountActive() {
  54. if account.autoUpload && account.autoUploadBackground && UIApplication.shared.applicationState == UIApplication.State.background {
  55. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: nil) { (hasPermission) in
  56. if hasPermission {
  57. self.uploadAssetsNewAndFull(viewController: nil, selector: NCBrandGlobal.shared.selectorUploadAutoUpload)
  58. }
  59. }
  60. }
  61. }
  62. }
  63. func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
  64. if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.authorizedAlways {
  65. NCManageDatabase.shared.setAccountAutoUploadProperty("autoUploadBackground", state: false)
  66. self.stopSignificantChangeUpdates()
  67. }
  68. }
  69. func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
  70. NCAskAuthorization.shared.askAuthorizationLocationManager() { (hasFullPermissions) in
  71. if !hasFullPermissions {
  72. NCManageDatabase.shared.setAccountAutoUploadProperty("autoUploadBackground", state: false)
  73. self.stopSignificantChangeUpdates()
  74. }
  75. }
  76. }
  77. // MARK: -
  78. @objc func initAutoUpload(viewController: UIViewController?) {
  79. if let account = NCManageDatabase.shared.getAccountActive() {
  80. if account.autoUpload {
  81. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { (hasPermission) in
  82. if hasPermission {
  83. self.uploadAssetsNewAndFull(viewController:viewController, selector: NCBrandGlobal.shared.selectorUploadAutoUpload)
  84. if account.autoUploadBackground {
  85. NCAskAuthorization.shared.askAuthorizationLocationManager() { (hasFullPermissions) in
  86. if hasFullPermissions {
  87. self.startSignificantChangeUpdates()
  88. } else {
  89. NCManageDatabase.shared.setAccountAutoUploadProperty("autoUploadBackground", state: false)
  90. self.stopSignificantChangeUpdates()
  91. }
  92. }
  93. }
  94. } else {
  95. NCManageDatabase.shared.setAccountAutoUploadProperty("autoUpload", state: false)
  96. self.stopSignificantChangeUpdates()
  97. }
  98. }
  99. }
  100. } else {
  101. stopSignificantChangeUpdates()
  102. }
  103. }
  104. @objc func autoUploadFullPhotos(viewController: UIViewController?) {
  105. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: appDelegate.window.rootViewController) { (hasPermission) in
  106. if hasPermission {
  107. self.uploadAssetsNewAndFull(viewController: viewController, selector: NCBrandGlobal.shared.selectorUploadAutoUploadAll)
  108. }
  109. }
  110. }
  111. private func uploadAssetsNewAndFull(viewController: UIViewController?, selector: String) {
  112. if appDelegate.account == nil || appDelegate.account.count == 0 { return }
  113. guard let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", appDelegate.account)) else { return }
  114. let autoUploadPath = NCManageDatabase.shared.getAccountAutoUploadPath(urlBase: account.urlBase, account: account.account)
  115. var counterLivePhoto: Int = 0
  116. var metadataFull: [tableMetadata] = []
  117. DispatchQueue.global(qos: .background).async {
  118. self.getCameraRollAssets(viewController: viewController, account: account, selector: selector, alignPhotoLibrary: false) { (assets) in
  119. if assets == nil || assets?.count == 0 {
  120. NCCommunicationCommon.shared.writeLog("Automatic upload, no new assets found")
  121. return
  122. } else {
  123. NCCommunicationCommon.shared.writeLog("Automatic upload, new \(assets?.count ?? 0) assets found")
  124. }
  125. guard let assets = assets else { return }
  126. if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  127. DispatchQueue.main.async {
  128. self.hud = CCHud.init(view: self.appDelegate.window.rootViewController?.view)
  129. NCContentPresenter.shared.messageNotification("_attention_", description: "_create_full_upload_", delay: NCBrandGlobal.shared.dismissAfterSecondLong, type: .info, errorCode: 0, forced: true)
  130. self.hud?.visibleHudTitle(NSLocalizedString("_wait_", comment: ""), mode: MBProgressHUDMode.indeterminate, color: NCBrandColor.shared.brand)
  131. }
  132. }
  133. // Create the folder for auto upload & if request the subfolders
  134. if NCNetworking.shared.createFolder(assets: assets, selector: selector, useSubFolder: account.autoUploadCreateSubfolder, account: account.account, urlBase: account.urlBase) {
  135. if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  136. DispatchQueue.main.async {
  137. NCContentPresenter.shared.messageNotification("_error_", description: "_error_createsubfolders_upload_", delay: NCBrandGlobal.shared.dismissAfterSecond, type: .error, errorCode: NCBrandGlobal.shared.ErrorInternalError, forced: true)
  138. self.hud?.hideHud()
  139. }
  140. return
  141. }
  142. }
  143. self.endForAssetToUpload = false
  144. for asset in assets {
  145. var livePhoto = false
  146. var session: String = ""
  147. guard let assetDate = asset.creationDate else { continue }
  148. let assetMediaType = asset.mediaType
  149. let formatter = DateFormatter()
  150. var serverUrl: String = ""
  151. 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)!
  152. if asset.mediaSubtypes.contains(.photoLive) && CCUtility.getLivePhoto() {
  153. livePhoto = true
  154. }
  155. if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  156. session = NCCommunicationCommon.shared.sessionIdentifierUpload
  157. } else {
  158. if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto == false { session = NCNetworking.shared.sessionIdentifierBackground }
  159. else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo == false { session = NCNetworking.shared.sessionIdentifierBackground }
  160. else if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto { session = NCNetworking.shared.sessionIdentifierBackgroundWWan }
  161. else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo { session = NCNetworking.shared.sessionIdentifierBackgroundWWan }
  162. else { session = NCNetworking.shared.sessionIdentifierBackground }
  163. }
  164. formatter.dateFormat = "yyyy"
  165. let yearString = formatter.string(from: assetDate)
  166. formatter.dateFormat = "MM"
  167. let monthString = formatter.string(from: assetDate)
  168. if account.autoUploadCreateSubfolder {
  169. serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
  170. } else {
  171. serverUrl = autoUploadPath
  172. }
  173. // MOST COMPATIBLE SEARCH --> HEIC --> JPG
  174. var fileNameSearchMetadata = fileName
  175. let ext = (fileNameSearchMetadata as NSString).pathExtension.uppercased()
  176. if ext == "HEIC" && CCUtility.getFormatCompatibility() {
  177. fileNameSearchMetadata = (fileNameSearchMetadata as NSString).deletingPathExtension + ".jpg"
  178. }
  179. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account.account, serverUrl, fileNameSearchMetadata)) != nil {
  180. if selector == NCBrandGlobal.shared.selectorUploadAutoUpload {
  181. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  182. }
  183. } else {
  184. /* INSERT METADATA FOR UPLOAD */
  185. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: account.account, fileName: fileName, ocId: NSUUID().uuidString, serverUrl: serverUrl, urlBase: account.urlBase, url: "", contentType: "", livePhoto: livePhoto)
  186. metadataForUpload.assetLocalIdentifier = asset.localIdentifier
  187. metadataForUpload.session = session
  188. metadataForUpload.sessionSelector = selector
  189. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(asset: asset)
  190. metadataForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload
  191. if assetMediaType == PHAssetMediaType.video {
  192. metadataForUpload.typeFile = NCBrandGlobal.shared.metadataTypeFileVideo
  193. } else if (assetMediaType == PHAssetMediaType.image) {
  194. metadataForUpload.typeFile = NCBrandGlobal.shared.metadataTypeFileImage
  195. }
  196. if selector == NCBrandGlobal.shared.selectorUploadAutoUpload {
  197. NCCommunicationCommon.shared.writeLog("Automatic upload added \(metadataForUpload.fileNameView) (\(metadataForUpload.size) bytes) with Identifier \(metadataForUpload.assetLocalIdentifier)")
  198. NCManageDatabase.shared.addMetadataForAutoUpload(metadataForUpload)
  199. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  200. } else if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  201. metadataFull.append(metadataForUpload)
  202. }
  203. /* INSERT METADATA MOV LIVE PHOTO FOR UPLOAD */
  204. if livePhoto {
  205. counterLivePhoto += 1
  206. let fileName = (fileName as NSString).deletingPathExtension + ".mov"
  207. let ocId = NSUUID().uuidString
  208. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  209. CCUtility.extractLivePhotoAsset(asset, filePath: filePath) { (url) in
  210. if url != nil {
  211. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: account.account, fileName: fileName, ocId: ocId, serverUrl: serverUrl, urlBase: account.urlBase, url: "", contentType: "", livePhoto: livePhoto)
  212. metadataForUpload.session = session
  213. metadataForUpload.sessionSelector = selector
  214. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  215. metadataForUpload.status = NCBrandGlobal.shared.metadataStatusWaitUpload
  216. metadataForUpload.typeFile = NCBrandGlobal.shared.metadataTypeFileVideo
  217. if selector == NCBrandGlobal.shared.selectorUploadAutoUpload {
  218. NCCommunicationCommon.shared.writeLog("Automatic upload added Live Photo \(metadataForUpload.fileNameView) (\(metadataForUpload.size) bytes) with Identifier \(metadataForUpload.assetLocalIdentifier)")
  219. NCManageDatabase.shared.addMetadataForAutoUpload(metadataForUpload)
  220. } else if selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  221. metadataFull.append(metadataForUpload)
  222. }
  223. }
  224. }
  225. counterLivePhoto -= 1
  226. if self.endForAssetToUpload && counterLivePhoto == 0 && selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  227. DispatchQueue.main.async {
  228. NCManageDatabase.shared.addMetadatas(metadataFull)
  229. self.hud?.hideHud()
  230. }
  231. }
  232. }
  233. }
  234. }
  235. self.endForAssetToUpload = true
  236. if counterLivePhoto == 0 && selector == NCBrandGlobal.shared.selectorUploadAutoUploadAll {
  237. DispatchQueue.main.async {
  238. NCManageDatabase.shared.addMetadatas(metadataFull)
  239. self.hud?.hideHud()
  240. }
  241. }
  242. } // END
  243. } // END DispatchQueue.global(qos: .background).async
  244. }
  245. // MARK: -
  246. @objc func alignPhotoLibrary(viewController: UIViewController?) {
  247. if let account = NCManageDatabase.shared.getAccountActive() {
  248. getCameraRollAssets(viewController: viewController, account: account, selector: NCBrandGlobal.shared.selectorUploadAutoUploadAll, alignPhotoLibrary: true) { (assets) in
  249. NCManageDatabase.shared.clearTable(tablePhotoLibrary.self, account: account.account)
  250. if let assets = assets {
  251. NCManageDatabase.shared.addPhotoLibrary(assets, account: account.account)
  252. NCCommunicationCommon.shared.writeLog("Align Photo Library \(assets.count)")
  253. }
  254. }
  255. }
  256. }
  257. private func getCameraRollAssets(viewController: UIViewController?, account: tableAccount, selector: String, alignPhotoLibrary: Bool, completion: @escaping (_ assets: [PHAsset]?)->()) {
  258. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { (hasPermission) in
  259. if hasPermission {
  260. let assetCollection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil)
  261. if assetCollection.count > 0 {
  262. let predicateImage = NSPredicate(format: "mediaType == %i", PHAssetMediaType.image.rawValue)
  263. let predicateVideo = NSPredicate(format: "mediaType == %i", PHAssetMediaType.video.rawValue)
  264. var predicate: NSPredicate?
  265. let fetchOptions = PHFetchOptions()
  266. var newAssets: [PHAsset] = []
  267. if alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo) {
  268. predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicateImage, predicateVideo])
  269. } else if account.autoUploadImage {
  270. predicate = predicateImage
  271. } else if account.autoUploadVideo {
  272. predicate = predicateVideo
  273. } else {
  274. completion(nil)
  275. return
  276. }
  277. fetchOptions.predicate = predicate
  278. let assets: PHFetchResult<PHAsset> = PHAsset.fetchAssets(in: assetCollection.firstObject!, options: fetchOptions)
  279. if selector == NCBrandGlobal.shared.selectorUploadAutoUpload {
  280. var creationDate = ""
  281. var idAsset = ""
  282. let idsAsset = NCManageDatabase.shared.getPhotoLibraryIdAsset(image: account.autoUploadImage, video: account.autoUploadVideo, account: account.account)
  283. assets.enumerateObjects { (asset, _, _) in
  284. if asset.creationDate != nil { creationDate = String(describing: asset.creationDate!) }
  285. idAsset = account.account + asset.localIdentifier + creationDate
  286. if !(idsAsset?.contains(idAsset) ?? false) {
  287. newAssets.append(asset)
  288. }
  289. }
  290. } else {
  291. assets.enumerateObjects { (asset, _, _) in
  292. newAssets.append(asset)
  293. }
  294. }
  295. completion(newAssets)
  296. } else {
  297. completion(nil)
  298. }
  299. } else {
  300. completion(nil)
  301. }
  302. }
  303. }
  304. }