浏览代码

coding

Signed-off-by: marinofaggiana <ios@nextcloud.com>
marinofaggiana 2 年之前
父节点
当前提交
d121e2128a

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

@@ -391,7 +391,7 @@ extension NCCreateFormUploadConflict: UITableViewDataSource {
 
                 } else {
 
-                    CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadataNewFile) { metadataNew, fileNamePath in
+                    CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadataNewFile, queue: .main) { metadataNew, fileNamePath in
 
                         if metadataNew != nil {
                             self.fileNamesPath[metadataNewFile.fileNameView] = fileNamePath!

+ 1 - 1
iOSClient/Networking/NCNetworking.swift

@@ -489,7 +489,7 @@ import Photos
 
         } else {
 
-            CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata) { extractMetadata, fileNamePath in
+            CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata, queue: .main) { extractMetadata, fileNamePath in
 
                 guard let metadata = extractMetadata else {
                     NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))

+ 16 - 6
iOSClient/Networking/NCNetworkingProcessUpload.swift

@@ -24,6 +24,7 @@
 import UIKit
 import NCCommunication
 import Photos
+import Queuer
 
 class NCNetworkingProcessUpload: NSObject {
 
@@ -55,6 +56,7 @@ class NCNetworkingProcessUpload: NSObject {
     @objc private func process() {
         guard !appDelegate.account.isEmpty else { return }
 
+        let queue = DispatchQueue.global(qos: .background)
         var counterUpload: Int = 0
         let sessionSelectors = [NCGlobal.shared.selectorUploadFile, NCGlobal.shared.selectorUploadAutoUpload, NCGlobal.shared.selectorUploadAutoUploadAll]
         let metadatasUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "status == %d OR status == %d", NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading))
@@ -65,7 +67,7 @@ class NCNetworkingProcessUpload: NSObject {
 
         print("[LOG] PROCESS-UPLOAD \(counterUpload)")
 
-        NCNetworking.shared.getOcIdInBackgroundSession(queue: DispatchQueue.global(qos: .background), completion: { listOcId in
+        NCNetworking.shared.getOcIdInBackgroundSession(queue: queue, completion: { listOcId in
 
             for sessionSelector in sessionSelectors {
                 if counterUpload < self.maxConcurrentOperationUpload {
@@ -107,11 +109,12 @@ class NCNetworkingProcessUpload: NSObject {
                         }
 
                         // OK EXTRACT
+                        let semaphore = Semaphore()
                         if !metadata.assetLocalIdentifier.isEmpty {
-                            CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata) { extractMetadata, fileNamePath in
+                            CCUtility.extractImageVideoFromAssetLocalIdentifier(forUpload: metadata, queue: queue) { extractMetadata, fileNamePath in
                                 if let metadata = extractMetadata {
                                     let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
-                                    NCUtilityFileSystem.shared.moveFileInBackground(atPath: fileNamePath!, toPath: toPath)
+                                    NCUtilityFileSystem.shared.moveFile(atPath: fileNamePath!, toPath: toPath)
                                     metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: toPath)
                                     // DETECT IF CHUNCK
                                     if chunckSize > 0 && metadata.size > chunckSize {
@@ -130,7 +133,7 @@ class NCNetworkingProcessUpload: NSObject {
                                             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) { url in
+                                            CCUtility.extractLivePhotoAsset(fetchAssets.firstObject, filePath: filePath, queue: queue) { url in
                                                 if url != 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 = NCCommunicationCommon.typeClassFile.video.rawValue
@@ -146,17 +149,24 @@ class NCNetworkingProcessUpload: NSObject {
                                                     }
                                                     metadataLivePhotoForUpload = NCManageDatabase.shared.addMetadata(metadataLivePhoto)
                                                 }
+                                                semaphore.continue()
                                             }
+                                        } else {
+                                            semaphore.continue()
                                         }
+                                    } else {
+                                        semaphore.continue()
                                     }
                                 } else {
                                     NCManageDatabase.shared.deleteMetadata(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
+                                    semaphore.continue()
                                 }
                             }
                         } else {
-
+                            semaphore.continue()
                         }
-
+                        semaphore.wait()
+                        
                         // Chunk 
                         if metadata.chunk && UIApplication.shared.applicationState == .active {
 //                            if metadata.session == NCNetworking.shared.sessionIdentifierBackgroundWWan && metadata.isAutoupload && NCNetworking.shared.networkReachability != NCCommunicationCommon.typeReachability.reachableEthernetOrWiFi {

+ 2 - 2
iOSClient/Utility/CCUtility.h

@@ -243,8 +243,8 @@
 
 + (NSString *)getMimeType:(NSString *)fileNameView;
 
-+ (void)extractImageVideoFromAssetLocalIdentifierForUpload:(tableMetadata *)metadataForUpload completion:(void(^)(tableMetadata *newMetadata, NSString* fileNamePath))completion;
-+ (void)extractLivePhotoAsset:(PHAsset*)asset filePath:(NSString *)filePath withCompletion:(void (^)(NSURL* url))completion;
++ (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 =====
 

+ 131 - 113
iOSClient/Utility/CCUtility.m

@@ -1352,136 +1352,142 @@
     return path;
 }
 
-+ (void)extractImageVideoFromAssetLocalIdentifierForUpload:(tableMetadata *)metadataForUpload completion:(void(^)(tableMetadata *metadata, NSString* fileNamePath))completion
++ (void)extractImageVideoFromAssetLocalIdentifierForUpload:(tableMetadata *)metadataForUpload queue:(dispatch_queue_t)queue completion:(void(^)(tableMetadata *metadata, NSString* fileNamePath))completion
 {
     if (metadataForUpload == nil) {
-        return completion(nil, 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) {
-        return completion(nil, nil);
+        dispatch_async(queue, ^{
+            completion(nil, nil);
+        });
+        return;
     }
     
     PHAsset *asset = result[0];
     NSDate *creationDate = asset.creationDate;
     NSDate *modificationDate = asset.modificationDate;
 
-    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
-    
-        // 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]}];
-                    return completion(nil, nil);
-                }
-            };
-            
-            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;
+    // IMAGE
+    if (asset.mediaType == PHAssetMediaTypeImage) {
 
-                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(dispatch_get_main_queue(), ^{
-                    completion(metadata, fileNamePath);
+        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;
         }
-    
-        // 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]}];
+
+        [[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);
-                }
-            };
-            
-            [[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;
-                    //NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: modificationDate, NSFileModificationDate, creationDate, NSFileCreationDate, NULL];
+                });
+                return;
+            }
+        };
 
-                    [[NSFileManager defaultManager] removeItemAtURL:fileNamePathURL error:nil];
-                    [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileNamePathURL error:&error];
-                    //[[NSFileManager defaultManager] setAttributes: attributes ofItemAtPath:fileNamePath error:nil];
+        [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
 
-                    dispatch_async(dispatch_get_main_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);
-                        }
-                    });
-                }
-            }];
-        }
-    });
+            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 withCompletion:(void (^)(NSURL* url))completion
++ (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];
@@ -1501,12 +1507,24 @@
             }
             if(videoResource){
                 [[PHAssetResourceManager defaultManager] writeDataForAssetResource:videoResource toFile:fileUrl options:nil completionHandler:^(NSError * _Nullable error) {
-                    if (!error) {
-                        completion(fileUrl);
-                    } else { completion(nil); }
+                    dispatch_async(queue, ^{
+                        if (!error) {
+                            completion(fileUrl);
+                        } else {
+                            completion(nil);
+                        }
+                    });
                 }];
-            } else { completion(nil); }
-        } else { completion(nil); }
+            } else {
+                dispatch_async(queue, ^{
+                    completion(nil);
+                });
+            }
+        } else {
+            dispatch_async(queue, ^{
+                completion(nil);
+            });
+        }
     }];
 }