NCCameraRoll.swift 15 KB

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