Jelajahi Sumber

New class AutoUpload

Marino Faggiana 7 tahun lalu
induk
melakukan
ae815a050d

+ 0 - 4
Nextcloud.xcodeproj/project.pbxproj

@@ -557,7 +557,6 @@
 		F7A377161EB2364A002856D3 /* Crashlytics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F7A377141EB2364A002856D3 /* Crashlytics.framework */; };
 		F7A3771A1EB2364A002856D3 /* Fabric.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F7A377151EB2364A002856D3 /* Fabric.framework */; };
 		F7B0C0CD1EE7E7750033AC24 /* CCSynchronize.m in Sources */ = {isa = PBXBuildFile; fileRef = F7B0C0CC1EE7E7750033AC24 /* CCSynchronize.m */; };
-		F7B0C1721EE8397E0033AC24 /* test.txt in Resources */ = {isa = PBXBuildFile; fileRef = F7B0C1711EE8397E0033AC24 /* test.txt */; };
 		F7B0C1751EE839A30033AC24 /* NCAutoUpload.m in Sources */ = {isa = PBXBuildFile; fileRef = F7B0C1741EE839A30033AC24 /* NCAutoUpload.m */; };
 		F7B1FBC41E72E3D1001781FE /* Media.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = F7B1FBB11E72E3D1001781FE /* Media.xcassets */; };
 		F7B1FBC61E72E3D1001781FE /* SwiftModalWebVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7B1FBBF1E72E3D1001781FE /* SwiftModalWebVC.swift */; };
@@ -1606,7 +1605,6 @@
 		F7ACE4311BAC0268006C0017 /* CCSettings.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSettings.m; sourceTree = "<group>"; };
 		F7B0C0CB1EE7E7750033AC24 /* CCSynchronize.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCSynchronize.h; sourceTree = "<group>"; };
 		F7B0C0CC1EE7E7750033AC24 /* CCSynchronize.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CCSynchronize.m; sourceTree = "<group>"; };
-		F7B0C1711EE8397E0033AC24 /* test.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = test.txt; sourceTree = "<group>"; };
 		F7B0C1731EE839A30033AC24 /* NCAutoUpload.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NCAutoUpload.h; sourceTree = "<group>"; };
 		F7B0C1741EE839A30033AC24 /* NCAutoUpload.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NCAutoUpload.m; sourceTree = "<group>"; };
 		F7B1A7731EBB3C8000BFB6D1 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/CTAssetsPicker.strings; sourceTree = "<group>"; };
@@ -3208,7 +3206,6 @@
 		F7B0C1701EE8397E0033AC24 /* AutoUpload */ = {
 			isa = PBXGroup;
 			children = (
-				F7B0C1711EE8397E0033AC24 /* test.txt */,
 				F7B0C1731EE839A30033AC24 /* NCAutoUpload.h */,
 				F7B0C1741EE839A30033AC24 /* NCAutoUpload.m */,
 			);
@@ -4038,7 +4035,6 @@
 				F77B0F211D118A16002130FE /* ZSSh6.png in Resources */,
 				F762CB5D1EACB7D400B38484 /* Reader-Export.png in Resources */,
 				F77B0F231D118A16002130FE /* ZSSh3.png in Resources */,
-				F7B0C1721EE8397E0033AC24 /* test.txt in Resources */,
 				F769D39C1E9E1506006DBBB4 /* CCLocalStorageCell.xib in Resources */,
 				F77B0F251D118A16002130FE /* ZSSh1.png in Resources */,
 				F762CB621EACB7D400B38484 /* Reader-Mark-Y@2x.png in Resources */,

+ 4 - 3
iOSClient/AppDelegate.m

@@ -40,6 +40,7 @@
 #import <Crashlytics/Crashlytics.h>
 #import "JDStatusBarNotification.h"
 #import "NCBridgeSwift.h"
+#import "NCAutoUpload.h"
 
 @interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
 {
@@ -266,7 +267,7 @@
     
     // Fabric
     [Fabric with:@[[Crashlytics class]]];
-    
+        
     return YES;
 }
 
@@ -353,7 +354,7 @@
             [_activeMain requestServerCapabilities];
     
         NSLog(@"[LOG] Initialize Auto upload");
-        [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initStateAutoUpload" object:nil];
+        [[NCAutoUpload sharedInstance] initStateAutoUpload];
         
         NSLog(@"[LOG] Listning Favorites");
         [_activeFavorites readListingFavorites];
@@ -1227,7 +1228,7 @@
     NSLog(@"[LOG] Start perform Fetch With Completion Handler");
     
     // Verify new photo
-    [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initStateAutoUpload" object:nil];
+    [[NCAutoUpload sharedInstance] initStateAutoUpload];
     
     // after 20 sec
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{

+ 12 - 1
iOSClient/AutoUpload/NCAutoUpload.h

@@ -22,7 +22,18 @@
 //
 
 #import <Foundation/Foundation.h>
+#import <Photos/Photos.h>
+#import "CCManageAsset.h"
+#import "CCManageAutoUpload.h"
 
-@interface NCAutoUpload : NSObject
+@interface NCAutoUpload : NSObject <PHPhotoLibraryChangeObserver, CCManageLocationDelegate>
+
++ (NCAutoUpload *)sharedInstance;
+
+@property (nonatomic, strong) PHFetchResult *assetsFetchResult;
+
+- (void)initStateAutoUpload;
+- (BOOL)checkIfLocationIsEnabled;
+- (void)setupAutoUploadFull;
 
 @end

+ 580 - 0
iOSClient/AutoUpload/NCAutoUpload.m

@@ -22,7 +22,587 @@
 //
 
 #import "NCAutoUpload.h"
+#import "AppDelegate.h"
+#import "NCBridgeSwift.h"
+
+@interface NCAutoUpload ()
+{
+    CCHud *_hud;
+}
+@end
 
 @implementation NCAutoUpload
 
++ (NCAutoUpload *)sharedInstance {
+    
+    static NCAutoUpload *sharedInstance;
+    
+    @synchronized(self)
+    {
+        if (!sharedInstance) {
+            
+            sharedInstance = [NCAutoUpload new];
+        }
+        return sharedInstance;
+    }
+}
+
+#pragma --------------------------------------------------------------------------------------------
+#pragma mark ==== Photo Library Change Observer ====
+#pragma --------------------------------------------------------------------------------------------
+
+- (void)photoLibraryDidChange:(PHChange *)changeInfo
+{
+    /*
+     PHFetchResultChangeDetails *collectionChanges = [changeInfo changeDetailsForFetchResult:self.assetsFetchResult];
+     
+     if (collectionChanges) {
+     
+     self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
+     
+     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
+     [self uploadNewAssets];
+     });
+     }
+     */
+}
+
+#pragma --------------------------------------------------------------------------------------------
+#pragma mark === initStateAutoUpload ===
+#pragma --------------------------------------------------------------------------------------------
+
+- (void)initStateAutoUpload
+{
+    tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
+    
+    if (tableAccount.autoUpload) {
+        
+        [self setupAutoUpload];
+        
+        if (tableAccount.autoUploadBackground) {
+         
+            [self checkIfLocationIsEnabled];
+        }
+        
+    } else {
+        
+        [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
+        
+        [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
+        
+        [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
+    }
+}
+
+#pragma --------------------------------------------------------------------------------------------
+#pragma mark === Camera Upload & Full ===
+#pragma --------------------------------------------------------------------------------------------
+
+- (void)setupAutoUpload
+{
+    if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
+        
+        self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
+        
+        [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
+        
+        [self performSelectorOnMainThread:@selector(uploadNewAssets) withObject:nil waitUntilDone:NO];
+        
+    } else {
+        
+        [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
+        
+        [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
+        
+        [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
+        
+        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
+                                                        message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
+                                                       delegate:nil
+                                              cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
+                                              otherButtonTitles:nil];
+        [alert show];
+    }
+}
+
+- (void)setupAutoUploadFull
+{
+    if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
+        
+        self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
+        
+        [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
+        
+        [self performSelectorOnMainThread:@selector(uploadFullAssets) withObject:nil waitUntilDone:NO];
+        
+    } else {
+        
+        [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
+        
+        [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
+        
+        [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
+        
+        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
+                                                        message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
+                                                       delegate:nil
+                                              cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
+                                              otherButtonTitles:nil];
+        [alert show];
+    }
+}
+
+#pragma --------------------------------------------------------------------------------------------
+#pragma mark === Location ===
+#pragma --------------------------------------------------------------------------------------------
+
+- (BOOL)checkIfLocationIsEnabled
+{
+    [CCManageLocation sharedInstance].delegate = self;
+    
+    if ([CLLocationManager locationServicesEnabled]) {
+        
+        NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
+        
+        if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
+            
+            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
+                
+                NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
+                [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
+                
+            } else {
+                
+                if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
+                    
+                    [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
+                    
+                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
+                                                                    message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
+                                                                   delegate:nil
+                                                          cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
+                                                          otherButtonTitles:nil];
+                    [alert show];
+                    
+                } else {
+                    
+                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
+                                                                    message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
+                                                                   delegate:nil
+                                                          cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
+                                                          otherButtonTitles:nil];
+                    [alert show];
+                }
+            }
+            
+        } else {
+            
+            if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
+                
+                [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:YES];
+                [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
+                
+            } else {
+                
+                [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
+                [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
+                
+                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
+                                                                 message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
+                                                                delegate:nil
+                                                       cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
+                                                       otherButtonTitles:nil];
+                [alert show];
+            }
+        }
+        
+    } else {
+        
+        [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
+        [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
+        
+        if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
+            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
+                                                            message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
+                                                           delegate:nil
+                                                  cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
+                                                  otherButtonTitles:nil];
+            [alert show];
+            
+        } else {
+            
+            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
+                                                            message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
+                                                           delegate:nil
+                                                  cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
+                                                  otherButtonTitles:nil];
+            [alert show];
+        }
+    }
+    
+    tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
+    return tableAccount.autoUploadBackground;
+}
+
+
+- (void)statusAuthorizationLocationChanged
+{
+    if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
+        
+        if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
+            
+            ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
+            
+            [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
+                                        usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
+                                            
+                                        } failureBlock:^(NSError *error) {
+                                            
+                                        }];
+        }
+        
+        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
+            
+            if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
+                
+                if ([CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
+                    
+                    [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
+                    [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
+                }
+                
+            } else {
+                
+                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
+                                                                 message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
+                                                                delegate:nil
+                                                       cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
+                                                       otherButtonTitles:nil];
+                [alert show];
+            }
+            
+        } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
+            
+            tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
+            
+            if (tableAccount.autoUploadBackground) {
+                
+                [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
+                [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
+                
+                if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
+                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
+                                                                    message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
+                                                                   delegate:nil
+                                                          cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
+                                                          otherButtonTitles:nil];
+                    [alert show];
+                    
+                } else {
+                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
+                                                                    message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
+                                                                   delegate:nil
+                                                          cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
+                                                          otherButtonTitles:nil];
+                    [alert show];
+                }
+            }
+        }
+        
+        if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
+            
+            [CCManageLocation sharedInstance].firstChangeAuthorizationDone = YES;
+        }
+    }
+}
+
+- (void)changedLocation
+{
+    // Only in background
+    tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
+    
+    if (tableAccount.autoUpload && tableAccount.autoUploadBackground && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
+        
+        
+        if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
+            
+            //check location
+            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
+                
+                NSLog(@"[LOG] Changed Location call uploadNewAssets");
+                
+                [self uploadNewAssets];
+            }
+            
+        } else {
+            
+            [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
+            [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
+            
+            [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
+            [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
+        }
+    }
+}
+
+#pragma --------------------------------------------------------------------------------------------
+#pragma mark ===== Upload Assets : NEW & FULL ====
+#pragma --------------------------------------------------------------------------------------------
+
+- (void)uploadNewAssets
+{
+    [self uploadAssetsNewAndFull:NO];
+}
+
+- (void)uploadFullAssets
+{
+    [self uploadAssetsNewAndFull:YES];
+}
+
+- (void)uploadAssetsNewAndFull:(BOOL)assetsFull
+{
+    CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
+    NSMutableArray *newItemsToUpload;
+    tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
+    
+    // Check Asset : NEW or FULL
+    if (assetsFull) {
+        
+        newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
+        
+    } else {
+        
+        NSDate *databaseDatePhoto = tableAccount.autoUploadDatePhoto;
+        NSDate *databaseDateVideo = tableAccount.autoUploadDateVideo;
+        
+        newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
+    }
+    
+    // News Assets ? if no verify if blocked Table Auto Upload -> Autostart
+    if ([newItemsToUpload count] == 0)
+        return;
+    
+    // Disable idle timer
+    [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
+    
+    if (assetsFull) {
+        
+        if (!_hud)
+            _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
+        
+        [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
+    }
+    
+    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
+        
+        if (assetsFull)
+            [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
+        else
+            [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
+    });
+}
+
+- (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
+{
+    [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
+}
+
+- (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
+{
+    [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
+}
+
+- (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
+{
+    NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
+    tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
+    
+    NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
+    BOOL useSubFolder = tableAccount.autoUploadCreateSubfolder;
+    
+    // Conversion from ALAsset -to-> PHAsset
+    for (ALAsset *asset in newItemsToUpload) {
+        
+        NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
+        PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
+        PHAsset *asset = [fetchResult firstObject];
+        [newItemsPHAssetToUpload addObject:asset];
+        NSLog(@"Convert url %@", url);
+    }
+    
+    // Create the folder for Photos & if request the subfolders
+    if(![app createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:newItemsPHAssetToUpload selector:selectorUploadAutoUploadAll]) {
+        
+        // end loading
+        [_hud hideHud];
+        
+        // Enable idle timer
+        [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
+        
+        return;
+    }
+    
+    for (PHAsset *asset in newItemsPHAssetToUpload) {
+        
+        NSString *serverUrl;
+        NSDate *assetDate = asset.creationDate;
+        PHAssetMediaType assetMediaType = asset.mediaType;
+        NSString *session;
+        NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
+        
+        // Select type of session
+        
+        if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto == NO) session = k_upload_session;
+        if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo == NO) session = k_upload_session;
+        if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto) session = k_upload_session_wwan;
+        if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo) session = k_upload_session_wwan;
+        
+        NSDateFormatter *formatter = [NSDateFormatter new];
+        
+        [formatter setDateFormat:@"yyyy"];
+        NSString *yearString = [formatter stringFromDate:assetDate];
+        
+        [formatter setDateFormat:@"MM"];
+        NSString *monthString = [formatter stringFromDate:assetDate];
+        
+        if (useSubFolder)
+            serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
+        else
+            serverUrl = autoUploadPath;
+        
+        CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
+        
+        metadataNet.action = actionUploadAsset;
+        metadataNet.assetLocalIdentifier = asset.localIdentifier;
+        if (assetsFull) {
+            metadataNet.selector = selectorUploadAutoUploadAll;
+            metadataNet.selectorPost = selectorUploadRemovePhoto;
+            metadataNet.priority = NSOperationQueuePriorityLow;
+        } else {
+            metadataNet.selector = selectorUploadAutoUpload;
+            metadataNet.selectorPost = nil;
+            metadataNet.priority = NSOperationQueuePriorityNormal;
+        }
+        metadataNet.fileName = fileName;
+        metadataNet.serverUrl = serverUrl;
+        metadataNet.session = session;
+        metadataNet.taskStatus = k_taskStatusResume;
+        
+        if (assetsFull)
+            [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
+        else
+            [self writeAssetToSandbox:metadataNet];
+    }
+    
+    // end loading
+    [_hud hideHud];
+    
+    // Enable idle timer
+    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
+}
+
+- (void)writeAssetToSandbox:(CCMetadataNet *)metadataNet
+{
+    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
+    PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
+    
+    PHAsset *asset = result[0];
+    PHAssetMediaType assetMediaType = asset.mediaType;
+    NSDate *assetDate = asset.creationDate;
+    __block NSError *error = nil;
+    
+    // VIDEO
+    if (assetMediaType == PHAssetMediaTypeVideo) {
+        
+        @autoreleasepool {
+            
+            PHVideoRequestOptions *options = [PHVideoRequestOptions new];
+            options.networkAccessAllowed = true;
+            
+            [[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
+                
+                if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]])
+                    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] error:nil];
+                
+                AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:playerItem.asset presetName:AVAssetExportPresetHighestQuality];
+                
+                if (exportSession) {
+                    
+                    exportSession.outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]];
+                    exportSession.outputFileType = AVFileTypeQuickTimeMovie;
+                    
+                    [exportSession exportAsynchronouslyWithCompletionHandler:^{
+                        
+                        if (AVAssetExportSessionStatusCompleted == exportSession.status) {
+                            
+                            [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
+                            
+                        } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
+                            
+                            [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
+                            
+                        } else {
+                            NSLog(@"Export Session Status: %ld", (long)exportSession.status);
+                        }
+                    }];
+                    
+                } else {
+                    
+                    [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
+                }
+            }];
+        }
+    }
+    
+    // IMAGE
+    if (assetMediaType == PHAssetMediaTypeImage) {
+        
+        @autoreleasepool {
+            
+            PHImageRequestOptions *options = [PHImageRequestOptions new];
+            options.synchronous = NO;
+            
+            [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
+                
+                [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] options:NSDataWritingAtomic error:&error];
+                
+                if (error) {
+                    
+                    NSString *note = [NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description];
+                    
+                    [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:note type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
+                    
+                    [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier];
+                    
+                } else {
+                    
+                    [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
+                }
+            }];
+        }
+    }
+}
+
+- (void)addDatabaseAutoUpload:(CCMetadataNet *)metadataNet assetDate:(NSDate *)assetDate assetMediaType:(PHAssetMediaType)assetMediaType
+{
+    if ([[NCManageDatabase sharedInstance] addAutoUploadWithMetadataNet:metadataNet]) {
+        
+        [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutoUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"Add Auto Upload, Asset Data: %@", [NSDateFormatter localizedStringFromDate:assetDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
+        
+    } else {
+        
+        [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutoUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"Add Auto Upload [File already present in Table autoUpload], Asset Data: %@", [NSDateFormatter localizedStringFromDate:assetDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
+    }
+    
+    dispatch_async(dispatch_get_main_queue(), ^{
+        
+        // Update Camera Auto Upload data
+        if ([metadataNet.selector isEqualToString:selectorUploadAutoUpload])
+            [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:assetMediaType assetDate:assetDate];
+        
+        // Update icon badge number
+        [app updateApplicationIconBadgeNumber];
+    });
+}
+
 @end

+ 1 - 6
iOSClient/Photos/CCPhotos.h

@@ -32,20 +32,15 @@
 #import "CCManageLocation.h"
 #import "CCDetail.h"
 #import "CCUtility.h"
-#import "CCManageAsset.h"
-#import "CCManageAutoUpload.h"
 #import "CCSection.h"
 #import "CCHud.h"
 #import "OCNetworking.h"
 
 @class tableMetadata;
 
-@interface CCPhotos: UICollectionViewController <UICollectionViewDataSource, UICollectionViewDelegate, UIActionSheetDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, CCManageLocationDelegate, PHPhotoLibraryChangeObserver, OCNetworkingDelegate>
+@interface CCPhotos: UICollectionViewController <UICollectionViewDataSource, UICollectionViewDelegate, UIActionSheetDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, OCNetworkingDelegate>
 
 @property (nonatomic, weak) CCDetail *detailViewController;
-@property (nonatomic, strong) PHFetchResult *assetsFetchResult;
-
-- (BOOL)checkIfLocationIsEnabled;
 
 - (void)downloadFileSuccess:(tableMetadata *)metadata;
 - (void)downloadFileFailure:(NSInteger)errorCode;

+ 1 - 568
iOSClient/Photos/CCPhotos.m

@@ -23,6 +23,7 @@
 
 #import "CCPhotos.h"
 #import "AppDelegate.h"
+#import "CCManageAutoUpload.h"
 #import "NCBridgeSwift.h"
 
 @interface CCPhotos () <CCActionsDeleteDelegate, CCActionsDownloadThumbnailDelegate>
@@ -50,8 +51,6 @@
 {
     if (self = [super initWithCoder:aDecoder])  {
         
-        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initStateAutoUpload:) name:@"initStateAutoUpload" object:nil];
-        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupAutoUploadFull) name:@"setupAutoUploadFull" object:nil];
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
         
@@ -219,26 +218,6 @@
     }
 }
 
-#pragma --------------------------------------------------------------------------------------------
-#pragma mark ==== Photo Library Change Observer ====
-#pragma --------------------------------------------------------------------------------------------
-
-- (void)photoLibraryDidChange:(PHChange *)changeInfo
-{
-    /*
-     PHFetchResultChangeDetails *collectionChanges = [changeInfo changeDetailsForFetchResult:self.assetsFetchResult];
-     
-     if (collectionChanges) {
-     
-     self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
-     
-     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
-     [self uploadNewAssets];
-     });
-     }
-     */
-}
-
 #pragma --------------------------------------------------------------------------------------------
 #pragma mark ==== DZNEmptyDataSetSource Methods ====
 #pragma --------------------------------------------------------------------------------------------
@@ -751,550 +730,4 @@
     [self.detailViewController setTitle:_metadata.fileNamePrint];
 }
 
-#pragma --------------------------------------------------------------------------------------------
-#pragma mark === initStateAutoUpload ===
-#pragma --------------------------------------------------------------------------------------------
-
-- (void)initStateAutoUpload:(NSNotification *)notification
-{
-    int afterDelay = 0;
-    
-    if (notification.object)
-        afterDelay = [[notification.object objectForKey:@"afterDelay"] intValue];
-    
-    [self performSelector:@selector(initStateAutoUpload) withObject:nil afterDelay:afterDelay];
-}
-
-- (void)initStateAutoUpload
-{
-    tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
-
-    if (tableAccount.autoUpload) {
-        
-        [self setupAutoUpload];
-        
-        if (tableAccount.autoUploadBackground)
-            [self checkIfLocationIsEnabled];
-        
-    } else {
-        
-        [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
-                        
-        [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
-        
-        [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
-    }
-}
-
-#pragma --------------------------------------------------------------------------------------------
-#pragma mark === Camera Upload & Full ===
-#pragma --------------------------------------------------------------------------------------------
-
-- (void)setupAutoUpload
-{
-    if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
-        
-        self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
-        
-        [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
-        
-        [self uploadNewAssets];
-        
-    } else {
-        
-        [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
-                
-        [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
-        
-        [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
-        
-        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
-                                                        message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
-                                                       delegate:nil
-                                              cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
-                                              otherButtonTitles:nil];
-        [alert show];
-    }
-}
-
-- (void)setupAutoUploadFull
-{
-    if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
-        
-        self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
-        
-        [PHPhotoLibrary.sharedPhotoLibrary registerChangeObserver:self];
-        
-        [self uploadFullAssets];
-        
-    } else {
-        
-        [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
-        
-        [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
-        
-        [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
-        
-        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
-                                                        message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
-                                                       delegate:nil
-                                              cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
-                                              otherButtonTitles:nil];
-        [alert show];
-    }
-}
-
-#pragma --------------------------------------------------------------------------------------------
-#pragma mark === Location ===
-#pragma --------------------------------------------------------------------------------------------
-
-- (BOOL)checkIfLocationIsEnabled
-{
-    [CCManageLocation sharedInstance].delegate = self;
-    
-    if ([CLLocationManager locationServicesEnabled]) {
-        
-        NSLog(@"[LOG] checkIfLocationIsEnabled : authorizationStatus: %d", [CLLocationManager authorizationStatus]);
-        
-        if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways) {
-            
-            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ) {
-                
-                NSLog(@"[LOG] checkIfLocationIsEnabled : Location services not determined");
-                [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
-                
-            } else {
-                
-                if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
-                    
-                    [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
-                    
-                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
-                                                                    message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
-                                                                   delegate:nil
-                                                          cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
-                                                          otherButtonTitles:nil];
-                    [alert show];
-                    
-                } else {
-                    
-                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
-                                                                    message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
-                                                                   delegate:nil
-                                                          cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
-                                                          otherButtonTitles:nil];
-                    [alert show];
-                }
-            }
-            
-        } else {
-            
-            if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
-                
-                [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:YES];
-                [[CCManageLocation sharedInstance] startSignificantChangeUpdates];
-                
-            } else {
-                
-                [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
-                [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
-                
-                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
-                                                                 message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
-                                                                delegate:nil
-                                                       cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
-                                                       otherButtonTitles:nil];
-                [alert show];
-            }
-        }
-        
-    } else {
-        
-        [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
-        [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
-        
-        if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
-            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
-                                                            message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
-                                                           delegate:nil
-                                                  cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
-                                                  otherButtonTitles:nil];
-            [alert show];
-            
-        } else {
-            
-            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
-                                                            message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
-                                                           delegate:nil
-                                                  cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
-                                                  otherButtonTitles:nil];
-            [alert show];
-        }
-    }
-    
-    tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
-    return tableAccount.autoUploadBackground;
-}
-
-
-- (void)statusAuthorizationLocationChanged
-{
-    if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
-        
-        if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
-            
-            ALAssetsLibrary *assetLibrary = [CCUtility defaultAssetsLibrary];
-            
-            [assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
-                                        usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
-                                            
-                                        } failureBlock:^(NSError *error) {
-                                            
-                                        }];
-        }
-        
-        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
-            
-            if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
-                
-                if ([CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
-                    
-                    [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
-                    [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
-                }
-                
-            } else {
-                
-                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil)
-                                                                 message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil)
-                                                                delegate:nil
-                                                       cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
-                                                       otherButtonTitles:nil];
-                [alert show];
-            }
-            
-        } else if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined){
-            
-            tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
-            
-            if (tableAccount.autoUploadBackground) {
-                
-                [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
-                [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
-                
-                if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
-                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_location_not_enabled_", nil)
-                                                                    message:NSLocalizedString(@"_location_not_enabled_msg_", nil)
-                                                                   delegate:nil
-                                                          cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
-                                                          otherButtonTitles:nil];
-                    [alert show];
-                    
-                } else {
-                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_access_photo_location_not_enabled_", nil)
-                                                                    message:NSLocalizedString(@"_access_photo_location_not_enabled_msg_", nil)
-                                                                   delegate:nil
-                                                          cancelButtonTitle:NSLocalizedString(@"_ok_", nil)
-                                                          otherButtonTitles:nil];
-                    [alert show];
-                }
-            }
-        }
-        
-        if (![CCManageLocation sharedInstance].firstChangeAuthorizationDone) {
-            
-            [CCManageLocation sharedInstance].firstChangeAuthorizationDone = YES;
-        }
-    }
-}
-
-- (void)changedLocation
-{
-    // Only in background
-    tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
-    
-    if (tableAccount.autoUpload && tableAccount.autoUploadBackground && [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
-    
-        
-        if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized) {
-            
-            //check location
-            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
-                
-                NSLog(@"[LOG] Changed Location call uploadNewAssets");
-
-                [self uploadNewAssets];
-            }
-            
-        } else {
-            
-            [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUpload" state:NO];
-            [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadBackground" state:NO];
-            
-            [[CCManageLocation sharedInstance] stopSignificantChangeUpdates];
-            [PHPhotoLibrary.sharedPhotoLibrary unregisterChangeObserver:self];
-        }
-    }
-}
-
-#pragma --------------------------------------------------------------------------------------------
-#pragma mark ===== Upload Assets : NEW & FULL ====
-#pragma --------------------------------------------------------------------------------------------
-
-- (void)uploadNewAssets
-{
-    [self uploadAssetsNewAndFull:NO];
-}
-
-- (void)uploadFullAssets
-{
-    [self uploadAssetsNewAndFull:YES];
-}
-
-- (void)uploadAssetsNewAndFull:(BOOL)assetsFull
-{
-    CCManageAsset *manageAsset = [[CCManageAsset alloc] init];
-    NSMutableArray *newItemsToUpload;
-    tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
-    
-    // Check Asset : NEW or FULL
-    if (assetsFull) {
-        
-        newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:[NSDate distantPast] dateVideo:[NSDate distantPast]];
-        
-    } else {
-        
-        NSDate *databaseDatePhoto = tableAccount.autoUploadDatePhoto;
-        NSDate *databaseDateVideo = tableAccount.autoUploadDateVideo;
-        
-        newItemsToUpload = [manageAsset getCameraRollNewItemsWithDatePhoto:databaseDatePhoto dateVideo:databaseDateVideo];
-    }
-    
-    // News Assets ? if no verify if blocked Table Auto Upload -> Autostart
-    if ([newItemsToUpload count] == 0)
-        return;
-    
-    // Disable idle timer
-    [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
-    
-    if (assetsFull) {
-        
-        if (!_hud)
-            _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
-        
-        [_hud visibleHudTitle:NSLocalizedString(@"_create_full_upload_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
-    }
-
-    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
-        
-        if (assetsFull)
-            [self performSelectorOnMainThread:@selector(uploadFullAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
-        else
-            [self performSelectorOnMainThread:@selector(uploadNewAssetsToNetwork:) withObject:newItemsToUpload waitUntilDone:NO];
-    });
-}
-
-- (void)uploadNewAssetsToNetwork:(NSMutableArray *)newItemsToUpload
-{
-    [self uploadAssetsToNetwork:newItemsToUpload assetsFull:NO];
-}
-
-- (void)uploadFullAssetsToNetwork:(NSMutableArray *)newItemsToUpload
-{
-    [self uploadAssetsToNetwork:newItemsToUpload assetsFull:YES];
-}
-
-- (void)uploadAssetsToNetwork:(NSMutableArray *)newItemsToUpload assetsFull:(BOOL)assetsFull
-{
-    NSMutableArray *newItemsPHAssetToUpload = [[NSMutableArray alloc] init];
-    tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
-    
-    NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
-    BOOL useSubFolder = tableAccount.autoUploadCreateSubfolder;
-    
-    // Conversion from ALAsset -to-> PHAsset
-    for (ALAsset *asset in newItemsToUpload) {
-        
-        NSURL *url = [asset valueForProperty:@"ALAssetPropertyAssetURL"];
-        PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
-        PHAsset *asset = [fetchResult firstObject];
-        [newItemsPHAssetToUpload addObject:asset];
-        NSLog(@"Convert url %@", url);
-    }
-    
-    // Create the folder for Photos & if request the subfolders
-    if(![app createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:newItemsPHAssetToUpload selector:selectorUploadAutoUploadAll]) {
-            
-        // end loading
-        [_hud hideHud];
-        
-        // Enable idle timer
-        [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
-        
-        return;
-    }
-    
-    for (PHAsset *asset in newItemsPHAssetToUpload) {
-        
-        NSString *serverUrl;
-        NSDate *assetDate = asset.creationDate;
-        PHAssetMediaType assetMediaType = asset.mediaType;
-        NSString *session;
-        NSString *fileName = [CCUtility createFileNameFromAsset:asset key:nil];
-        
-        // Select type of session
-        
-        if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto == NO) session = k_upload_session;
-        if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo == NO) session = k_upload_session;
-        if (assetMediaType == PHAssetMediaTypeImage && tableAccount.autoUploadWWAnPhoto) session = k_upload_session_wwan;
-        if (assetMediaType == PHAssetMediaTypeVideo && tableAccount.autoUploadWWAnVideo) session = k_upload_session_wwan;
-        
-        NSDateFormatter *formatter = [NSDateFormatter new];
-        
-        [formatter setDateFormat:@"yyyy"];
-        NSString *yearString = [formatter stringFromDate:assetDate];
-        
-        [formatter setDateFormat:@"MM"];
-        NSString *monthString = [formatter stringFromDate:assetDate];
-
-        if (useSubFolder)
-            serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
-        else
-            serverUrl = autoUploadPath;
-        
-        CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
-            
-        metadataNet.action = actionUploadAsset;
-        metadataNet.assetLocalIdentifier = asset.localIdentifier;
-        if (assetsFull) {
-            metadataNet.selector = selectorUploadAutoUploadAll;
-            metadataNet.selectorPost = selectorUploadRemovePhoto;
-            metadataNet.priority = NSOperationQueuePriorityLow;
-        } else {
-            metadataNet.selector = selectorUploadAutoUpload;
-            metadataNet.selectorPost = nil;
-            metadataNet.priority = NSOperationQueuePriorityNormal;
-        }
-        metadataNet.fileName = fileName;
-        metadataNet.serverUrl = serverUrl;
-        metadataNet.session = session;
-        metadataNet.taskStatus = k_taskStatusResume;
-        
-        if (assetsFull)
-            [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
-        else
-            [self writeAssetToSandbox:metadataNet];
-    }
-    
-    // end loading
-    [_hud hideHud];
-    
-    // Enable idle timer
-    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
-}
-
-- (void)writeAssetToSandbox:(CCMetadataNet *)metadataNet
-{
-    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
-    PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadataNet.assetLocalIdentifier] options:nil];
-    
-    PHAsset *asset = result[0];
-    PHAssetMediaType assetMediaType = asset.mediaType;
-    NSDate *assetDate = asset.creationDate;
-    __block NSError *error = nil;
-    
-    // VIDEO
-    if (assetMediaType == PHAssetMediaTypeVideo) {
-        
-        @autoreleasepool {
-            
-            PHVideoRequestOptions *options = [PHVideoRequestOptions new];
-            options.networkAccessAllowed = true;
-            
-            [[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
-                
-                if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]])
-                    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] error:nil];
-                
-                AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:playerItem.asset presetName:AVAssetExportPresetHighestQuality];
-                
-                if (exportSession) {
-                    
-                    exportSession.outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName]];
-                    exportSession.outputFileType = AVFileTypeQuickTimeMovie;
-                    
-                    [exportSession exportAsynchronouslyWithCompletionHandler:^{
-                        
-                        if (AVAssetExportSessionStatusCompleted == exportSession.status) {
-                            
-                            [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
-                            
-                        } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
-                                                        
-                            [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
-                            
-                        } else {
-                            NSLog(@"Export Session Status: %ld", (long)exportSession.status);
-                        }
-                    }];
-                    
-                } else {
-                    
-                    [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description] type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:appDelegate.activeUrl];
-                }
-            }];
-        }
-    }
-    
-    // IMAGE
-    if (assetMediaType == PHAssetMediaTypeImage) {
-        
-        @autoreleasepool {
-            
-            PHImageRequestOptions *options = [PHImageRequestOptions new];
-            options.synchronous = NO;
-            
-            [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
-                
-                [imageData writeToFile:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadataNet.fileName] options:NSDataWritingAtomic error:&error];
-                
-                if (error) {
-                    
-                    NSString *note = [NSString stringWithFormat:@"%@ [%@]",NSLocalizedString(@"_read_file_error_", nil), error.description];
-
-                    [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:metadataNet.selector note:note type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
-                    
-                    [[NCManageDatabase sharedInstance] deleteAutoUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier];
-                    
-                } else {
-                    
-                    [self addDatabaseAutoUpload:metadataNet assetDate:assetDate assetMediaType:assetMediaType];
-                }
-            }];
-        }
-    }
-}
-
-- (void)addDatabaseAutoUpload:(CCMetadataNet *)metadataNet assetDate:(NSDate *)assetDate assetMediaType:(PHAssetMediaType)assetMediaType
-{    
-    if ([[NCManageDatabase sharedInstance] addAutoUploadWithMetadataNet:metadataNet]) {
-        
-        [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutoUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"Add Auto Upload, Asset Data: %@", [NSDateFormatter localizedStringFromDate:assetDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
-       
-    } else {
-        
-        [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionAutoUpload selector:metadataNet.selector note:[NSString stringWithFormat:@"Add Auto Upload [File already present in Table autoUpload], Asset Data: %@", [NSDateFormatter localizedStringFromDate:assetDate dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]] type:k_activityTypeInfo verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
-    }
-    
-    dispatch_async(dispatch_get_main_queue(), ^{
-        
-        // Update Camera Auto Upload data
-        if ([metadataNet.selector isEqualToString:selectorUploadAutoUpload])
-            [[NCManageDatabase sharedInstance] setAccountAutoUploadDateAssetType:assetMediaType assetDate:assetDate];
-        
-        // Update icon badge number
-        [app updateApplicationIconBadgeNumber];
-    });
-}
-
 @end

+ 6 - 6
iOSClient/Settings/CCManageAutoUpload.m

@@ -22,6 +22,7 @@
 //
 
 #import "CCManageAutoUpload.h"
+#import "NCAutoUpload.h"
 #import "AppDelegate.h"
 #import "NCBridgeSwift.h"
 
@@ -240,7 +241,7 @@
         }
         
         // Initialize Auto Upload
-        [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initStateAutoUpload" object:nil];
+        [[NCAutoUpload sharedInstance] initStateAutoUpload];
         
         [self reloadForm];
     }
@@ -250,10 +251,9 @@
         if ([[rowDescriptor.value valueData] boolValue] == YES) {
             
             BOOL isLocationIsEnabled = NO;
-                
-            if (app.activePhotos)
-                [app.activePhotos checkIfLocationIsEnabled];
-                
+            
+            [[NCAutoUpload sharedInstance] checkIfLocationIsEnabled];
+                            
             if(isLocationIsEnabled == YES) {
                     
                 UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_autoupload_background_title_", nil) message:NSLocalizedString(@"_autoupload_background_msg_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
@@ -277,7 +277,7 @@
         
         if ([[rowDescriptor.value valueData] boolValue] == YES) {
             
-            [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setupAutoUploadFull" object:nil];
+            [[NCAutoUpload sharedInstance] setupAutoUploadFull];
             [[NCManageDatabase sharedInstance] setAccountAutoUploadFiled:@"autoUploadFull" state:YES];
             
         } else {

+ 3 - 1
iOSClient/Synchronize/CCSynchronize.h

@@ -26,6 +26,8 @@
 #import "CCHud.h"
 #import "CCCellMain.h"
 
+@class tableMetadata;
+
 @interface CCSynchronize : NSObject
 
 @property (nonatomic, strong) CCHud *hud;
@@ -35,7 +37,7 @@
 @property (nonatomic, strong) NSMutableOrderedSet *foldersInSynchronized;
 
 - (void)readFolderServerUrl:(NSString *)serverUrl selector:(NSString *)selector;
-- (void)readFile:(id)metadata withDownload:(BOOL)withDownload;
+- (void)readFile:(tableMetadata *)metadata withDownload:(BOOL)withDownload;
 
 - (void)verifyChangeMedatas:(NSArray *)allRecordMetadatas serverUrl:(NSString *)serverUrl account:(NSString *)account withDownload:(BOOL)withDownload;