瀏覽代碼

coding

Signed-off-by: marinofaggiana <ios@nextcloud.com>
marinofaggiana 2 年之前
父節點
當前提交
d501dd9848

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

@@ -397,16 +397,12 @@ extension NCCreateFormUploadConflict: UITableViewDataSource {
                 } else {
 
                     // PREVIEW
-                    CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadataNewFile, queue: .main) { metadataNew, fileNamePath in
-
-                        if metadataNew != nil {
+                    NCUtility.shared.extractImageVideoFromAssetLocalIdentifier(metadata: metadataNewFile, modifyMetadataForUpload: false, queue: .main) { metadata, fileNamePath, error in
+                        if !error {
                             self.fileNamesPath[metadataNewFile.fileNameView] = fileNamePath!
-
                             do {
-
                                 let fileDictionary = try FileManager.default.attributesOfItem(atPath: fileNamePath!)
                                 let fileSize = fileDictionary[FileAttributeKey.size] as! Int64
-
                                 if mediaType == PHAssetMediaType.image {
                                     let data = try Data(contentsOf: URL(fileURLWithPath: fileNamePath!))
                                     if let image = UIImage(data: data) {
@@ -417,9 +413,7 @@ extension NCCreateFormUploadConflict: UITableViewDataSource {
                                         cell.imageNewFile.image = image
                                     }
                                 }
-
                                 cell.labelDetailNewFile.text = CCUtility.dateDiff(date) + "\n" + CCUtility.transformedSize(fileSize)
-
                             } catch { print("Error: \(error)") }
                         }
                     }

+ 4 - 4
iOSClient/Networking/NCNetworkingProcessUpload.swift

@@ -223,9 +223,9 @@ class NCNetworkingProcessUpload: NSObject {
         if metadata.livePhoto, fetchAssets.count > 0  {
             let ocId = NSUUID().uuidString
             let fileName = (metadata.fileName as NSString).deletingPathExtension + ".mov"
-            let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
-            CCUtility.extractLivePhotoAsset(fetchAssets.firstObject, filePath: filePath, queue: queue) { url in
-                if url != nil {
+            let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
+            NCUtility.shared.extractLivePhoto(asset: fetchAssets.firstObject,  fileNamePath: fileNamePath, queue: queue) { error in
+                if !error {
                     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 = NCCommunicationCommon.typeClassFile.video.rawValue
                     metadataLivePhoto.e2eEncrypted = metadata.e2eEncrypted
@@ -233,7 +233,7 @@ class NCNetworkingProcessUpload: NSObject {
                     metadataLivePhoto.isExtractFile = true
                     metadataLivePhoto.session = metadata.session
                     metadataLivePhoto.sessionSelector = metadata.sessionSelector
-                    metadataLivePhoto.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
+                    metadataLivePhoto.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
                     metadataLivePhoto.status = metadata.status
                     if chunckSize > 0 && metadataLivePhoto.size > chunckSize {
                         metadataLivePhoto.chunk = true

+ 0 - 3
iOSClient/Utility/CCUtility.h

@@ -243,9 +243,6 @@
 
 + (NSString *)getMimeType:(NSString *)fileNameView;
 
-+ (void)extractImageVideoFromAssetLocalIdentifierForUpload:(tableMetadata *)metadataForUpload queue:(dispatch_queue_t)queue completion:(void(^)(tableMetadata *newMetadata, NSString* fileNamePath))completion;
-+ (void)extractLivePhotoAsset:(PHAsset*)asset filePath:(NSString *)filePath queue:(dispatch_queue_t)queue withCompletion:(void (^)(NSURL* url))completion;
-
 // ===== E2E Encrypted =====
 
 + (NSString *)generateRandomIdentifier;

+ 0 - 176
iOSClient/Utility/CCUtility.m

@@ -1352,182 +1352,6 @@
     return path;
 }
 
-+ (void)extractImageVideoFromAssetLocalIdentifierForUpload:(tableMetadata *)metadataForUpload queue:(dispatch_queue_t)queue completion:(void(^)(tableMetadata *metadata, NSString* fileNamePath))completion
-{
-    if (metadataForUpload == nil) {
-        dispatch_async(queue, ^{
-            completion(nil, nil);
-        });
-        return;
-    }
-    
-    tableMetadata *metadata = [[NCManageDatabase shared] copyObjectWithMetadata:metadataForUpload];
-    
-    PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
-    if (!result.count) {
-        dispatch_async(queue, ^{
-            completion(nil, nil);
-        });
-        return;
-    }
-    
-    PHAsset *asset = result[0];
-    NSDate *creationDate = asset.creationDate;
-    NSDate *modificationDate = asset.modificationDate;
-
-    // IMAGE
-    if (asset.mediaType == PHAssetMediaTypeImage) {
-
-        PHImageRequestOptions *options = [PHImageRequestOptions new];
-        options.networkAccessAllowed = YES;
-        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
-        options.synchronous = YES;
-        options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
-
-            NSLog(@"cacheAsset: %f", progress);
-
-            if (error) {
-                [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCGlobal.shared.notificationCenterUploadedFile object:nil userInfo:@{@"ocId": metadata.ocId, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Image request iCloud failed [%@]", error.description]}];
-                dispatch_async(queue, ^{
-                    completion(nil, nil);
-                });
-                return;
-            }
-        };
-
-        NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
-
-        //raw image will always ignore any edits made to the photo if compatibility is false
-        if ([extensionAsset isEqualToString:@"DNG"]) {
-            options.version = PHImageRequestOptionsVersionOriginal;
-        }
-
-        [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
-
-            NSError *error = nil;
-            NSString *fileName = metadata.fileNameView;
-
-            if (([extensionAsset isEqualToString:@"HEIC"] || [extensionAsset isEqualToString:@"DNG"]) && [CCUtility getFormatCompatibility]) {
-
-                CIImage *ciImage = [CIImage imageWithData:imageData];
-                CIContext *context = [CIContext context];
-                imageData = [context JPEGRepresentationOfImage:ciImage colorSpace:ciImage.colorSpace options:@{}];
-
-                NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
-                fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
-                metadata.contentType = @"image/jpeg";
-                metadata.ext = @"jpg";
-            }
-
-            NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:fileName];
-
-            [[NSFileManager defaultManager]removeItemAtPath:fileNamePath error:nil];
-            [imageData writeToFile:fileNamePath options:NSDataWritingAtomic error:&error];
-
-            if (metadata.e2eEncrypted) {
-                metadata.fileNameView = fileName;
-            } else {
-                metadata.fileNameView = fileName;
-                metadata.fileName = fileName;
-            }
-
-            metadata.creationDate = creationDate;
-            metadata.date = modificationDate;
-            metadata.size = [[NCUtilityFileSystem shared] getFileSizeWithFilePath:fileNamePath];
-
-            dispatch_async(queue, ^{
-                completion(metadata, fileNamePath);
-            });
-        }];
-    }
-
-    // VIDEO
-    if (asset.mediaType == PHAssetMediaTypeVideo) {
-
-        PHVideoRequestOptions *options = [PHVideoRequestOptions new];
-        options.networkAccessAllowed = YES;
-        options.version = PHVideoRequestOptionsVersionOriginal;
-        options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
-
-            NSLog(@"cacheAsset: %f", progress);
-
-            if (error) {
-                [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCGlobal.shared.notificationCenterUploadedFile object:nil userInfo:@{@"ocId": metadata.ocId, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description]}];
-                dispatch_async(queue, ^{
-                    completion(nil, nil);
-                });
-                return;
-            }
-        };
-
-        [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
-
-            if ([asset isKindOfClass:[AVURLAsset class]]) {
-
-                NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView];
-                NSURL *fileNamePathURL = [[NSURL alloc] initFileURLWithPath:fileNamePath];
-                NSError *error = nil;
-
-                [[NSFileManager defaultManager] removeItemAtURL:fileNamePathURL error:nil];
-                [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileNamePathURL error:&error];
-
-                dispatch_async(queue, ^{
-                    if (error) {
-                        [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCGlobal.shared.notificationCenterUploadedFile object:nil userInfo:@{@"ocId": metadata.ocId, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description]}];
-                        completion(nil, nil);
-                    } else {
-                        metadata.creationDate = creationDate;
-                        metadata.date = modificationDate;
-                        metadata.size = [[NCUtilityFileSystem shared] getFileSizeWithFilePath:fileNamePath];
-                        completion(metadata, fileNamePath);
-                    }
-                });
-            }
-        }];
-    }
-}
-
-+ (void)extractLivePhotoAsset:(PHAsset*)asset filePath:(NSString *)filePath queue:(dispatch_queue_t)queue withCompletion:(void (^)(NSURL* url))completion
-{    
-    [CCUtility removeFileAtPath:filePath];
-    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
-    PHLivePhotoRequestOptions *options = [PHLivePhotoRequestOptions new];
-    options.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
-    options.networkAccessAllowed = YES;
-    
-    [[PHImageManager defaultManager] requestLivePhotoForAsset:asset targetSize:[UIScreen mainScreen].bounds.size contentMode:PHImageContentModeDefault options:options resultHandler:^(PHLivePhoto * _Nullable livePhoto, NSDictionary * _Nullable info) {
-        if (livePhoto) {
-            NSArray *assetResources = [PHAssetResource assetResourcesForLivePhoto:livePhoto];
-            PHAssetResource *videoResource = nil;
-            for(PHAssetResource *resource in assetResources){
-                if (resource.type == PHAssetResourceTypePairedVideo) {
-                    videoResource = resource;
-                    break;
-                }
-            }
-            if(videoResource){
-                [[PHAssetResourceManager defaultManager] writeDataForAssetResource:videoResource toFile:fileUrl options:nil completionHandler:^(NSError * _Nullable error) {
-                    dispatch_async(queue, ^{
-                        if (!error) {
-                            completion(fileUrl);
-                        } else {
-                            completion(nil);
-                        }
-                    });
-                }];
-            } else {
-                dispatch_async(queue, ^{
-                    completion(nil);
-                });
-            }
-        } else {
-            dispatch_async(queue, ^{
-                completion(nil);
-            });
-        }
-    }];
-}
-
 #pragma --------------------------------------------------------------------------------------------
 #pragma mark ===== E2E Encrypted =====
 #pragma --------------------------------------------------------------------------------------------

+ 24 - 0
iOSClient/Utility/NCUtility.swift

@@ -29,6 +29,7 @@ import PDFKit
 import Accelerate
 import CoreMedia
 import Queuer
+import Photos
 
 class NCUtility: NSObject {
     @objc static let shared: NCUtility = {
@@ -512,6 +513,29 @@ class NCUtility: NSObject {
         }
     }
 
+    func extractLivePhoto(asset: PHAsset?, fileNamePath: String, queue: DispatchQueue, completion: @escaping (_ error: Bool) -> ()) {
+
+        guard let asset = asset else { return queue.async { completion(true) }}
+        let options = PHLivePhotoRequestOptions()
+        options.deliveryMode = PHImageRequestOptionsDeliveryMode.fastFormat
+        options.isNetworkAccessAllowed = true
+
+        PHImageManager.default().requestLivePhoto(for: asset, targetSize: UIScreen.main.bounds.size, contentMode: PHImageContentMode.default, options: options) { livePhoto, info in
+            guard let livePhoto = livePhoto else { return queue.async { completion(true) }}
+            var videoResource: PHAssetResource?
+            for resource in PHAssetResource.assetResources(for: livePhoto) {
+                if resource.type == PHAssetResourceType.pairedVideo {
+                    videoResource = resource
+                    break
+                }
+            }
+            guard let videoResource = videoResource else { return queue.async { completion(true) }}
+            PHAssetResourceManager.default().writeData(for: videoResource, toFile: URL(fileURLWithPath: fileNamePath), options: nil) { error in
+                queue.async { completion(error != nil) }
+            }
+        }
+    }
+
     func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
 
         let asset = AVURLAsset(url: url)