NCAutoUpload.swift 21 KB

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