NCCameraRoll.swift 15 KB

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