NCCameraRoll.swift 15 KB

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