Advertisement
Guest User

Untitled

a guest
Nov 15th, 2018
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 69.88 KB | None | 0 0
  1. //
  2. // AppDelegate.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23.  
  24. #import "AppDelegate.h"
  25.  
  26. #import "iRate.h"
  27. #import "AFURLSessionManager.h"
  28. #import "CCNetworking.h"
  29. #import "CCGraphics.h"
  30. #import "CCPhotos.h"
  31. #import "CCSynchronize.h"
  32. #import "CCMain.h"
  33. #import "CCDetail.h"
  34. #import <Fabric/Fabric.h>
  35. #import <Crashlytics/Crashlytics.h>
  36. #import "JDStatusBarNotification.h"
  37. #import "NCBridgeSwift.h"
  38. #import "NCAutoUpload.h"
  39.  
  40. /* Remove comment for activate Firebase and push notification */
  41. //#import "Firebase.h"
  42. //@interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
  43.  
  44. @interface AppDelegate () <UNUserNotificationCenterDelegate>
  45. {
  46.  
  47. }
  48. @end
  49.  
  50. @implementation AppDelegate
  51.  
  52. + (void)initialize
  53. {
  54. [iRate sharedInstance].daysUntilPrompt = 5;
  55. [iRate sharedInstance].usesUntilPrompt = 5;
  56. [iRate sharedInstance].promptForNewVersionIfUserRated = true;
  57.  
  58. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  59.  
  60. //enable preview mode
  61. //[iRate sharedInstance].previewMode = YES;
  62. }
  63.  
  64. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  65. {
  66. // Brand
  67. if ([NCBrandOptions sharedInstance].use_firebase) {
  68.  
  69. /* Remove comment for activate Firebase and push notification */
  70.  
  71. /*
  72. //In order for this to work, proper GoogleService-Info.plist must be included
  73. @try {
  74. [FIRApp configure];
  75. } @catch (NSException *exception) {
  76. NSLog(@"[LOG] Something went wrong while configuring Firebase");
  77. }
  78.  
  79. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
  80.  
  81. UIUserNotificationType allNotificationTypes =(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
  82. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
  83.  
  84. [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  85.  
  86. } else {
  87.  
  88. // iOS 10 or later
  89. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  90. // For iOS 10 display notification (sent via APNS)
  91. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  92. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  93. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  94. }];
  95.  
  96. // For iOS 10 data message (sent via FCM)
  97. [FIRMessaging messaging].remoteMessageDelegate = self;
  98. #endif
  99. }
  100. */
  101. }
  102.  
  103. NSString *dir;
  104. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:[NCBrandOptions sharedInstance].capabilitiesGroups];
  105.  
  106. NSLog(@"[LOG] Start program group -----------------");
  107. NSLog(@"%@", dirGroup);
  108. NSLog(@"[LOG] Start program application -----------");
  109. NSLog(@"%@", [[CCUtility getDirectoryDocuments] stringByDeletingLastPathComponent]);
  110. NSLog(@"[LOG] -------------------------------------");
  111.  
  112. // create Directory Documents
  113. dir = [CCUtility getDirectoryDocuments];
  114. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  115. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  116.  
  117. // create Directory audio => Library, Application Support, audio
  118. dir = [CCUtility getDirectoryAudio];
  119. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  120. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  121.  
  122. // create Directory database Nextcloud
  123. dir = [[dirGroup URLByAppendingPathComponent:appDatabaseNextcloud] path];
  124. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  125. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  126.  
  127. NSError *error = nil;
  128. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:dir error:&error];
  129.  
  130. // Verify upgrade
  131. if ([self upgrade]) {
  132.  
  133. // Set account, if no exists clear all
  134. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  135.  
  136. if (account == nil) {
  137.  
  138. // remove all the keys Chain
  139. [CCUtility deleteAllChainStore];
  140.  
  141. // remove all the App group key
  142. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  143.  
  144. } else {
  145.  
  146. [self settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  147. }
  148. }
  149.  
  150. #ifdef DEBUG
  151. NSLog(@"[LOG] Copy DB on Documents directory");
  152. NSString *atPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [[dirGroup URLByAppendingPathComponent:appDatabaseNextcloud] path]];
  153. NSString *toPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [CCUtility getDirectoryDocuments]];
  154. [[NSFileManager defaultManager] removeItemAtPath:toPathDB error:nil];
  155. [[NSFileManager defaultManager] copyItemAtPath:atPathDB toPath:toPathDB error:nil];
  156. #endif
  157.  
  158. // Operation Queue OC Networking
  159. _netQueue = [[NSOperationQueue alloc] init];
  160. _netQueue.name = k_queue;
  161. _netQueue.maxConcurrentOperationCount = k_maxConcurrentOperation;
  162.  
  163. // Add notification change session
  164. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionChanged:) name:k_networkingSessionNotification object:nil];
  165.  
  166. // Initialization Share
  167. self.sharesID = [NSMutableDictionary new];
  168. self.sharesLink = [NSMutableDictionary new];
  169. self.sharesUserAndGroup = [NSMutableDictionary new];
  170.  
  171. // Initialization Notification
  172. self.listOfNotifications = [NSMutableArray new];
  173.  
  174. // Background Fetch
  175. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  176.  
  177. // Initialization List
  178. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  179. self.listChangeTask = [[NSMutableDictionary alloc] init];
  180. self.listMainVC = [[NSMutableDictionary alloc] init];
  181.  
  182. // setting Reachable in back
  183. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  184.  
  185. self.reachability = [Reachability reachabilityForInternetConnection];
  186.  
  187. self.lastReachability = [self.reachability isReachable];
  188. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  189. [self.reachability startNotifier];
  190. });
  191.  
  192. //AV Session
  193. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  194. //[[AVAudioSession sharedInstance] setActive:YES error:nil];
  195. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  196.  
  197. // How to hide UINavigationBar 1px bottom line < iOS 11
  198. [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
  199. [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
  200.  
  201. // passcode
  202. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  203.  
  204. dispatch_async(dispatch_get_main_queue(), ^{
  205. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  206. });
  207.  
  208. // Quick Actions
  209. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  210.  
  211. [self configDynamicShortcutItems];
  212.  
  213. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  214.  
  215. if (shortcutItem)
  216. [self handleShortCutItem:shortcutItem];
  217. }
  218.  
  219. // Verify Lock
  220. [self verifyLockOnLoadAutoUpload];
  221.  
  222. // Start Timer
  223. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(processAutoDownloadUpload) userInfo:nil repeats:YES];
  224. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  225.  
  226. // Registration Push Notification
  227. UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert;
  228. UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  229. [application registerUserNotificationSettings:notificationSettings];
  230.  
  231. // Fabric
  232. [Fabric with:@[[Crashlytics class]]];
  233. [self logUser];
  234.  
  235. return YES;
  236. }
  237.  
  238. //
  239. // L' applicazione si dimetterà dallo stato di attivo
  240. //
  241. - (void)applicationWillResignActive:(UIApplication *)application
  242. {
  243. [_activeMain closeAllMenu];
  244.  
  245. [self updateApplicationIconBadgeNumber];
  246. }
  247.  
  248. //
  249. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  250. //
  251. - (void)applicationWillEnterForeground:(UIApplication *)application
  252. {
  253. // Test Maintenance
  254. if (self.activeAccount.length == 0 || self.maintenanceMode)
  255. return;
  256.  
  257. NSLog(@"[LOG] Request Service Server Nextcloud");
  258. [[NCService sharedInstance] startRequestServicesServer];
  259.  
  260. NSLog(@"[LOG] Initialize Auto upload");
  261. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  262. }
  263.  
  264. //
  265. // L' applicazione entrerà in primo piano (attivo sempre)
  266. //
  267. - (void)applicationDidBecomeActive:(UIApplication *)application
  268. {
  269. // Test Maintenance
  270. if (self.activeAccount.length == 0 || self.maintenanceMode)
  271. return;
  272.  
  273. // verify Upload
  274. [self verifyUploadInErrorOrWait];
  275.  
  276. // middelware ping
  277. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  278. NSLog(@"[LOG] Middleware Ping");
  279. [[NCService sharedInstance] middlewarePing];
  280. }
  281. }
  282.  
  283. //
  284. // L' applicazione è entrata nello sfondo
  285. //
  286. - (void)applicationDidEnterBackground:(UIApplication *)application
  287. {
  288. NSLog(@"[LOG] Enter in Background");
  289.  
  290. [[CCQuickActions quickActionsManager] closeAll];
  291.  
  292. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  293.  
  294. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  295.  
  296. __block UIBackgroundTaskIdentifier background_task;
  297.  
  298. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  299.  
  300. //Clean up code. Tell the system that we are done.
  301. [application endBackgroundTask: background_task];
  302. background_task = UIBackgroundTaskInvalid;
  303. }];
  304. }
  305. }
  306.  
  307. //
  308. // L'applicazione terminerà
  309. //
  310. - (void)applicationWillTerminate:(UIApplication *)application
  311. {
  312. NSLog(@"[LOG] bye bye, Nextcloud !");
  313. }
  314.  
  315. #pragma --------------------------------------------------------------------------------------------
  316. #pragma mark ===== Login =====
  317. #pragma --------------------------------------------------------------------------------------------
  318.  
  319. - (void)openLoginView:(id)delegate loginType:(enumLoginType)loginType
  320. {
  321. BOOL loginWeb = NO;
  322.  
  323. @synchronized (self) {
  324.  
  325. // only for personalized LoginWeb [customer]
  326. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  327.  
  328. if (_activeLoginWeb == nil) {
  329.  
  330. _activeLoginWeb = [CCLoginWeb new];
  331. _activeLoginWeb.delegate = delegate;
  332. _activeLoginWeb.loginType = loginType;
  333. _activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  334.  
  335. dispatch_async(dispatch_get_main_queue(), ^ {
  336. [_activeLoginWeb presentModalWithDefaultTheme:delegate];
  337. });
  338. }
  339. return;
  340. }
  341.  
  342. // ------------------- Nextcloud -------------------------
  343. //
  344.  
  345. // Login flow : LoginWeb
  346. if (loginType == loginModifyPasswordUser) {
  347. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  348. if (account.loginFlow)
  349. loginWeb = YES;
  350. }
  351.  
  352. if (loginWeb) {
  353.  
  354. if (_activeLoginWeb == nil) {
  355.  
  356. _activeLoginWeb = [CCLoginWeb new];
  357. _activeLoginWeb.delegate = delegate;
  358. _activeLoginWeb.loginType = loginType;
  359. _activeLoginWeb.urlBase = self.activeUrl;
  360.  
  361. dispatch_async(dispatch_get_main_queue(), ^ {
  362. [_activeLoginWeb presentModalWithDefaultTheme:delegate];
  363. });
  364. }
  365.  
  366. } else {
  367.  
  368. if (_activeLogin == nil) {
  369.  
  370. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  371. _activeLogin.delegate = delegate;
  372. _activeLogin.loginType = loginType;
  373.  
  374. dispatch_async(dispatch_get_main_queue(), ^ {
  375. [delegate presentViewController:_activeLogin animated:YES completion:nil];
  376. });
  377. }
  378. }
  379.  
  380. }
  381. }
  382.  
  383. #pragma --------------------------------------------------------------------------------------------
  384. #pragma mark ===== Setting Active Account for all APP =====
  385. #pragma --------------------------------------------------------------------------------------------
  386.  
  387. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activeUserID:(NSString *)activeUserID activePassword:(NSString *)activePassword
  388. {
  389. self.activeAccount = activeAccount;
  390. self.activeUrl = activeUrl;
  391. self.activeUser = activeUser;
  392. self.activeUserID = activeUserID;
  393. self.activePassword = activePassword;
  394.  
  395. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  396.  
  397. // Setting Account to CCNetworking
  398. [[CCNetworking sharedNetworking] settingAccount];
  399. }
  400.  
  401. #pragma --------------------------------------------------------------------------------------------
  402. #pragma mark ===== Push Notification =====
  403. #pragma --------------------------------------------------------------------------------------------
  404.  
  405. - (void)subscribingNextcloudServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  406. {
  407. NSLog(@"[LOG] Error Subscribing Nextcloud Server %@", message);
  408. }
  409.  
  410. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
  411. {
  412. [application registerForRemoteNotifications];
  413. }
  414.  
  415. /* Remove comment for activate Firebase and push notification */
  416.  
  417. /*
  418. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  419. {
  420. // test
  421. if (self.activeAccount.length == 0)
  422. return;
  423.  
  424. // FIREBASE registered token
  425.  
  426. [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
  427. NSString *pushToken = [[FIRInstanceID instanceID] token];
  428. // NSString *pushToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
  429.  
  430. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:pushToken];
  431. NSDictionary *devicePushKey = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DevicePushKey-Info" ofType:@"plist"]];
  432.  
  433. #ifdef DEBUG
  434. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyDevelopment"];
  435. #else
  436. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyProduction"];
  437. #endif
  438.  
  439. if ([devicePublicKey length] > 0 && [pushTokenHash length] > 0) {
  440.  
  441. NSLog(@"[LOG] Firebase InstanceID push token: %@", pushToken);
  442.  
  443. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  444.  
  445. NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:pushToken, @"pushToken", pushTokenHash, @"pushTokenHash", devicePublicKey, @"devicePublicKey", nil];
  446.  
  447. metadataNet.action = actionSubscribingNextcloudServer;
  448. metadataNet.options = options;
  449. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  450. }
  451. }
  452. */
  453.  
  454. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  455. {
  456. NSLog(@"[LOG] Error register remote notification %@", error);
  457. }
  458.  
  459. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  460.  
  461. UIApplicationState state = [application applicationState];
  462.  
  463. if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
  464.  
  465. NSLog(@"[LOG] Receive Notification on Inactive or Background state");
  466.  
  467. } else {
  468.  
  469. NSLog(@"[LOG] Receive Notification on Active state");
  470. }
  471.  
  472. // If you are receiving a notification message while your app is in the background,
  473. // this callback will not be fired till the user taps on the notification launching the application.
  474. // TODO: Handle data of notification
  475.  
  476. // Print message ID.
  477. //if (userInfo[kGCMMessageIDKey]) {
  478. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  479. //}
  480.  
  481. // Print full message.
  482. NSLog(@"[LOG] %@", userInfo);
  483.  
  484. }
  485.  
  486. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  487. {
  488. UIApplicationState state = [application applicationState];
  489.  
  490. // Print message ID.
  491. //if (userInfo[kGCMMessageIDKey]) {
  492. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  493. //}
  494.  
  495. // Print full message.
  496. NSLog(@"[LOG] %@", userInfo);
  497.  
  498.  
  499. if (state == UIApplicationStateBackground || (state == UIApplicationStateInactive)) {
  500.  
  501. } else if (state == UIApplicationStateInactive) {
  502.  
  503. // user tapped notification
  504. completionHandler(UIBackgroundFetchResultNewData);
  505.  
  506. } else {
  507.  
  508. // app is active
  509. completionHandler(UIBackgroundFetchResultNoData);
  510. }
  511. }
  512.  
  513. /* Remove comment for activate Firebase and push notification */
  514.  
  515. #pragma FIREBASE
  516. /*
  517. - (void)tokenRefreshNotification:(NSNotification *)notification {
  518.  
  519. // Note that this callback will be fired everytime a new token is generated, including the first
  520. // time. So if you need to retrieve the token as soon as it is available this is where that
  521. // should be done.
  522.  
  523. NSString *refreshedToken = [[FIRInstanceID instanceID] token];
  524. NSLog(@"[LOG] InstanceID token: %@", refreshedToken);
  525.  
  526. // Connect to FCM since connection may have failed when attempted before having a token.
  527. [self connectToFcm];
  528.  
  529. // TODO: If necessary send token to application server.
  530. }
  531.  
  532. - (void)connectToFcm {
  533.  
  534. // Won't connect since there is no token
  535. if (![[FIRInstanceID instanceID] token]) {
  536. return;
  537. }
  538.  
  539. // Disconnect previous FCM connection if it exists.
  540. [[FIRMessaging messaging] disconnect];
  541.  
  542. [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
  543. if (error != nil) {
  544. NSLog(@"[LOG] Unable to connect to FCM. %@", error);
  545. } else {
  546. NSLog(@"[LOG] Connected to FCM.");
  547. }
  548. }];
  549. }
  550.  
  551. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  552. // Receive data message on iOS 10 devices while app is in the foreground.
  553. - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  554. // Print full message
  555. NSLog(@"[LOG] %@", remoteMessage.appData);
  556. }
  557. #endif
  558. */
  559.  
  560. #pragma --------------------------------------------------------------------------------------------
  561. #pragma mark ===== Quick Actions - ShotcutItem =====
  562. #pragma --------------------------------------------------------------------------------------------
  563.  
  564. - (void)configDynamicShortcutItems
  565. {
  566. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  567.  
  568. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionPhotos"];
  569. UIApplicationShortcutIcon *shortcutUploadIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionUpload"];
  570.  
  571. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  572. UIApplicationShortcutItem *shortcutUpload = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.upload", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadIcon userInfo:nil];
  573.  
  574. // add the array to our app
  575. if (shortcutUpload && shortcutPhotos)
  576. [UIApplication sharedApplication].shortcutItems = @[shortcutUpload, shortcutPhotos];
  577. }
  578.  
  579. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  580. {
  581. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  582.  
  583. completionHandler(handledShortCutItem);
  584. }
  585.  
  586. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  587. {
  588. BOOL handled = NO;
  589.  
  590. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  591.  
  592. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  593. NSString *shortcutUpload = [NSString stringWithFormat:@"%@.upload", bundleId];
  594. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  595.  
  596. if ([shortcutItem.type isEqualToString:shortcutUpload] && self.activeAccount) {
  597.  
  598. dispatch_async(dispatch_get_main_queue(), ^{
  599.  
  600. if (_activeMain) {
  601.  
  602. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  603.  
  604. if (splitViewController.isCollapsed) {
  605.  
  606. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  607. for (UINavigationController *nvc in tbc.viewControllers) {
  608.  
  609. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  610. [nvc popToRootViewControllerAnimated:NO];
  611. }
  612.  
  613. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  614.  
  615. } else {
  616.  
  617. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  618. [nvcDetail popToRootViewControllerAnimated:NO];
  619.  
  620. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  621. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  622. }
  623.  
  624. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  625.  
  626. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  627. [[CCQuickActions quickActionsManager] startQuickActionsViewController:_activeMain];
  628. });
  629. }
  630. });
  631.  
  632. handled = YES;
  633. }
  634.  
  635. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  636.  
  637. dispatch_async(dispatch_get_main_queue(), ^{
  638.  
  639. if (_activeMain) {
  640.  
  641. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  642.  
  643. if (splitViewController.isCollapsed) {
  644.  
  645. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  646. for (UINavigationController *nvc in tbc.viewControllers) {
  647.  
  648. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  649. [nvc popToRootViewControllerAnimated:NO];
  650. }
  651.  
  652. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  653.  
  654. } else {
  655.  
  656. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  657. [nvcDetail popToRootViewControllerAnimated:NO];
  658.  
  659. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  660. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  661. }
  662.  
  663. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  664.  
  665. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  666. [[CCQuickActions quickActionsManager] startQuickActionsViewController:_activeMain];
  667. });
  668. }
  669. });
  670.  
  671. handled = YES;
  672. }
  673.  
  674. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  675.  
  676. dispatch_async(dispatch_get_main_queue(), ^{
  677.  
  678. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  679.  
  680. if (splitViewController.isCollapsed) {
  681.  
  682. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  683. for (UINavigationController *nvc in tbc.viewControllers) {
  684.  
  685. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  686. [nvc popToRootViewControllerAnimated:NO];
  687. }
  688.  
  689. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  690.  
  691. } else {
  692.  
  693. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  694. [nvcDetail popToRootViewControllerAnimated:NO];
  695.  
  696. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  697. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  698. }
  699. });
  700.  
  701. handled = YES;
  702. }
  703.  
  704. return handled;
  705. }
  706.  
  707. #pragma --------------------------------------------------------------------------------------------
  708. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  709. #pragma --------------------------------------------------------------------------------------------
  710.  
  711. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  712. {
  713. static NSInteger errorCodePrev = 0;
  714.  
  715. dispatch_async(dispatch_get_main_queue(), ^{
  716.  
  717. if (visible) {
  718.  
  719. switch (errorcode) {
  720.  
  721. // JDStatusBarNotification
  722. case kCFURLErrorNotConnectedToInternet :
  723.  
  724. if (errorCodePrev != errorcode)
  725. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  726.  
  727. errorCodePrev = errorcode;
  728. break;
  729.  
  730. // TWMessageBarManager
  731. default:
  732.  
  733. if (description.length > 0) {
  734.  
  735. [TWMessageBarManager sharedInstance].styleSheet = self;
  736. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  737. }
  738. break;
  739. }
  740.  
  741. } else {
  742.  
  743. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  744. }
  745. });
  746. }
  747.  
  748. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  749. {
  750. UIColor *backgroundColor = nil;
  751. switch (type)
  752. {
  753. case TWMessageBarMessageTypeError:
  754. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  755. break;
  756. case TWMessageBarMessageTypeSuccess:
  757. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  758. break;
  759. case TWMessageBarMessageTypeInfo:
  760. backgroundColor = [NCBrandColor sharedInstance].brand;
  761. break;
  762. default:
  763. break;
  764. }
  765. return backgroundColor;
  766. }
  767.  
  768. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  769. {
  770. UIColor *strokeColor = nil;
  771. switch (type)
  772. {
  773. case TWMessageBarMessageTypeError:
  774. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  775. break;
  776. case TWMessageBarMessageTypeSuccess:
  777. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  778. break;
  779. case TWMessageBarMessageTypeInfo:
  780. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  781. break;
  782. default:
  783. break;
  784. }
  785. return strokeColor;
  786. }
  787.  
  788. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  789. {
  790. UIImage *iconImage = nil;
  791. switch (type)
  792. {
  793. case TWMessageBarMessageTypeError:
  794. iconImage = [UIImage imageNamed:@"icon-error.png"];
  795. break;
  796. case TWMessageBarMessageTypeSuccess:
  797. iconImage = [UIImage imageNamed:@"icon-success.png"];
  798. break;
  799. case TWMessageBarMessageTypeInfo:
  800. iconImage = [UIImage imageNamed:@"icon-info.png"];
  801. break;
  802. default:
  803. break;
  804. }
  805. return iconImage;
  806. }
  807.  
  808. - (void)updateApplicationIconBadgeNumber
  809. {
  810. // Test Maintenance
  811. if (self.maintenanceMode)
  812. return;
  813.  
  814. NSInteger total = 0;
  815.  
  816. // Total
  817. total = [[CCNetworking sharedNetworking] getNumDownloadInProgressWWan:NO] + [[CCNetworking sharedNetworking] getNumDownloadInProgressWWan:YES] + [[CCNetworking sharedNetworking] getNumUploadInProgressWWan:NO] + [[CCNetworking sharedNetworking] getNumUploadInProgressWWan:YES];
  818.  
  819. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  820.  
  821. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  822.  
  823. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  824.  
  825. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  826.  
  827. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  828.  
  829. if (total > 0) {
  830. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  831. } else {
  832. [tbItem setBadgeValue:nil];
  833.  
  834. NSDictionary* userInfo = @{@"fileID": @"", @"serverUrl": @"", @"progress": [NSNumber numberWithFloat:0]};
  835. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  836. }
  837. }
  838. }
  839.  
  840. #pragma --------------------------------------------------------------------------------------------
  841. #pragma mark ===== TabBarController =====
  842. #pragma --------------------------------------------------------------------------------------------
  843.  
  844. - (void)createTabBarController:(UITabBarController *)tabBarController
  845. {
  846. UITabBarItem *item;
  847. NSLayoutConstraint *constraint;
  848. CGFloat multiplier = 0;
  849. CGFloat safeAreaBottom = 0;
  850.  
  851. if (@available(iOS 11, *)) {
  852. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom/2;
  853. }
  854.  
  855. [self aspectTabBar:tabBarController.tabBar hidden:NO];
  856.  
  857. // File
  858. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  859. [item setTitle:NSLocalizedString(@"_home_", nil)];
  860. item.image = [UIImage imageNamed:@"tabBarFiles"];
  861. item.selectedImage = [UIImage imageNamed:@"tabBarFiles"];
  862.  
  863. // Favorites
  864. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  865. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  866. item.image = [UIImage imageNamed:@"tabBarFavorite"];
  867. item.selectedImage = [UIImage imageNamed:@"tabBarFavorite"];
  868.  
  869. // (PLUS)
  870. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  871. item.title = @"";
  872. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[UIColor clearColor]];
  873. item.enabled = false;
  874.  
  875. // Photos
  876. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPhotos];
  877. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  878. item.image = [UIImage imageNamed:@"tabBarPhotos"];
  879. item.selectedImage = [UIImage imageNamed:@"tabBarPhotos"];
  880.  
  881. // More
  882. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  883. [item setTitle:NSLocalizedString(@"_more_", nil)];
  884. item.image = [UIImage imageNamed:@"tabBarMore"];
  885. item.selectedImage = [UIImage imageNamed:@"tabBarMore"];
  886.  
  887. // Plus Button
  888. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brandElement];
  889. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  890. buttonPlus.tag = 99;
  891. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  892. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  893. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  894.  
  895. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  896. [tabBarController.tabBar addSubview:buttonPlus];
  897.  
  898. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  899. [tabBarController.view addConstraint:constraint];
  900.  
  901. multiplier = 1 * (tabBarController.tabBar.frame.size.height - safeAreaBottom) / tabBarController.tabBar.frame.size.height;
  902. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:multiplier constant:0];
  903. [tabBarController.view addConstraint:constraint];
  904.  
  905. multiplier = 0.8 * (tabBarController.tabBar.frame.size.height - safeAreaBottom) / tabBarController.tabBar.frame.size.height;
  906.  
  907. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  908. [tabBarController.view addConstraint:constraint];
  909.  
  910. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  911. [tabBarController.view addConstraint:constraint];
  912. }
  913.  
  914. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav online:(BOOL)online hidden:(BOOL)hidden
  915. {
  916. nav.translucent = NO;
  917. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  918. nav.tintColor = [NCBrandColor sharedInstance].brandText;
  919. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].brandText}];
  920. // Change bar bottom line shadow
  921. nav.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  922.  
  923. if (!online)
  924. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  925.  
  926. nav.hidden = hidden;
  927.  
  928. [nav setAlpha:1];
  929. }
  930.  
  931. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  932. {
  933. tab.translucent = NO;
  934. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  935. tab.tintColor = [NCBrandColor sharedInstance].brandElement;
  936.  
  937. tab.hidden = hidden;
  938.  
  939. [tab setAlpha:1];
  940. }
  941.  
  942. - (void)plusButtonVisibile:(BOOL)visible
  943. {
  944. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  945. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  946.  
  947. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  948.  
  949. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brandElement];
  950. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  951. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  952.  
  953. if (buttonPlus) {
  954.  
  955. if (visible) {
  956.  
  957. buttonPlus.hidden = false;
  958.  
  959. } else {
  960.  
  961. buttonPlus.hidden = true;
  962. }
  963. }
  964. }
  965.  
  966. - (void)handleTouchTabbarCenter:(id)sender
  967. {
  968. // Test Maintenance
  969. if (self.maintenanceMode)
  970. return;
  971.  
  972. UIView *view = [[(UIButton *)sender superview] superview];
  973.  
  974. CreateMenuAdd *menuAdd = [[CreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brandElement];
  975. [menuAdd createMenuWithView:view];
  976. }
  977.  
  978. - (void)selectedTabBarController:(NSInteger)index
  979. {
  980. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  981.  
  982. if (splitViewController.isCollapsed) {
  983.  
  984. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  985. for (UINavigationController *nvc in tbc.viewControllers) {
  986.  
  987. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  988. [nvc popToRootViewControllerAnimated:NO];
  989. }
  990.  
  991. [tbc setSelectedIndex: index];
  992.  
  993. } else {
  994.  
  995. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  996. [nvcDetail popToRootViewControllerAnimated:NO];
  997.  
  998. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  999. [tbc setSelectedIndex: index];
  1000. }
  1001. }
  1002.  
  1003. - (NSString *)getTabBarControllerActiveServerUrl
  1004. {
  1005. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1006. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  1007.  
  1008. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  1009. NSInteger index = tabBarController.selectedIndex;
  1010.  
  1011. // select active serverUrl
  1012. if (index == k_tabBarApplicationIndexFile) {
  1013. serverUrl = self.activeMain.serverUrl;
  1014. } else if (index == k_tabBarApplicationIndexFavorite) {
  1015. if (self.activeFavorites.serverUrl)
  1016. serverUrl = self.activeFavorites.serverUrl;
  1017. } else if (index == k_tabBarApplicationIndexPhotos) {
  1018. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  1019. }
  1020.  
  1021. return serverUrl;
  1022. }
  1023.  
  1024. #pragma --------------------------------------------------------------------------------------------
  1025. #pragma mark ===== Theming Color =====
  1026. #pragma --------------------------------------------------------------------------------------------
  1027.  
  1028. - (void)settingThemingColorBrand
  1029. {
  1030. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1031. return;
  1032.  
  1033. if ([NCBrandOptions sharedInstance].use_themingColor) {
  1034.  
  1035. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilites];
  1036.  
  1037. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  1038.  
  1039. } else {
  1040.  
  1041. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  1042. [NCBrandColor sharedInstance].brandElement = [NCBrandColor sharedInstance].customer;
  1043. [NCBrandColor sharedInstance].brandText = [NCBrandColor sharedInstance].customerText;
  1044. }
  1045.  
  1046. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  1047. }
  1048.  
  1049. - (void)changeTheming:(UIViewController *)vc
  1050. {
  1051. // Change Navigation & TabBar color
  1052. vc.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  1053. vc.tabBarController.tabBar.tintColor = [NCBrandColor sharedInstance].brandElement;
  1054. // Change bar bottom line shadow
  1055. vc.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  1056.  
  1057. // Change button Plus
  1058. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1059. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  1060.  
  1061. UIButton *button = [tabBarController.view viewWithTag:99];
  1062. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brandElement];
  1063.  
  1064. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  1065. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  1066.  
  1067. // Tint Color GLOBAL WINDOW
  1068. [self.window setTintColor:[NCBrandColor sharedInstance].textView];
  1069. }
  1070.  
  1071. #pragma --------------------------------------------------------------------------------------------
  1072. #pragma mark ===== Manager Passcode =====
  1073. #pragma --------------------------------------------------------------------------------------------
  1074.  
  1075. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  1076. {
  1077. // ServerUrl active
  1078. NSString *serverUrl = self.activeMain.serverUrl;
  1079. BOOL isBlockZone = false;
  1080.  
  1081. // fermiamo la data della sessione
  1082. self.sessionePasscodeLock = nil;
  1083.  
  1084. // se il block code è a zero esci con NON attivare la richiesta password
  1085. if ([[CCUtility getBlockCode] length] == 0) return NO;
  1086.  
  1087. // se non c'è attivo un account esci con NON attivare la richiesta password
  1088. if ([self.activeAccount length] == 0) return NO;
  1089.  
  1090. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  1091. if (serverUrl && _activeUrl) {
  1092.  
  1093. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  1094.  
  1095. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", self.activeAccount, serverUrl]];
  1096.  
  1097. if (directory.lock) {
  1098. isBlockZone = true;
  1099. break;
  1100. } else {
  1101. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  1102. if (serverUrl == self.activeUrl)
  1103. break;
  1104. }
  1105. }
  1106. }
  1107.  
  1108. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  1109.  
  1110. return YES;
  1111. }
  1112.  
  1113. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  1114. {
  1115. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  1116. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  1117. viewController.delegate = self;
  1118. viewController.title = [NCBrandOptions sharedInstance].brand;
  1119. viewController.fromType = CCBKPasscodeFromLockScreen;
  1120. viewController.inputViewTitlePassword = YES;
  1121.  
  1122. if ([CCUtility getSimplyBlockCode]) {
  1123.  
  1124. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  1125. viewController.passcodeInputView.maximumLength = 6;
  1126.  
  1127. } else {
  1128.  
  1129. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  1130. viewController.passcodeInputView.maximumLength = 64;
  1131. }
  1132.  
  1133. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  1134. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  1135.  
  1136. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  1137. return navigationController;
  1138. }
  1139.  
  1140. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  1141. {
  1142. [aViewController dismissViewControllerAnimated:YES completion:nil];
  1143.  
  1144. // is a lock screen
  1145. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  1146.  
  1147. [aViewController dismissViewControllerAnimated:YES completion:nil];
  1148.  
  1149. // start session Passcode Lock
  1150. BOOL isBlockZone = false;
  1151. NSString *serverUrl = self.activeMain.serverUrl;
  1152.  
  1153. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  1154.  
  1155. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", self.activeAccount, serverUrl]];
  1156.  
  1157. if (directory.lock) {
  1158. isBlockZone = true;
  1159. break;
  1160. } else {
  1161. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  1162. if (serverUrl == self.activeUrl)
  1163. break;
  1164. }
  1165. }
  1166. if (isBlockZone)
  1167. self.sessionePasscodeLock = [NSDate date];
  1168. }
  1169. }
  1170.  
  1171. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  1172. {
  1173. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  1174. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  1175. //self.lockUntilDate = nil;
  1176. //self.failedAttempts = 0;
  1177. aResultHandler(YES);
  1178. } else aResultHandler(NO);
  1179. } else aResultHandler(YES);
  1180. }
  1181.  
  1182. #pragma --------------------------------------------------------------------------------------------
  1183. #pragma mark ===== reachabilityChanged =====
  1184. #pragma --------------------------------------------------------------------------------------------
  1185.  
  1186. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  1187. {
  1188. if ([self.reachability isReachable]) {
  1189.  
  1190. if (self.lastReachability == NO) {
  1191.  
  1192. NSLog(@"[LOG] Request Service Server Nextcloud");
  1193. [[NCService sharedInstance] startRequestServicesServer];
  1194. }
  1195.  
  1196. NSLog(@"[LOG] Reachability Changed: Reachable");
  1197.  
  1198. self.lastReachability = YES;
  1199.  
  1200. } else {
  1201.  
  1202. if (self.lastReachability == YES) {
  1203. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  1204. }
  1205.  
  1206. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  1207.  
  1208. self.lastReachability = NO;
  1209. }
  1210.  
  1211. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  1212. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  1213.  
  1214. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  1215. }
  1216.  
  1217. #pragma --------------------------------------------------------------------------------------------
  1218. #pragma mark ===== Fetch =====
  1219. #pragma --------------------------------------------------------------------------------------------
  1220.  
  1221. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  1222. {
  1223. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  1224.  
  1225. // verify Upload
  1226. [self verifyUploadInErrorOrWait];
  1227.  
  1228. // Verify new photo
  1229. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  1230.  
  1231. // after 20 sec
  1232. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1233.  
  1234. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", self.activeAccount] sorted:nil ascending:NO];
  1235.  
  1236. if ([records count] > 0) {
  1237. completionHandler(UIBackgroundFetchResultNewData);
  1238. } else {
  1239. completionHandler(UIBackgroundFetchResultNoData);
  1240. }
  1241.  
  1242. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  1243. });
  1244. }
  1245.  
  1246. #pragma --------------------------------------------------------------------------------------------
  1247. #pragma mark ===== Operation Networking & Session =====
  1248. #pragma --------------------------------------------------------------------------------------------
  1249.  
  1250. //
  1251. // Method called by the system when all the background task has end
  1252. //
  1253. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  1254. {
  1255. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  1256.  
  1257. // after 20 sec
  1258. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1259.  
  1260. self.backgroundSessionCompletionHandler = completionHandler;
  1261. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  1262. self.backgroundSessionCompletionHandler = nil;
  1263. completionHandler();
  1264.  
  1265. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  1266. });
  1267. }
  1268.  
  1269. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  1270. {
  1271. id operation;
  1272.  
  1273. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withUserID:_activeUserID withPassword:_activePassword withUrl:_activeUrl];
  1274.  
  1275. [operation setQueuePriority:metadataNet.priority];
  1276.  
  1277. [netQueue addOperation:operation];
  1278. }
  1279.  
  1280. // Notification change session
  1281. - (void)sessionChanged:(NSNotification *)notification
  1282. {
  1283. NSURLSession *session;
  1284. NSString *fileID;
  1285. NSURLSessionTask *task;
  1286.  
  1287. for (id object in notification.object) {
  1288.  
  1289. if ([object isKindOfClass:[NSURLSession class]])
  1290. session = object;
  1291.  
  1292. if ([object isKindOfClass:[NSString class]])
  1293. fileID = object;
  1294.  
  1295. if ([object isKindOfClass:[NSURLSessionTask class]])
  1296. task = object;
  1297. }
  1298.  
  1299. /*
  1300. Task
  1301. */
  1302. if (fileID && [_listChangeTask objectForKey:fileID])
  1303. dispatch_async(dispatch_get_main_queue(), ^{
  1304. [self changeTask:fileID];
  1305. });
  1306.  
  1307. /*
  1308. Session
  1309. */
  1310. if (session) {
  1311.  
  1312. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1313.  
  1314. unsigned long numDownload = [downloadTasks count];
  1315. unsigned long numUpload = [uploadTasks count];
  1316.  
  1317. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  1318. }];
  1319. }
  1320. }
  1321.  
  1322. - (void)changeTask:(NSString *)fileID
  1323. {
  1324. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1325. if (!metadata) return;
  1326. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1327. if (!serverUrl) return;
  1328.  
  1329. if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"stopUpload"]) {
  1330.  
  1331. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierStop predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1332.  
  1333. }
  1334. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"reloadUpload"]) {
  1335.  
  1336. // V 1.8 if upload_session_wwan change in upload_session
  1337. if ([metadata.session isEqualToString:k_upload_session_wwan])
  1338. metadata.session = k_upload_session;
  1339.  
  1340. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1341. }
  1342. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"reloadDownload"]) {
  1343.  
  1344. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1345.  
  1346. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:k_download_session taskStatus:k_taskStatusResume delegate:self.activeMain];
  1347. }
  1348. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  1349.  
  1350. // remove the file
  1351.  
  1352. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, fileID] error:nil];
  1353. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", self.directoryUser, fileID] error:nil];
  1354.  
  1355. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  1356. }
  1357. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"cancelDownload"]) {
  1358.  
  1359. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1360. }
  1361.  
  1362. // remove ChangeTask (fileID) from the list
  1363. [_listChangeTask removeObjectForKey:fileID];
  1364.  
  1365. // delete progress
  1366. [_listProgressMetadata removeObjectForKey:fileID];
  1367.  
  1368. // Progress Task
  1369. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  1370.  
  1371. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  1372.  
  1373. // Refresh
  1374. if (_activeMain && [_listChangeTask count] == 0) {
  1375. [_activeMain reloadDatasource:serverUrl];
  1376. }
  1377. }
  1378.  
  1379. #pragma --------------------------------------------------------------------------------------------
  1380. #pragma mark ===== Process Auto Upload < k_timerProcess seconds > =====
  1381. #pragma --------------------------------------------------------------------------------------------
  1382.  
  1383. - (void)processAutoDownloadUpload
  1384. {
  1385. // Test Maintenance
  1386. if (self.maintenanceMode)
  1387. return;
  1388.  
  1389. // BACKGROND & FOREGROUND
  1390. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1391.  
  1392. // ONLY BACKGROUND
  1393. NSLog(@"[LOG] -PROCESS-AUTO-UPLOAD-");
  1394. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1395.  
  1396. } else {
  1397.  
  1398. // ONLY FOREFROUND
  1399. NSLog(@"[LOG] -PROCESS-AUTO-UPLOAD-");
  1400. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1401. }
  1402. }
  1403.  
  1404. - (void)loadAutoDownloadUpload:(NSNumber *)maxConcurrent
  1405. {
  1406. CCMetadataNet *metadataNet;
  1407.  
  1408. // E2EE : not in background
  1409. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1410. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadLock];
  1411. if (metadataNet) {
  1412. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@ AND e2eEncrypted = 1", self.activeAccount, metadataNet.serverUrl]];
  1413. if (directory != nil)
  1414. return;
  1415. }
  1416. }
  1417.  
  1418. // Stop Timer
  1419. [_timerProcessAutoDownloadUpload invalidate];
  1420.  
  1421. NSInteger maxConcurrentDownloadUpload = [maxConcurrent integerValue];
  1422.  
  1423. NSInteger counterDownloadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  1424. NSInteger counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1425. NSInteger counterUploadInLock = [[[NCManageDatabase sharedInstance] getQueueUploadWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND lock = true", self.activeAccount]] count];
  1426.  
  1427. NSInteger counterNewUpload = 0;
  1428.  
  1429. // ------------------------- <selector Auto Download> -------------------------
  1430.  
  1431. while (counterDownloadInSession < maxConcurrentDownloadUpload) {
  1432.  
  1433. metadataNet = [[NCManageDatabase sharedInstance] getQueueDownload];
  1434. if (metadataNet) {
  1435.  
  1436. [[CCNetworking sharedNetworking] downloadFile:metadataNet.fileName fileID:metadataNet.fileID serverUrl:metadataNet.serverUrl selector:metadataNet.selector selectorPost:metadataNet.selectorPost session:metadataNet.session taskStatus:metadataNet.taskStatus delegate:self.activeMain];
  1437.  
  1438. } else
  1439. break;
  1440.  
  1441. counterDownloadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  1442. }
  1443.  
  1444. // ------------------------- <selector Auto Upload> -------------------------
  1445.  
  1446. if (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload && counterUploadInLock < 1) {
  1447.  
  1448. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadLockWithSelector:selectorUploadAutoUpload];
  1449. if (metadataNet) {
  1450.  
  1451. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1452.  
  1453. counterNewUpload++;
  1454. }
  1455.  
  1456. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1457. }
  1458.  
  1459. // ------------------------- <selector Auto Upload All> ----------------------
  1460.  
  1461. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1462. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND sessionSelector = %@ AND sessionTaskIdentifier = %i", _activeAccount, selectorUploadAutoUploadAll, k_taskIdentifierError] sorted:nil ascending:NO];
  1463.  
  1464. NSInteger errorCount = [metadatas count];
  1465.  
  1466. if (errorCount >= k_maxErrorAutoUploadAll) {
  1467.  
  1468. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1469.  
  1470. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionAutoUpload selector:selectorUploadAutoUploadAll note:@"_too_errors_automatic_all_" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  1471.  
  1472. } else {
  1473.  
  1474. if (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload && counterUploadInLock < 1) {
  1475.  
  1476. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadLockWithSelector:selectorUploadAutoUploadAll];
  1477. if (metadataNet) {
  1478.  
  1479. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1480.  
  1481. counterNewUpload++;
  1482. }
  1483.  
  1484. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1485. }
  1486. }
  1487.  
  1488. // ------------------------- <selector Upload File> -------------------------
  1489.  
  1490. if (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload && counterUploadInLock < 1) {
  1491.  
  1492. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadLockWithSelector:selectorUploadFile];
  1493. if (metadataNet) {
  1494.  
  1495. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1496.  
  1497. counterNewUpload++;
  1498. }
  1499.  
  1500. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1501. }
  1502.  
  1503. // Start Timer
  1504. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(processAutoDownloadUpload) userInfo:nil repeats:YES];
  1505. }
  1506.  
  1507. #pragma --------------------------------------------------------------------------------------------
  1508. #pragma mark ===== Process Verify =====
  1509. #pragma --------------------------------------------------------------------------------------------
  1510.  
  1511. - (void)verifyLockOnLoadAutoUpload
  1512. {
  1513. // Test Maintenance
  1514. if (self.maintenanceMode || self.activeAccount.length == 0)
  1515. return;
  1516.  
  1517. NSInteger counterUploadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count];
  1518. NSArray *tableMetadatasInLock = [[NCManageDatabase sharedInstance] getLockQueueUpload];
  1519.  
  1520. if (counterUploadInSession == 0 && [tableMetadatasInLock count] > 0) {
  1521.  
  1522. // Unlock
  1523. for (tableMetadata *metadata in tableMetadatasInLock) {
  1524.  
  1525. if ([[NCManageDatabase sharedInstance] isTableInvalidated:metadata] == NO)
  1526. [[NCManageDatabase sharedInstance] unlockQueueUploadWithAssetLocalIdentifier:metadata.assetLocalIdentifier];
  1527. }
  1528. }
  1529. }
  1530.  
  1531. - (void)verifyUploadInErrorOrWait
  1532. {
  1533. // Test Maintenance
  1534. if (self.maintenanceMode || self.activeAccount.length == 0)
  1535. return;
  1536.  
  1537. NSMutableSet *directoryIDs = [NSMutableSet new];
  1538.  
  1539. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session CONTAINS 'upload' AND (sessionTaskIdentifier = %i OR sessionTaskIdentifier = %i)", _activeAccount, k_taskIdentifierError, k_taskIdentifierWaitStart] sorted:nil ascending:NO];
  1540.  
  1541. NSLog(@"[LOG] Verify re upload in error n. %lu", (unsigned long)[metadatas count]);
  1542.  
  1543. for (tableMetadata *metadata in metadatas) {
  1544.  
  1545. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus: k_taskStatusResume];
  1546.  
  1547. [directoryIDs addObject:metadata.directoryID];
  1548.  
  1549. NSLog(@"[LOG] Re upload file : %@", metadata.fileName);
  1550. }
  1551. }
  1552.  
  1553. #pragma --------------------------------------------------------------------------------------------
  1554. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1555. #pragma --------------------------------------------------------------------------------------------
  1556.  
  1557. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1558. {
  1559. return YES;
  1560. }
  1561.  
  1562. // Method called from iOS system to send a file from other app.
  1563. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1564. {
  1565. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1566. NSLog(@"[LOG] the path is: %@", url.path);
  1567.  
  1568. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1569. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1570.  
  1571. if (self.activeAccount) {
  1572.  
  1573. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1574.  
  1575. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1576. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1577.  
  1578. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1579.  
  1580. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1581. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1582. });
  1583. }
  1584.  
  1585. // remove from InBox
  1586. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1587.  
  1588. return YES;
  1589. }
  1590.  
  1591. #pragma --------------------------------------------------------------------------------------------
  1592. #pragma mark ===== Crashlytics =====
  1593. #pragma --------------------------------------------------------------------------------------------
  1594.  
  1595. - (void) logUser
  1596. {
  1597. if (self.activeAccount.length > 0)
  1598. [CrashlyticsKit setUserName:self.activeAccount];
  1599. }
  1600.  
  1601. #pragma --------------------------------------------------------------------------------------------
  1602. #pragma mark ===== Maintenance Mode =====
  1603. #pragma --------------------------------------------------------------------------------------------
  1604.  
  1605. - (void)maintenanceMode:(BOOL)mode
  1606. {
  1607. self.maintenanceMode = mode;
  1608. }
  1609.  
  1610. #pragma --------------------------------------------------------------------------------------------
  1611. #pragma mark ===== UPGRADE =====
  1612. #pragma --------------------------------------------------------------------------------------------
  1613.  
  1614. - (BOOL)upgrade
  1615. {
  1616. #ifdef DEBUG
  1617. //self.maintenanceMode = YES;
  1618. #endif
  1619.  
  1620. NSString *actualVersion = [CCUtility getVersion];
  1621. NSString *actualBuild = [CCUtility getBuild];
  1622.  
  1623. /* ---------------------- UPGRADE VERSION ----------------------- */
  1624.  
  1625. // VERSION < 2.17.6
  1626.  
  1627. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1628.  
  1629. // Remove All old Photo Library
  1630. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1631. }
  1632.  
  1633. // VERSION == 2.17.6
  1634. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1635.  
  1636. // Build < 10
  1637. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1638.  
  1639. // Remove All old Photo Library
  1640. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1641. }
  1642. }
  1643.  
  1644. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1645.  
  1646. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1647. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1648. }
  1649.  
  1650. return YES;
  1651. }
  1652.  
  1653. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement