NCAutoUpload.swift 21 KB

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