NCAutoUpload.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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.init()
  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)->()) {
  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: 0, forced: true)
  121. NCUtility.shared.startActivityIndicator(backgroundView: nil, blurEffect: true)
  122. self.uploadAssetsNewAndFull(viewController: viewController, selector: NCGlobal.shared.selectorUploadAutoUploadAll, log: log) { (items) in
  123. NCUtility.shared.stopActivityIndicator()
  124. }
  125. }
  126. }
  127. }
  128. private func uploadAssetsNewAndFull(viewController: UIViewController?, selector: String, log: String, completion: @escaping (_ items: Int)->()) {
  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, forced: true)
  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 { session = NCNetworking.shared.sessionIdentifierBackground }
  172. else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo == false { session = NCNetworking.shared.sessionIdentifierBackground }
  173. else if assetMediaType == PHAssetMediaType.image && account.autoUploadWWAnPhoto { session = NCNetworking.shared.sessionIdentifierBackgroundWWan }
  174. else if assetMediaType == PHAssetMediaType.video && account.autoUploadWWAnVideo { session = NCNetworking.shared.sessionIdentifierBackgroundWWan }
  175. else { session = NCNetworking.shared.sessionIdentifierBackground }
  176. }
  177. formatter.dateFormat = "yyyy"
  178. let yearString = formatter.string(from: assetDate)
  179. formatter.dateFormat = "MM"
  180. let monthString = formatter.string(from: assetDate)
  181. if account.autoUploadCreateSubfolder {
  182. serverUrl = autoUploadPath + "/" + yearString + "/" + monthString
  183. } else {
  184. serverUrl = autoUploadPath
  185. }
  186. // MOST COMPATIBLE SEARCH --> HEIC --> JPG
  187. var fileNameSearchMetadata = fileName
  188. let ext = (fileNameSearchMetadata as NSString).pathExtension.uppercased()
  189. if ext == "HEIC" && CCUtility.getFormatCompatibility() {
  190. fileNameSearchMetadata = (fileNameSearchMetadata as NSString).deletingPathExtension + ".jpg"
  191. }
  192. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account.account, serverUrl, fileNameSearchMetadata)) != nil {
  193. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  194. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  195. }
  196. } else {
  197. /* INSERT METADATA FOR UPLOAD */
  198. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: account.account, userId: account.userId, fileName: fileName, fileNameView: fileName, ocId: NSUUID().uuidString, serverUrl: serverUrl, urlBase: account.urlBase, url: "", contentType: "", livePhoto: livePhoto)
  199. metadataForUpload.assetLocalIdentifier = asset.localIdentifier
  200. metadataForUpload.session = session
  201. metadataForUpload.sessionSelector = selector
  202. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(asset: asset)
  203. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  204. if assetMediaType == PHAssetMediaType.video {
  205. metadataForUpload.typeFile = NCGlobal.shared.metadataTypeFileVideo
  206. } else if (assetMediaType == PHAssetMediaType.image) {
  207. metadataForUpload.typeFile = NCGlobal.shared.metadataTypeFileImage
  208. }
  209. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  210. NCCommunicationCommon.shared.writeLog("Automatic upload added \(metadataForUpload.fileNameView) (\(metadataForUpload.size) bytes) with Identifier \(metadataForUpload.assetLocalIdentifier)")
  211. self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: [metadataForUpload], verifyAlreadyExists: true)
  212. NCManageDatabase.shared.addPhotoLibrary([asset], account: account.account)
  213. } else if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  214. metadataFull.append(metadataForUpload)
  215. }
  216. counterItemsUpload += 1
  217. /* INSERT METADATA MOV LIVE PHOTO FOR UPLOAD */
  218. if livePhoto {
  219. counterLivePhoto += 1
  220. let fileName = (fileName as NSString).deletingPathExtension + ".mov"
  221. let ocId = NSUUID().uuidString
  222. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  223. CCUtility.extractLivePhotoAsset(asset, filePath: filePath) { (url) in
  224. if url != nil {
  225. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: account.account, userId: account.userId, fileName: fileName, fileNameView: fileName, ocId: ocId, serverUrl: serverUrl, urlBase: account.urlBase, url: "", contentType: "", livePhoto: livePhoto)
  226. metadataForUpload.session = session
  227. metadataForUpload.sessionSelector = selector
  228. metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  229. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  230. metadataForUpload.typeFile = NCGlobal.shared.metadataTypeFileVideo
  231. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  232. NCCommunicationCommon.shared.writeLog("Automatic upload added Live Photo \(metadataForUpload.fileNameView) (\(metadataForUpload.size) bytes) with Identifier \(metadataForUpload.assetLocalIdentifier)")
  233. self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: [metadataForUpload], verifyAlreadyExists: true)
  234. } else if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  235. metadataFull.append(metadataForUpload)
  236. }
  237. counterItemsUpload += 1
  238. }
  239. counterLivePhoto -= 1
  240. if counterLivePhoto == 0 && self.endForAssetToUpload {
  241. DispatchQueue.main.async {
  242. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  243. self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: metadataFull)
  244. }
  245. completion(counterItemsUpload)
  246. }
  247. }
  248. }
  249. }
  250. }
  251. }
  252. self.endForAssetToUpload = true
  253. if counterLivePhoto == 0 {
  254. DispatchQueue.main.async {
  255. if selector == NCGlobal.shared.selectorUploadAutoUploadAll {
  256. self.appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: metadataFull)
  257. }
  258. completion(counterItemsUpload)
  259. }
  260. }
  261. }
  262. }
  263. }
  264. // MARK: -
  265. @objc func alignPhotoLibrary(viewController: UIViewController?) {
  266. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  267. getCameraRollAssets(viewController: viewController, account: activeAccount, selector: NCGlobal.shared.selectorUploadAutoUploadAll, alignPhotoLibrary: true) { (assets) in
  268. NCManageDatabase.shared.clearTable(tablePhotoLibrary.self, account: activeAccount.account)
  269. if let assets = assets {
  270. NCManageDatabase.shared.addPhotoLibrary(assets, account: activeAccount.account)
  271. NCCommunicationCommon.shared.writeLog("Align Photo Library \(assets.count)")
  272. }
  273. }
  274. }
  275. }
  276. private func getCameraRollAssets(viewController: UIViewController?, account: tableAccount, selector: String, alignPhotoLibrary: Bool, completion: @escaping (_ assets: [PHAsset]?)->()) {
  277. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: viewController) { (hasPermission) in
  278. if hasPermission {
  279. let assetCollection = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil)
  280. if assetCollection.count > 0 {
  281. let predicateImage = NSPredicate(format: "mediaType == %i", PHAssetMediaType.image.rawValue)
  282. let predicateVideo = NSPredicate(format: "mediaType == %i", PHAssetMediaType.video.rawValue)
  283. var predicate: NSPredicate?
  284. let fetchOptions = PHFetchOptions()
  285. var newAssets: [PHAsset] = []
  286. if alignPhotoLibrary || (account.autoUploadImage && account.autoUploadVideo) {
  287. predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicateImage, predicateVideo])
  288. } else if account.autoUploadImage {
  289. predicate = predicateImage
  290. } else if account.autoUploadVideo {
  291. predicate = predicateVideo
  292. } else {
  293. return completion(nil)
  294. }
  295. fetchOptions.predicate = predicate
  296. let assets: PHFetchResult<PHAsset> = PHAsset.fetchAssets(in: assetCollection.firstObject!, options: fetchOptions)
  297. if selector == NCGlobal.shared.selectorUploadAutoUpload {
  298. var creationDate = ""
  299. var idAsset = ""
  300. let idsAsset = NCManageDatabase.shared.getPhotoLibraryIdAsset(image: account.autoUploadImage, video: account.autoUploadVideo, account: account.account)
  301. assets.enumerateObjects { (asset, _, _) in
  302. if asset.creationDate != nil { creationDate = String(describing: asset.creationDate!) }
  303. idAsset = account.account + asset.localIdentifier + creationDate
  304. if !(idsAsset?.contains(idAsset) ?? false) {
  305. newAssets.append(asset)
  306. }
  307. }
  308. } else {
  309. assets.enumerateObjects { (asset, _, _) in
  310. newAssets.append(asset)
  311. }
  312. }
  313. completion(newAssets)
  314. } else {
  315. completion(nil)
  316. }
  317. } else {
  318. completion(nil)
  319. }
  320. }
  321. }
  322. }