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