Browse Source

improved code

Signed-off-by: Marino Faggiana <marino@marinofaggiana.com>
Marino Faggiana 2 years ago
parent
commit
80fa482203

+ 19 - 11
.swiftlint.yml

@@ -1,32 +1,40 @@
 opt_in_rules: # some rules are turned off by default, so you need to opt-in
-  - empty_collection_literal
-  - empty_count
-  - empty_string
-  - explicit_init
-  - unneeded_parentheses_in_closure_argument
-  - operator_usage_whitespace
+ - empty_collection_literal
+ - empty_count
+ - empty_string
+ - explicit_init
+ - unneeded_parentheses_in_closure_argument
+ - operator_usage_whitespace
 
 empty_count:
   severity: warning
 
+cyclomatic_complexity: 
+  warning: 25
+
 line_length:
-  # warning: 120, error: 200
   warning: 250
   error: 250
 
 function_body_length:
-  # warning: 40
-  warning: 60
+   warning: 200
 
 type_body_length:
-  # error: 350
+  warning: 350
   error: 500
+  
+file_length:
+  warning: 1000
+  error: 1500
+  ignore_comment_only_lines: true
 
 identifier_name:
   min_length: 0
   
 disabled_rules:  
- - unused_setter_value
+  - unused_setter_value
+  - large_tuple
+  - function_parameter_count
 
 excluded:
   - Carthage

+ 10 - 4
Nextcloud.xcodeproj/project.pbxproj

@@ -320,6 +320,8 @@
 		F77BB74A2899857B0090FC19 /* UINavigationController+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77BB7492899857B0090FC19 /* UINavigationController+Extension.swift */; };
 		F77BC3EB293E5268005F2B08 /* Swifter in Frameworks */ = {isa = PBXBuildFile; productRef = F77BC3EA293E5268005F2B08 /* Swifter */; };
 		F77BC3ED293E528A005F2B08 /* NCConfigServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77BC3EC293E528A005F2B08 /* NCConfigServer.swift */; };
+		F77C97392953131000FDDD09 /* NCCameraRoll.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77C97382953131000FDDD09 /* NCCameraRoll.swift */; };
+		F77C973A2953143A00FDDD09 /* NCCameraRoll.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77C97382953131000FDDD09 /* NCCameraRoll.swift */; };
 		F77ED59128C9CE9D00E24ED0 /* ToolbarData.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77ED59028C9CE9D00E24ED0 /* ToolbarData.swift */; };
 		F77ED59328C9CEA000E24ED0 /* ToolbarWidgetProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77ED59228C9CEA000E24ED0 /* ToolbarWidgetProvider.swift */; };
 		F77ED59528C9CEA400E24ED0 /* ToolbarWidgetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F77ED59428C9CEA300E24ED0 /* ToolbarWidgetView.swift */; };
@@ -926,6 +928,7 @@
 		F77BB747289985270090FC19 /* UITabBarController+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UITabBarController+Extension.swift"; sourceTree = "<group>"; };
 		F77BB7492899857B0090FC19 /* UINavigationController+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UINavigationController+Extension.swift"; sourceTree = "<group>"; };
 		F77BC3EC293E528A005F2B08 /* NCConfigServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCConfigServer.swift; sourceTree = "<group>"; };
+		F77C97382953131000FDDD09 /* NCCameraRoll.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NCCameraRoll.swift; sourceTree = "<group>"; };
 		F77ED59028C9CE9D00E24ED0 /* ToolbarData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarData.swift; sourceTree = "<group>"; };
 		F77ED59228C9CEA000E24ED0 /* ToolbarWidgetProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarWidgetProvider.swift; sourceTree = "<group>"; };
 		F77ED59428C9CEA300E24ED0 /* ToolbarWidgetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolbarWidgetView.swift; sourceTree = "<group>"; };
@@ -1881,21 +1884,22 @@
 		F7BFFA991A24D7BB0044ED85 /* Utility */ = {
 			isa = PBXGroup;
 			children = (
+				F702F2FC25EE5D2C008F8E80 /* NYMnemonic */,
 				F7053E3C1C639DF500741EA5 /* CCUtility.h */,
 				F7053E3D1C639DF500741EA5 /* CCUtility.m */,
+				F76D364528A4F8BF00214537 /* NCActivityIndicator.swift */,
 				F733598025C1C188002ABA72 /* NCAskAuthorization.swift */,
+				F77C97382953131000FDDD09 /* NCCameraRoll.swift */,
 				F765608E23BF813500765969 /* NCContentPresenter.swift */,
-				F702F30725EE5D47008F8E80 /* NCPopupViewController.swift */,
 				F70968A324212C4E00ED60E5 /* NCLivePhoto.swift */,
+				F702F30725EE5D47008F8E80 /* NCPopupViewController.swift */,
 				F707C26421A2DC5200F6181E /* NCStoreReview.swift */,
+				AF817EF0274BC781009ED85B /* NCUserBaseUrl.swift */,
 				F70BFC7320E0FA7C00C67599 /* NCUtility.swift */,
-				F76D364528A4F8BF00214537 /* NCActivityIndicator.swift */,
 				AF93474B27E34120002537EE /* NCUtility+Image.swift */,
-				AF817EF0274BC781009ED85B /* NCUserBaseUrl.swift */,
 				F74AF3A3247FB6AE00AC767B /* NCUtilityFileSystem.swift */,
 				AF36077027BFA4E8001A243D /* ParallelWorker.swift */,
 				F7245923289BB50B00474787 /* ThreadSafeDictionary.swift */,
-				F702F2FC25EE5D2C008F8E80 /* NYMnemonic */,
 			);
 			path = Utility;
 			sourceTree = "<group>";
@@ -2874,6 +2878,7 @@
 				AF22B20C277C6F4D00DAB0CC /* NCShareCell.swift in Sources */,
 				F7E98C1727E0D0FC001F9F19 /* NCManageDatabase+Video.swift in Sources */,
 				F79B646126CA661600838ACA /* UIControl+Extensions.swift in Sources */,
+				F77C973A2953143A00FDDD09 /* NCCameraRoll.swift in Sources */,
 				F7EDE4CC262D7B6F00414FE6 /* NCEmptyDataSet.swift in Sources */,
 				F7C30E01291BD2610017149B /* NCNetworkingE2EERename.swift in Sources */,
 				AF4BF61A27562A4B0081CEEF /* NCManageDatabase+Metadata.swift in Sources */,
@@ -3151,6 +3156,7 @@
 				F7AE00F5230D5F9E007ACF8A /* NCLoginWeb.swift in Sources */,
 				F707C26521A2DC5200F6181E /* NCStoreReview.swift in Sources */,
 				F7BAADCB1ED5A87C00B7EAD4 /* NCManageDatabase.swift in Sources */,
+				F77C97392953131000FDDD09 /* NCCameraRoll.swift in Sources */,
 				F70968A424212C4E00ED60E5 /* NCLivePhoto.swift in Sources */,
 				F7C30DFA291BCF790017149B /* NCNetworkingE2EECreateFolder.swift in Sources */,
 				F7BC288026663F85004D46C5 /* NCViewCertificateDetails.swift in Sources */,

+ 1 - 1
iOSClient/Extensions/Array+Extensions.swift

@@ -24,7 +24,7 @@
 
 import Foundation
 
-//https://stackoverflow.com/questions/33861036/unique-objects-inside-a-array-swift/45023247#45023247
+// https://stackoverflow.com/questions/33861036/unique-objects-inside-a-array-swift/45023247#45023247
 extension Array {
     func unique<T: Hashable>(map: ((Element) -> (T))) -> [Element] {
         var set = Set<T>() // the unique list kept in a Set for fast retrieval

+ 1 - 1
iOSClient/Extensions/String+Extensions.swift

@@ -51,7 +51,7 @@ extension String {
     }
 
     func md5() -> String {
-        //https://stackoverflow.com/a/32166735/9506784
+        // https://stackoverflow.com/a/32166735/9506784
 
         let length = Int(CC_MD5_DIGEST_LENGTH)
         let messageData = self.data(using: .utf8) ?? Data()

+ 2 - 1
iOSClient/Main/Create cloud/NCCreateFormUploadConflict.swift

@@ -384,7 +384,8 @@ extension NCCreateFormUploadConflict: UITableViewDataSource {
                 } else {
 
                     // PREVIEW
-                    NCUtility.shared.extractImageVideoFromAssetLocalIdentifier(metadata: metadataNewFile, modifyMetadataForUpload: false, viewController: self, hud: JGProgressHUD()) { metadata, fileNamePath, error in
+                    let cameraRoll = NCCameraRoll()
+                    cameraRoll.extractImageVideoFromAssetLocalIdentifier(metadata: metadataNewFile, modifyMetadataForUpload: false, viewController: self, hud: JGProgressHUD()) { metadata, fileNamePath, error in
                         if !error {
                             self.fileNamesPath[metadataNewFile.fileNameView] = fileNamePath!
                             do {

+ 2 - 1
iOSClient/Networking/NCNetworkingProcessUpload.swift

@@ -149,7 +149,8 @@ class NCNetworkingProcessUpload: NSObject {
                         }
 
                         let semaphore = DispatchSemaphore(value: 0)
-                        NCUtility.shared.extractFiles(from: metadata, viewController: viewController, hud: hud) { metadatas in
+                        let cameraRoll = NCCameraRoll()
+                        cameraRoll.extractCameraRoll(from: metadata, viewController: viewController, hud: hud) { metadatas in
                             if metadatas.isEmpty {
                                 NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
                             }

+ 2 - 1
iOSClient/Transfers/NCTransfers.swift

@@ -136,7 +136,8 @@ class NCTransfers: NCCollectionViewCommon, NCTransferCellDelegate {
         guard let metadata = metadataTemp else { return }
         guard appDelegate.account == metadata.account else { return }
 
-        NCUtility.shared.extractFiles(from: metadata, viewController: self, hud: JGProgressHUD()) { metadatas in
+        let cameraRoll = NCCameraRoll()
+        cameraRoll.extractCameraRoll(from: metadata, viewController: self, hud: JGProgressHUD()) { metadatas in
             for metadata in metadatas {
                 if let metadata = NCManageDatabase.shared.setMetadataStatus(ocId: metadata.ocId, status: NCGlobal.shared.metadataStatusInUpload) {
                     NCNetworking.shared.upload(metadata: metadata)

+ 270 - 0
iOSClient/Utility/NCCameraRoll.swift

@@ -0,0 +1,270 @@
+//
+//  NCCameraRoll.swift
+//  Nextcloud
+//
+//  Created by Marino Faggiana on 21/12/22.
+//  Copyright © 2022 Marino Faggiana. All rights reserved.
+//
+//  Author Marino Faggiana <marino.faggiana@nextcloud.com>
+//
+//  This program is free software: you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation, either version 3 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+//
+
+import Foundation
+import NextcloudKit
+import JGProgressHUD
+
+class NCCameraRoll: NSObject {
+
+    func extractCameraRoll(from metadata: tableMetadata, viewController: UIViewController?, hud: JGProgressHUD, completition: @escaping (_ metadatas: [tableMetadata]) -> Void) {
+
+        let chunckSize = CCUtility.getChunkSize() * 1000000
+        var metadatas: [tableMetadata] = []
+        let metadataSource = tableMetadata.init(value: metadata)
+
+        guard !metadata.isExtractFile else { return  completition([metadataSource]) }
+        guard !metadataSource.assetLocalIdentifier.isEmpty else {
+            let filePath = CCUtility.getDirectoryProviderStorageOcId(metadataSource.ocId, fileNameView: metadataSource.fileName)!
+            metadataSource.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
+            let results = NKCommon.shared.getInternalType(fileName: metadataSource.fileNameView, mimeType: metadataSource.contentType, directory: false)
+            metadataSource.contentType = results.mimeType
+            metadataSource.iconName = results.iconName
+            metadataSource.classFile = results.classFile
+            if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: filePath) {
+                metadataSource.creationDate = date
+            }
+            if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: filePath) {
+                metadataSource.date = date
+            }
+            metadataSource.chunk = chunckSize != 0 && metadata.size > chunckSize
+            metadataSource.isExtractFile = true
+            if let metadata = NCManageDatabase.shared.addMetadata(metadataSource) {
+                metadatas.append(metadata)
+            }
+            return completition(metadatas)
+        }
+
+        extractImageVideoFromAssetLocalIdentifier(metadata: metadataSource, modifyMetadataForUpload: true, viewController: viewController, hud: hud) { metadata, fileNamePath, error in
+            if let metadata = metadata, let fileNamePath = fileNamePath, !error {
+                metadatas.append(metadata)
+                let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
+                NCUtilityFileSystem.shared.moveFile(atPath: fileNamePath, toPath: toPath)
+                let fetchAssets = PHAsset.fetchAssets(withLocalIdentifiers: [metadataSource.assetLocalIdentifier], options: nil)
+                if metadata.livePhoto, fetchAssets.count > 0 {
+                    self.createMetadataLivePhotoFromMetadata(metadata, asset: fetchAssets.firstObject) { metadata in
+                        if let metadata = metadata, let metadata = NCManageDatabase.shared.addMetadata(metadata) {
+                            metadatas.append(metadata)
+                        }
+                        completition(metadatas)
+                    }
+                } else {
+                    completition(metadatas)
+                }
+            } else {
+                completition(metadatas)
+            }
+        }
+    }
+
+    func extractImageVideoFromAssetLocalIdentifier(metadata: tableMetadata,
+                                                   modifyMetadataForUpload: Bool,
+                                                   viewController: UIViewController?,
+                                                   hud: JGProgressHUD,
+                                                   completion: @escaping (_ metadata: tableMetadata?, _ fileNamePath: String?, _ error: Bool) -> Void) {
+
+        var fileNamePath: String?
+        let metadata = tableMetadata.init(value: metadata)
+        let chunckSize = CCUtility.getChunkSize() * 1000000
+        var compatibilityFormat: Bool = false
+        let isDirectoryE2EE = NCUtility.shared.isDirectoryE2EE(metadata: metadata)
+
+        func callCompletionWithError(_ error: Bool = true) {
+            if error {
+                completion(nil, nil, true)
+            } else {
+                var metadataReturn = metadata
+                if modifyMetadataForUpload {
+                    metadata.chunk = chunckSize != 0 && metadata.size > chunckSize
+                    metadata.isExtractFile = true
+                    if let metadata = NCManageDatabase.shared.addMetadata(metadata) {
+                        metadataReturn = metadata
+                    }
+                }
+                completion(metadataReturn, fileNamePath, error)
+            }
+        }
+
+        let fetchAssets = PHAsset.fetchAssets(withLocalIdentifiers: [metadata.assetLocalIdentifier], options: nil)
+        guard fetchAssets.count > 0, let asset = fetchAssets.firstObject, let extensionAsset = (asset.value(forKey: "filename") as? NSString)?.pathExtension.uppercased() else {
+            return callCompletionWithError()
+        }
+
+        let creationDate = asset.creationDate ?? Date()
+        let modificationDate = asset.modificationDate ?? Date()
+
+        if asset.mediaType == PHAssetMediaType.image && (extensionAsset == "HEIC" || extensionAsset == "DNG") && CCUtility.getFormatCompatibility() {
+            let fileName = (metadata.fileNameView as NSString).deletingPathExtension + ".jpg"
+            metadata.contentType = "image/jpeg"
+            fileNamePath = NSTemporaryDirectory() + fileName
+            metadata.fileNameView = fileName
+            if !isDirectoryE2EE {
+                metadata.fileName = fileName
+            }
+            compatibilityFormat = true
+        } else {
+            fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
+        }
+
+        guard let fileNamePath = fileNamePath else { return callCompletionWithError() }
+
+        if asset.mediaType == PHAssetMediaType.image {
+
+            let options = PHImageRequestOptions()
+            options.isNetworkAccessAllowed = true
+            if compatibilityFormat {
+                options.deliveryMode = .opportunistic
+            } else {
+                options.deliveryMode = .highQualityFormat
+            }
+            options.isSynchronous = true
+            if extensionAsset == "DNG" {
+                options.version = PHImageRequestOptionsVersion.original
+            }
+            options.progressHandler = { progress, error, _, _ in
+                print(progress)
+                if error != nil { return callCompletionWithError() }
+            }
+
+            PHImageManager.default().requestImageDataAndOrientation(for: asset, options: options) { data, _, _, _ in
+                guard var data = data else { return callCompletionWithError() }
+                if compatibilityFormat {
+                    guard let ciImage = CIImage(data: data), let colorSpace = ciImage.colorSpace, let dataJPEG = CIContext().jpegRepresentation(of: ciImage, colorSpace: colorSpace) else { return callCompletionWithError() }
+                    data = dataJPEG
+                }
+                NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
+                do {
+                    try data.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
+                } catch { return callCompletionWithError() }
+                metadata.creationDate = creationDate as NSDate
+                metadata.date = modificationDate as NSDate
+                metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
+                return callCompletionWithError(false)
+            }
+
+        } else if asset.mediaType == PHAssetMediaType.video {
+
+            let options = PHVideoRequestOptions()
+            options.isNetworkAccessAllowed = true
+            options.version = PHVideoRequestOptionsVersion.current
+            options.progressHandler = { progress, error, _, _ in
+                print(progress)
+                if error != nil { return callCompletionWithError() }
+            }
+
+            PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { asset, _, _ in
+                if let asset = asset as? AVURLAsset {
+                    NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
+                    do {
+                        try FileManager.default.copyItem(at: asset.url, to: URL(fileURLWithPath: fileNamePath))
+                        metadata.creationDate = creationDate as NSDate
+                        metadata.date = modificationDate as NSDate
+                        metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
+                        return callCompletionWithError(false)
+                    } catch { return callCompletionWithError() }
+                } else if let asset = asset as? AVComposition, asset.tracks.count > 1, let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality), let viewController = viewController {
+                    DispatchQueue.main.async {
+                        hud.indicatorView = JGProgressHUDRingIndicatorView()
+                        if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
+                            indicatorView.ringWidth = 1.5
+                        }
+                        hud.textLabel.text = NSLocalizedString("_exporting_video_", comment: "")
+                        hud.show(in: viewController.view)
+                        hud.tapOnHUDViewBlock = { _ in
+                            exporter.cancelExport()
+                        }
+                    }
+                    exporter.outputURL = URL(fileURLWithPath: fileNamePath)
+                    exporter.outputFileType = AVFileType.mp4
+                    exporter.shouldOptimizeForNetworkUse = true
+                    exporter.exportAsynchronously {
+                        DispatchQueue.main.async { hud.dismiss() }
+                        if exporter.status == .completed {
+                            metadata.creationDate = creationDate as NSDate
+                            metadata.date = modificationDate as NSDate
+                            metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
+                            return callCompletionWithError(false)
+                        } else { return callCompletionWithError() }
+                    }
+                    while exporter.status == AVAssetExportSession.Status.exporting || exporter.status == AVAssetExportSession.Status.waiting {
+                        hud.progress = exporter.progress
+                    }
+                } else {
+                    return callCompletionWithError()
+                }
+            }
+        } else {
+            return callCompletionWithError()
+        }
+    }
+
+    private func createMetadataLivePhotoFromMetadata(_ metadata: tableMetadata,
+                                                     asset: PHAsset?,
+                                                     completion: @escaping (_ metadata: tableMetadata?) -> Void) {
+
+        guard let asset = asset else { return completion(nil) }
+        let options = PHLivePhotoRequestOptions()
+        options.deliveryMode = PHImageRequestOptionsDeliveryMode.fastFormat
+        options.isNetworkAccessAllowed = true
+        let chunckSize = CCUtility.getChunkSize() * 1000000
+        let ocId = NSUUID().uuidString
+        let fileName = (metadata.fileName as NSString).deletingPathExtension + ".mov"
+        let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
+
+        PHImageManager.default().requestLivePhoto(for: asset, targetSize: UIScreen.main.bounds.size, contentMode: PHImageContentMode.default, options: options) { livePhoto, _ in
+            guard let livePhoto = livePhoto else { return completion(nil) }
+            var videoResource: PHAssetResource?
+            for resource in PHAssetResource.assetResources(for: livePhoto) where resource.type == PHAssetResourceType.pairedVideo {
+                videoResource = resource
+                break
+            }
+            guard let videoResource = videoResource else { return completion(nil) }
+            NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
+            PHAssetResourceManager.default().writeData(for: videoResource, toFile: URL(fileURLWithPath: fileNamePath), options: nil) { error in
+                if error != nil { return completion(nil) }
+                let metadataLivePhoto = NCManageDatabase.shared.createMetadata(account: metadata.account,
+                                                                               user: metadata.user,
+                                                                               userId: metadata.userId,
+                                                                               fileName: fileName,
+                                                                               fileNameView: fileName,
+                                                                               ocId: ocId,
+                                                                               serverUrl: metadata.serverUrl,
+                                                                               urlBase: metadata.urlBase,
+                                                                               url: "",
+                                                                               contentType: "",
+                                                                               isLivePhoto: true)
+                metadataLivePhoto.classFile = NKCommon.typeClassFile.video.rawValue
+                metadataLivePhoto.isExtractFile = true
+                metadataLivePhoto.session = metadata.session
+                metadataLivePhoto.sessionSelector = metadata.sessionSelector
+                metadataLivePhoto.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
+                metadataLivePhoto.status = metadata.status
+                metadataLivePhoto.chunk = chunckSize != 0 && metadata.size > chunckSize
+                metadataLivePhoto.creationDate = metadata.creationDate
+                metadataLivePhoto.date = metadata.date
+                metadataLivePhoto.uploadDate = metadata.uploadDate
+                return completion(NCManageDatabase.shared.addMetadata(metadataLivePhoto))
+            }
+        }
+    }
+}

+ 1 - 224
iOSClient/Utility/NCUtility.swift

@@ -328,230 +328,7 @@ class NCUtility: NSObject {
 
     // MARK: -
 
-    func extractFiles(from metadata: tableMetadata, viewController: UIViewController?, hud: JGProgressHUD, completition: @escaping (_ metadatas: [tableMetadata]) -> Void) {
-
-        let chunckSize = CCUtility.getChunkSize() * 1000000
-        var metadatas: [tableMetadata] = []
-        let metadataSource = tableMetadata.init(value: metadata)
-
-        guard !metadata.isExtractFile else { return  completition([metadataSource]) }
-        guard !metadataSource.assetLocalIdentifier.isEmpty else {
-            let filePath = CCUtility.getDirectoryProviderStorageOcId(metadataSource.ocId, fileNameView: metadataSource.fileName)!
-            metadataSource.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
-            let results = NKCommon.shared.getInternalType(fileName: metadataSource.fileNameView, mimeType: metadataSource.contentType, directory: false)
-            metadataSource.contentType = results.mimeType
-            metadataSource.iconName = results.iconName
-            metadataSource.classFile = results.classFile
-            if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: filePath) {
-                metadataSource.creationDate = date
-            }
-            if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: filePath) {
-                metadataSource.date = date
-            }
-            metadataSource.chunk = chunckSize != 0 && metadata.size > chunckSize
-            metadataSource.isExtractFile = true
-            if let metadata = NCManageDatabase.shared.addMetadata(metadataSource) {
-                metadatas.append(metadata)
-            }
-            return completition(metadatas)
-        }
-
-        extractImageVideoFromAssetLocalIdentifier(metadata: metadataSource, modifyMetadataForUpload: true, viewController: viewController, hud: hud) { metadata, fileNamePath, error in
-            if let metadata = metadata, let fileNamePath = fileNamePath, !error {
-                metadatas.append(metadata)
-                let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
-                NCUtilityFileSystem.shared.moveFile(atPath: fileNamePath, toPath: toPath)
-                let fetchAssets = PHAsset.fetchAssets(withLocalIdentifiers: [metadataSource.assetLocalIdentifier], options: nil)
-                if metadata.livePhoto, fetchAssets.count > 0  {
-                    NCUtility.shared.createMetadataLivePhotoFromMetadata(metadata, asset: fetchAssets.firstObject) { metadata in
-                        if let metadata = metadata, let metadata = NCManageDatabase.shared.addMetadata(metadata) {
-                            metadatas.append(metadata)
-                        }
-                        completition(metadatas)
-                    }
-                } else {
-                    completition(metadatas)
-                }
-            } else {
-                completition(metadatas)
-            }
-        }
-    }
-
-    func extractImageVideoFromAssetLocalIdentifier(metadata: tableMetadata, modifyMetadataForUpload: Bool, viewController: UIViewController?, hud: JGProgressHUD, completion: @escaping (_ metadata: tableMetadata?, _ fileNamePath: String?, _ error: Bool) -> ()) {
-
-        var fileNamePath: String?
-        let metadata = tableMetadata.init(value: metadata)
-        let chunckSize = CCUtility.getChunkSize() * 1000000
-        var compatibilityFormat: Bool = false
-        let isDirectoryE2EE = NCUtility.shared.isDirectoryE2EE(metadata: metadata)
-
-        func callCompletionWithError(_ error: Bool = true) {
-            if error {
-                completion(nil, nil, true)
-            } else {
-                var metadataReturn = metadata
-                if modifyMetadataForUpload {
-                    metadata.chunk = chunckSize != 0 && metadata.size > chunckSize
-                    metadata.isExtractFile = true
-                    if let metadata = NCManageDatabase.shared.addMetadata(metadata) {
-                        metadataReturn = metadata
-                    }
-                }
-                completion(metadataReturn, fileNamePath, error)
-            }
-        }
-
-        let fetchAssets = PHAsset.fetchAssets(withLocalIdentifiers: [metadata.assetLocalIdentifier], options: nil)
-        guard fetchAssets.count > 0, let asset = fetchAssets.firstObject, let extensionAsset = (asset.value(forKey: "filename") as? NSString)?.pathExtension.uppercased() else { return callCompletionWithError() }
-
-        let creationDate = asset.creationDate ?? Date()
-        let modificationDate = asset.modificationDate ?? Date()
-
-        if asset.mediaType == PHAssetMediaType.image && (extensionAsset == "HEIC" || extensionAsset == "DNG") && CCUtility.getFormatCompatibility() {
-            let fileName = (metadata.fileNameView as NSString).deletingPathExtension + ".jpg"
-            metadata.contentType = "image/jpeg"
-            fileNamePath = NSTemporaryDirectory() + fileName
-            metadata.fileNameView = fileName
-            if !isDirectoryE2EE {
-                metadata.fileName = fileName
-            }
-            compatibilityFormat = true
-        } else {
-            fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
-        }
-
-        guard let fileNamePath = fileNamePath else { return callCompletionWithError() }
-
-        if asset.mediaType == PHAssetMediaType.image {
-
-            let options = PHImageRequestOptions()
-            options.isNetworkAccessAllowed = true
-            if compatibilityFormat {
-                options.deliveryMode = .opportunistic
-            } else {
-                options.deliveryMode = .highQualityFormat
-            }
-            options.isSynchronous = true
-            if extensionAsset == "DNG" {
-                options.version = PHImageRequestOptionsVersion.original
-            }
-            options.progressHandler = { (progress, error, stop, info) in
-                print(progress)
-                if error != nil { return callCompletionWithError() }
-            }
-
-            PHImageManager.default().requestImageDataAndOrientation(for: asset, options: options) { data, dataUI, orientation, info in
-                guard var data = data else { return callCompletionWithError() }
-                if compatibilityFormat {
-                    guard let ciImage = CIImage.init(data: data), let colorSpace = ciImage.colorSpace, let dataJPEG = CIContext().jpegRepresentation(of: ciImage, colorSpace: colorSpace) else { return callCompletionWithError() }
-                    data = dataJPEG
-                }
-                NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
-                do {
-                    try data.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
-                } catch { return callCompletionWithError() }
-                metadata.creationDate = creationDate as NSDate
-                metadata.date = modificationDate as NSDate
-                metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
-                return callCompletionWithError(false)
-            }
-
-        } else if asset.mediaType == PHAssetMediaType.video {
-            
-            let options = PHVideoRequestOptions()
-            options.isNetworkAccessAllowed = true
-            options.version = PHVideoRequestOptionsVersion.current
-            options.progressHandler = { (progress, error, stop, info) in
-                print(progress)
-                if error != nil { return callCompletionWithError() }
-            }
-
-            PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { asset, audioMix, info in
-                if let asset = asset as? AVURLAsset {
-                    NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
-                    do {
-                        try FileManager.default.copyItem(at: asset.url, to: URL(fileURLWithPath: fileNamePath))
-                        metadata.creationDate = creationDate as NSDate
-                        metadata.date = modificationDate as NSDate
-                        metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
-                        return callCompletionWithError(false)
-                    } catch { return callCompletionWithError() }
-                } else if let asset = asset as? AVComposition, asset.tracks.count > 1, let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality), let viewController = viewController {
-                    DispatchQueue.main.async {
-                        hud.indicatorView = JGProgressHUDRingIndicatorView()
-                        if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
-                            indicatorView.ringWidth = 1.5
-                        }
-                        hud.textLabel.text = NSLocalizedString("_exporting_video_", comment: "")
-                        hud.show(in: viewController.view)
-                        hud.tapOnHUDViewBlock = { hud in
-                            exporter.cancelExport()
-                        }
-                    }
-                    exporter.outputURL = URL(fileURLWithPath: fileNamePath)
-                    exporter.outputFileType = AVFileType.mp4
-                    exporter.shouldOptimizeForNetworkUse = true
-                    exporter.exportAsynchronously {
-                        DispatchQueue.main.async { hud.dismiss() }
-                        if exporter.status == .completed {
-                            metadata.creationDate = creationDate as NSDate
-                            metadata.date = modificationDate as NSDate
-                            metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
-                            return callCompletionWithError(false)
-                        } else { return callCompletionWithError() }
-                    }
-                    while exporter.status == AVAssetExportSession.Status.exporting || exporter.status == AVAssetExportSession.Status.waiting {
-                        hud.progress = exporter.progress
-                    }
-                } else {
-                    return callCompletionWithError()
-                }
-            }
-        } else {
-            return callCompletionWithError()
-        }
-    }
-
-    func createMetadataLivePhotoFromMetadata(_ metadata: tableMetadata, asset: PHAsset?, completion: @escaping (_ metadata: tableMetadata?) -> ()) {
-
-        guard let asset = asset else { return completion(nil) }
-        let options = PHLivePhotoRequestOptions()
-        options.deliveryMode = PHImageRequestOptionsDeliveryMode.fastFormat
-        options.isNetworkAccessAllowed = true
-        let chunckSize = CCUtility.getChunkSize() * 1000000
-        let ocId = NSUUID().uuidString
-        let fileName = (metadata.fileName as NSString).deletingPathExtension + ".mov"
-        let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
-
-        PHImageManager.default().requestLivePhoto(for: asset, targetSize: UIScreen.main.bounds.size, contentMode: PHImageContentMode.default, options: options) { livePhoto, info in
-            guard let livePhoto = livePhoto else { return completion(nil) }
-            var videoResource: PHAssetResource?
-            for resource in PHAssetResource.assetResources(for: livePhoto) {
-                if resource.type == PHAssetResourceType.pairedVideo {
-                    videoResource = resource
-                    break
-                }
-            }
-            guard let videoResource = videoResource else { return completion(nil) }
-            NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
-            PHAssetResourceManager.default().writeData(for: videoResource, toFile: URL(fileURLWithPath: fileNamePath), options: nil) { error in
-                if error != nil { return completion(nil) }
-                let metadataLivePhoto = NCManageDatabase.shared.createMetadata(account: metadata.account, user: metadata.user, userId: metadata.userId, fileName: fileName, fileNameView: fileName, ocId: ocId, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, url: "", contentType: "", isLivePhoto: true)
-                metadataLivePhoto.classFile = NKCommon.typeClassFile.video.rawValue
-                metadataLivePhoto.isExtractFile = true
-                metadataLivePhoto.session = metadata.session
-                metadataLivePhoto.sessionSelector = metadata.sessionSelector
-                metadataLivePhoto.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
-                metadataLivePhoto.status = metadata.status
-                metadataLivePhoto.chunk = chunckSize != 0 && metadata.size > chunckSize
-                metadataLivePhoto.creationDate = metadata.creationDate
-                metadataLivePhoto.date = metadata.date
-                metadataLivePhoto.uploadDate = metadata.uploadDate
-                return completion(NCManageDatabase.shared.addMetadata(metadataLivePhoto))
-            }
-        }
-    }
+    
 
     func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {