NCCameraRoll.swift 15 KB

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