NCCameraRoll.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. //
  2. // NCCameraRoll.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 21/12/22.
  6. // Copyright © 2022 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 NextcloudKit
  25. import JGProgressHUD
  26. class NCCameraRoll: NSObject {
  27. func extractCameraRoll(from metadata: tableMetadata, viewController: UIViewController?, hud: JGProgressHUD, completition: @escaping (_ metadatas: [tableMetadata]) -> Void) {
  28. var chunkSize = NCGlobal.shared.chunkSizeMBCellular
  29. if NCNetworking.shared.networkReachability == NKCommon.TypeReachability.reachableEthernetOrWiFi {
  30. chunkSize = NCGlobal.shared.chunkSizeMBEthernetOrWiFi
  31. }
  32. var metadatas: [tableMetadata] = []
  33. let metadataSource = tableMetadata.init(value: metadata)
  34. guard !metadata.isExtractFile else { return completition([metadataSource]) }
  35. guard !metadataSource.assetLocalIdentifier.isEmpty else {
  36. let filePath = CCUtility.getDirectoryProviderStorageOcId(metadataSource.ocId, fileNameView: metadataSource.fileName)!
  37. metadataSource.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  38. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: metadataSource.fileNameView, mimeType: metadataSource.contentType, directory: false)
  39. metadataSource.contentType = results.mimeType
  40. metadataSource.iconName = results.iconName
  41. metadataSource.classFile = results.classFile
  42. if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: filePath) {
  43. metadataSource.creationDate = date
  44. }
  45. if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: filePath) {
  46. metadataSource.date = date
  47. }
  48. if metadataSource.size > chunkSize {
  49. metadataSource.chunk = chunkSize
  50. } else {
  51. metadataSource.chunk = 0
  52. }
  53. metadataSource.e2eEncrypted = metadata.isDirectoryE2EE
  54. if metadataSource.chunk > 0 || metadataSource.e2eEncrypted {
  55. metadataSource.session = NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload
  56. }
  57. metadataSource.isExtractFile = true
  58. if let metadata = NCManageDatabase.shared.addMetadata(metadataSource) {
  59. metadatas.append(metadata)
  60. }
  61. return completition(metadatas)
  62. }
  63. extractImageVideoFromAssetLocalIdentifier(metadata: metadataSource, modifyMetadataForUpload: true, viewController: viewController, hud: hud) { metadata, fileNamePath, error in
  64. if let metadata = metadata, let fileNamePath = fileNamePath, !error {
  65. metadatas.append(metadata)
  66. let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  67. NCUtilityFileSystem.shared.moveFile(atPath: fileNamePath, toPath: toPath)
  68. let fetchAssets = PHAsset.fetchAssets(withLocalIdentifiers: [metadataSource.assetLocalIdentifier], options: nil)
  69. if metadata.livePhoto, fetchAssets.count > 0 {
  70. self.createMetadataLivePhoto(metadata: metadata, asset: fetchAssets.firstObject) { metadata in
  71. if let metadata = metadata, let metadata = NCManageDatabase.shared.addMetadata(metadata) {
  72. metadatas.append(metadata)
  73. }
  74. completition(metadatas)
  75. }
  76. } else {
  77. completition(metadatas)
  78. }
  79. } else {
  80. completition(metadatas)
  81. }
  82. }
  83. }
  84. func extractImageVideoFromAssetLocalIdentifier(metadata: tableMetadata,
  85. modifyMetadataForUpload: Bool,
  86. viewController: UIViewController?,
  87. hud: JGProgressHUD,
  88. completion: @escaping (_ metadata: tableMetadata?, _ fileNamePath: String?, _ error: Bool) -> Void) {
  89. var fileNamePath: String?
  90. let metadata = tableMetadata.init(value: metadata)
  91. var compatibilityFormat: Bool = false
  92. var chunkSize = NCGlobal.shared.chunkSizeMBCellular
  93. if NCNetworking.shared.networkReachability == NKCommon.TypeReachability.reachableEthernetOrWiFi {
  94. chunkSize = NCGlobal.shared.chunkSizeMBEthernetOrWiFi
  95. }
  96. func callCompletionWithError(_ error: Bool = true) {
  97. if error {
  98. completion(nil, nil, true)
  99. } else {
  100. var metadataReturn = metadata
  101. if modifyMetadataForUpload {
  102. if metadata.size > chunkSize {
  103. metadata.chunk = chunkSize
  104. } else {
  105. metadata.chunk = 0
  106. }
  107. metadata.e2eEncrypted = metadata.isDirectoryE2EE
  108. if metadata.chunk > 0 || metadata.e2eEncrypted {
  109. metadata.session = NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload
  110. }
  111. metadata.isExtractFile = true
  112. if let metadata = NCManageDatabase.shared.addMetadata(metadata) {
  113. metadataReturn = metadata
  114. }
  115. }
  116. completion(metadataReturn, fileNamePath, error)
  117. }
  118. }
  119. let fetchAssets = PHAsset.fetchAssets(withLocalIdentifiers: [metadata.assetLocalIdentifier], options: nil)
  120. guard fetchAssets.count > 0, let asset = fetchAssets.firstObject else {
  121. return callCompletionWithError()
  122. }
  123. let extensionAsset = asset.originalFilename.pathExtension.uppercased()
  124. let creationDate = asset.creationDate ?? Date()
  125. let modificationDate = asset.modificationDate ?? Date()
  126. if asset.mediaType == PHAssetMediaType.image && (extensionAsset == "HEIC" || extensionAsset == "DNG") && CCUtility.getFormatCompatibility() {
  127. let fileName = (metadata.fileNameView as NSString).deletingPathExtension + ".jpg"
  128. metadata.contentType = "image/jpeg"
  129. fileNamePath = NSTemporaryDirectory() + fileName
  130. metadata.fileNameView = fileName
  131. if !metadata.isDirectoryE2EE {
  132. metadata.fileName = fileName
  133. }
  134. compatibilityFormat = true
  135. } else {
  136. fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
  137. }
  138. guard let fileNamePath = fileNamePath else { return callCompletionWithError() }
  139. if asset.mediaType == PHAssetMediaType.image {
  140. let options = PHImageRequestOptions()
  141. options.isNetworkAccessAllowed = true
  142. if compatibilityFormat {
  143. options.deliveryMode = .opportunistic
  144. } else {
  145. options.deliveryMode = .highQualityFormat
  146. }
  147. options.isSynchronous = true
  148. if extensionAsset == "DNG" {
  149. options.version = PHImageRequestOptionsVersion.original
  150. }
  151. options.progressHandler = { progress, error, _, _ in
  152. print(progress)
  153. if error != nil { return callCompletionWithError() }
  154. }
  155. PHImageManager.default().requestImageDataAndOrientation(for: asset, options: options) { data, _, _, _ in
  156. guard var data = data else { return callCompletionWithError() }
  157. if compatibilityFormat {
  158. guard let ciImage = CIImage(data: data), let colorSpace = ciImage.colorSpace, let dataJPEG = CIContext().jpegRepresentation(of: ciImage, colorSpace: colorSpace) else { return callCompletionWithError() }
  159. data = dataJPEG
  160. }
  161. NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
  162. do {
  163. try data.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
  164. } catch { return callCompletionWithError() }
  165. metadata.creationDate = creationDate as NSDate
  166. metadata.date = modificationDate as NSDate
  167. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  168. return callCompletionWithError(false)
  169. }
  170. } else if asset.mediaType == PHAssetMediaType.video {
  171. let options = PHVideoRequestOptions()
  172. options.isNetworkAccessAllowed = true
  173. options.version = PHVideoRequestOptionsVersion.current
  174. options.progressHandler = { progress, error, _, _ in
  175. print(progress)
  176. if error != nil { return callCompletionWithError() }
  177. }
  178. PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { asset, _, _ in
  179. if let asset = asset as? AVURLAsset {
  180. NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
  181. do {
  182. try FileManager.default.copyItem(at: asset.url, to: URL(fileURLWithPath: fileNamePath))
  183. metadata.creationDate = creationDate as NSDate
  184. metadata.date = modificationDate as NSDate
  185. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  186. return callCompletionWithError(false)
  187. } catch { return callCompletionWithError() }
  188. } else if let asset = asset as? AVComposition, asset.tracks.count > 1, let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality), let viewController = viewController {
  189. DispatchQueue.main.async {
  190. hud.indicatorView = JGProgressHUDRingIndicatorView()
  191. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  192. indicatorView.ringWidth = 1.5
  193. }
  194. hud.textLabel.text = NSLocalizedString("_exporting_video_", comment: "")
  195. hud.show(in: viewController.view)
  196. hud.tapOnHUDViewBlock = { _ in
  197. exporter.cancelExport()
  198. }
  199. }
  200. exporter.outputURL = URL(fileURLWithPath: fileNamePath)
  201. exporter.outputFileType = AVFileType.mp4
  202. exporter.shouldOptimizeForNetworkUse = true
  203. exporter.exportAsynchronously {
  204. DispatchQueue.main.async { hud.dismiss() }
  205. if exporter.status == .completed {
  206. metadata.creationDate = creationDate as NSDate
  207. metadata.date = modificationDate as NSDate
  208. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  209. return callCompletionWithError(false)
  210. } else { return callCompletionWithError() }
  211. }
  212. while exporter.status == AVAssetExportSession.Status.exporting || exporter.status == AVAssetExportSession.Status.waiting {
  213. hud.progress = exporter.progress
  214. }
  215. } else {
  216. return callCompletionWithError()
  217. }
  218. }
  219. } else {
  220. return callCompletionWithError()
  221. }
  222. }
  223. private func createMetadataLivePhoto(metadata: tableMetadata,
  224. asset: PHAsset?,
  225. completion: @escaping (_ metadata: tableMetadata?) -> Void) {
  226. guard let asset = asset else { return completion(nil) }
  227. let options = PHLivePhotoRequestOptions()
  228. options.deliveryMode = PHImageRequestOptionsDeliveryMode.fastFormat
  229. options.isNetworkAccessAllowed = true
  230. let ocId = NSUUID().uuidString
  231. let fileName = (metadata.fileName as NSString).deletingPathExtension + ".mov"
  232. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  233. var chunkSize = NCGlobal.shared.chunkSizeMBCellular
  234. if NCNetworking.shared.networkReachability == NKCommon.TypeReachability.reachableEthernetOrWiFi {
  235. chunkSize = NCGlobal.shared.chunkSizeMBEthernetOrWiFi
  236. }
  237. PHImageManager.default().requestLivePhoto(for: asset, targetSize: UIScreen.main.bounds.size, contentMode: PHImageContentMode.default, options: options) { livePhoto, _ in
  238. guard let livePhoto = livePhoto else { return completion(nil) }
  239. var videoResource: PHAssetResource?
  240. for resource in PHAssetResource.assetResources(for: livePhoto) where resource.type == PHAssetResourceType.pairedVideo {
  241. videoResource = resource
  242. break
  243. }
  244. guard let videoResource = videoResource else { return completion(nil) }
  245. NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
  246. PHAssetResourceManager.default().writeData(for: videoResource, toFile: URL(fileURLWithPath: fileNamePath), options: nil) { error in
  247. if error != nil { return completion(nil) }
  248. let metadataLivePhoto = NCManageDatabase.shared.createMetadata(account: metadata.account,
  249. user: metadata.user,
  250. userId: metadata.userId,
  251. fileName: fileName,
  252. fileNameView: fileName,
  253. ocId: ocId,
  254. serverUrl: metadata.serverUrl,
  255. urlBase: metadata.urlBase,
  256. url: "",
  257. contentType: "",
  258. isLivePhoto: true)
  259. metadataLivePhoto.classFile = NKCommon.TypeClassFile.video.rawValue
  260. metadataLivePhoto.isExtractFile = true
  261. metadataLivePhoto.session = metadata.session
  262. metadataLivePhoto.sessionSelector = metadata.sessionSelector
  263. metadataLivePhoto.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  264. metadataLivePhoto.status = metadata.status
  265. if metadataLivePhoto.size > chunkSize {
  266. metadataLivePhoto.chunk = chunkSize
  267. } else {
  268. metadataLivePhoto.chunk = 0
  269. }
  270. metadataLivePhoto.e2eEncrypted = metadata.isDirectoryE2EE
  271. if metadataLivePhoto.chunk > 0 || metadataLivePhoto.e2eEncrypted {
  272. metadataLivePhoto.session = NextcloudKit.shared.nkCommonInstance.sessionIdentifierUpload
  273. }
  274. metadataLivePhoto.creationDate = metadata.creationDate
  275. metadataLivePhoto.date = metadata.date
  276. metadataLivePhoto.uploadDate = metadata.uploadDate
  277. return completion(NCManageDatabase.shared.addMetadata(metadataLivePhoto))
  278. }
  279. }
  280. }
  281. }