AppDelegate.m 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627
  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. #import "AppDelegate.h"
  24. #import "iRate.h"
  25. #import "AFURLSessionManager.h"
  26. #import "CCNetworking.h"
  27. #import "CCGraphics.h"
  28. #import "CCPhotos.h"
  29. #import "CCSynchronize.h"
  30. #import "CCMain.h"
  31. #import "CCDetail.h"
  32. #import "NCClientEncryption.h"
  33. #import "Firebase.h"
  34. #import <Fabric/Fabric.h>
  35. #import <Crashlytics/Crashlytics.h>
  36. #import "JDStatusBarNotification.h"
  37. #import "NCBridgeSwift.h"
  38. #import "NCAutoUpload.h"
  39. @interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
  40. {
  41. }
  42. @end
  43. @implementation AppDelegate
  44. + (void)initialize
  45. {
  46. [iRate sharedInstance].daysUntilPrompt = 5;
  47. [iRate sharedInstance].usesUntilPrompt = 5;
  48. [iRate sharedInstance].promptForNewVersionIfUserRated = true;
  49. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  50. //enable preview mode
  51. //[iRate sharedInstance].previewMode = YES;
  52. }
  53. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  54. {
  55. // Brand
  56. if ([NCBrandOptions sharedInstance].use_firebase) {
  57. /*
  58. In order for this to work, proper GoogleService-Info.plist must be included
  59. */
  60. @try {
  61. [FIRApp configure];
  62. } @catch (NSException *exception) {
  63. NSLog(@"[LOG] Something went wrong while configuring Firebase");
  64. }
  65. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
  66. UIUserNotificationType allNotificationTypes =(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
  67. UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
  68. [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  69. } else {
  70. // iOS 10 or later
  71. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  72. // For iOS 10 display notification (sent via APNS)
  73. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  74. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  75. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  76. }];
  77. // For iOS 10 data message (sent via FCM)
  78. [FIRMessaging messaging].remoteMessageDelegate = self;
  79. #endif
  80. }
  81. }
  82. NSString *dir;
  83. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:[NCBrandOptions sharedInstance].capabilitiesGroups];
  84. NSLog(@"[LOG] Start program group -----------------");
  85. NSLog(@"%@", dirGroup);
  86. NSLog(@"[LOG] Start program application -----------");
  87. NSLog(@"%@", [[CCUtility getDirectoryLocal] stringByDeletingLastPathComponent]);
  88. NSLog(@"[LOG] -------------------------------------");
  89. // create Directory local => Documents
  90. dir = [CCUtility getDirectoryLocal];
  91. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  92. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  93. // create Directory audio => Library, Application Support, audio
  94. dir = [CCUtility getDirectoryAudio];
  95. if (![[NSFileManager defaultManager] fileExistsAtPath: dir] && [dir length])
  96. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  97. // create dir Database Nextcloud
  98. dir = [[dirGroup URLByAppendingPathComponent:appDatabaseNextcloud] path];
  99. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  100. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  101. NSError *error = nil;
  102. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:dir error:&error];
  103. // Verify upgrade
  104. if ([self upgrade]) {
  105. // Set account, if no exists clear all
  106. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  107. if (account == nil) {
  108. // remove all the keys Chain
  109. [CCUtility deleteAllChainStore];
  110. // remove all the App group key
  111. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  112. } else {
  113. [self settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  114. }
  115. }
  116. // Operation Queue OC Networking
  117. _netQueue = [[NSOperationQueue alloc] init];
  118. _netQueue.name = k_queue;
  119. _netQueue.maxConcurrentOperationCount = k_maxConcurrentOperation;
  120. // Add notification change session
  121. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionChanged:) name:k_networkingSessionNotification object:nil];
  122. // Initialization Share
  123. self.sharesID = [NSMutableDictionary new];
  124. self.sharesLink = [NSMutableDictionary new];
  125. self.sharesUserAndGroup = [NSMutableDictionary new];
  126. // Initialization Notification
  127. self.listOfNotifications = [NSMutableArray new];
  128. // Background Fetch
  129. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  130. // Initialization List
  131. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  132. self.listChangeTask = [[NSMutableDictionary alloc] init];
  133. self.listMainVC = [[NSMutableDictionary alloc] init];
  134. // setting Reachable in back
  135. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  136. self.reachability = [Reachability reachabilityForInternetConnection];
  137. self.lastReachability = [self.reachability isReachable];
  138. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  139. [self.reachability startNotifier];
  140. });
  141. //AV Session
  142. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  143. //[[AVAudioSession sharedInstance] setActive:YES error:nil];
  144. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  145. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  146. //UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  147. UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
  148. navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
  149. splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModeAllVisible;
  150. [app aspectNavigationControllerBar:navigationController.navigationBar online:YES hidden:NO];
  151. // Settings TabBar
  152. [self createTabBarController];
  153. // passcode
  154. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  155. dispatch_async(dispatch_get_main_queue(), ^{
  156. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  157. });
  158. // Quick Actions
  159. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  160. [self configDynamicShortcutItems];
  161. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  162. if (shortcutItem)
  163. [self handleShortCutItem:shortcutItem];
  164. }
  165. // Start Timer
  166. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(processAutoDownloadUpload) userInfo:nil repeats:YES];
  167. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  168. // Registration Push Notification
  169. UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert;
  170. UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
  171. [application registerUserNotificationSettings:notificationSettings];
  172. // Fabric
  173. [Fabric with:@[[Crashlytics class]]];
  174. [self logUser];
  175. return YES;
  176. }
  177. //
  178. // L' applicazione si dimetterà dallo stato di attivo
  179. //
  180. - (void)applicationWillResignActive:(UIApplication *)application
  181. {
  182. [_activeMain closeAllMenu];
  183. [self updateApplicationIconBadgeNumber];
  184. }
  185. //
  186. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  187. //
  188. - (void)applicationWillEnterForeground:(UIApplication *)application
  189. {
  190. // refresh active Main
  191. if (_activeMain) {
  192. [_activeMain reloadDatasource];
  193. [_activeMain readFileReloadFolder];
  194. }
  195. // refresh Photos tab
  196. if (_activePhotos) {
  197. [_activePhotos reloadDatasourceForced];
  198. }
  199. // Initializations
  200. [self applicationInitialized];
  201. }
  202. //
  203. // L' applicazione è entrata nello sfondo
  204. //
  205. - (void)applicationDidEnterBackground:(UIApplication *)application
  206. {
  207. NSLog(@"[LOG] Enter in Background");
  208. [[CCQuickActions quickActionsManager] closeAll];
  209. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  210. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  211. __block UIBackgroundTaskIdentifier background_task;
  212. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  213. //Clean up code. Tell the system that we are done.
  214. [application endBackgroundTask: background_task];
  215. background_task = UIBackgroundTaskInvalid;
  216. }];
  217. }
  218. }
  219. //
  220. // L'applicazione terminerà
  221. //
  222. - (void)applicationWillTerminate:(UIApplication *)application
  223. {
  224. NSLog(@"[LOG] bye bye, Nextcloud !");
  225. }
  226. //
  227. // Application Initialized
  228. //
  229. - (void)applicationInitialized
  230. {
  231. // Test Maintenance
  232. if (self.maintenanceMode)
  233. return;
  234. // Execute : now
  235. NSLog(@"[LOG] Update Folder Photo");
  236. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:_activeUrl];
  237. if ([autoUploadPath length] > 0) {
  238. NSString *fileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  239. NSString *serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:_activeUrl];
  240. [[CCSynchronize sharedSynchronize] readFileForFolder:fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  241. }
  242. // Execute : after 1 sec.
  243. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  244. // verify Download
  245. [[CCNetworking sharedNetworking] verifyDownloadInProgress];
  246. if (_activeMain)
  247. [[CCNetworking sharedNetworking] verifyDownloadInError:self.activeMain];
  248. // verify Upload
  249. [[CCNetworking sharedNetworking] verifyUploadInProgress];
  250. [[CCNetworking sharedNetworking] verifyUploadInErrorOrWait];
  251. if (_activeMain) {
  252. NSLog(@"[LOG] Request Server Capabilities");
  253. [_activeMain requestServerCapabilities];
  254. }
  255. if (_activeMain && [[NCBrandOptions sharedInstance] use_middlewarePing]) {
  256. NSLog(@"[LOG] Middleware Ping");
  257. [_activeMain middlewarePing];
  258. }
  259. NSLog(@"[LOG] Initialize Auto upload");
  260. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  261. NSLog(@"[LOG] Listning Favorites");
  262. [_activeFavorites readListingFavorites];
  263. });
  264. }
  265. #pragma --------------------------------------------------------------------------------------------
  266. #pragma mark ===== Login =====
  267. #pragma --------------------------------------------------------------------------------------------
  268. - (void)openLoginView:(id)delegate loginType:(enumLoginType)loginType
  269. {
  270. @synchronized (self) {
  271. if ([NCBrandOptions sharedInstance].use_login_web) {
  272. if (!_activeLoginWeb.view.window) {
  273. _activeLoginWeb = [CCLoginWeb new];
  274. _activeLoginWeb.delegate = delegate;
  275. _activeLoginWeb.loginType = loginType;
  276. dispatch_async(dispatch_get_main_queue(), ^ {
  277. [_activeLoginWeb presentModalWithDefaultTheme:delegate];
  278. });
  279. }
  280. } else {
  281. if (_activeLogin == nil) {
  282. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  283. _activeLogin.delegate = delegate;
  284. _activeLogin.loginType = loginType;
  285. dispatch_async(dispatch_get_main_queue(), ^ {
  286. [delegate presentViewController:_activeLogin animated:YES completion:nil];
  287. });
  288. }
  289. }
  290. }
  291. }
  292. #pragma --------------------------------------------------------------------------------------------
  293. #pragma mark ===== Setting Active Account for all APP =====
  294. #pragma --------------------------------------------------------------------------------------------
  295. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activeUserID:(NSString *)activeUserID activePassword:(NSString *)activePassword
  296. {
  297. self.activeAccount = activeAccount;
  298. self.activeUrl = activeUrl;
  299. self.activeUser = activeUser;
  300. self.activeUserID = activeUserID;
  301. self.activePassword = activePassword;
  302. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  303. // Setting Account to CCNetworking
  304. [[CCNetworking sharedNetworking] settingAccount];
  305. }
  306. #pragma --------------------------------------------------------------------------------------------
  307. #pragma mark ===== Push Notification =====
  308. #pragma --------------------------------------------------------------------------------------------
  309. - (void)subscribingNextcloudServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  310. {
  311. NSLog(@"[LOG] Error Subscribing Nextcloud Server %@", message);
  312. }
  313. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
  314. {
  315. [application registerForRemoteNotifications];
  316. }
  317. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  318. {
  319. // test
  320. if (self.activeAccount.length == 0)
  321. return;
  322. // FIREBASE registered token
  323. [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
  324. NSString *pushToken = [[FIRInstanceID instanceID] token];
  325. // NSString *pushToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
  326. NSString *pushTokenHash = [[NCClientEncryption sharedManager] createSHA512:pushToken];
  327. NSDictionary *devicePushKey = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DevicePushKey-Info" ofType:@"plist"]];
  328. #ifdef DEBUG
  329. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyDevelopment"];
  330. #else
  331. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyProduction"];
  332. #endif
  333. if ([devicePublicKey length] > 0 && [pushTokenHash length] > 0) {
  334. NSLog(@"[LOG] Firebase InstanceID push token: %@", pushToken);
  335. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  336. NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:pushToken, @"pushToken", pushTokenHash, @"pushTokenHash", devicePublicKey, @"devicePublicKey", nil];
  337. metadataNet.action = actionSubscribingNextcloudServer;
  338. metadataNet.options = options;
  339. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  340. }
  341. }
  342. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  343. {
  344. NSLog(@"[LOG] Error register remote notification %@", error);
  345. }
  346. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  347. UIApplicationState state = [application applicationState];
  348. if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
  349. NSLog(@"[LOG] Receive Notification on Inactive or Background state");
  350. } else {
  351. NSLog(@"[LOG] Receive Notification on Active state");
  352. }
  353. // If you are receiving a notification message while your app is in the background,
  354. // this callback will not be fired till the user taps on the notification launching the application.
  355. // TODO: Handle data of notification
  356. // Print message ID.
  357. //if (userInfo[kGCMMessageIDKey]) {
  358. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  359. //}
  360. // Print full message.
  361. NSLog(@"[LOG] %@", userInfo);
  362. }
  363. - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  364. {
  365. UIApplicationState state = [application applicationState];
  366. // Print message ID.
  367. //if (userInfo[kGCMMessageIDKey]) {
  368. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  369. //}
  370. // Print full message.
  371. NSLog(@"[LOG] %@", userInfo);
  372. if (state == UIApplicationStateBackground || (state == UIApplicationStateInactive)) {
  373. } else if (state == UIApplicationStateInactive) {
  374. // user tapped notification
  375. completionHandler(UIBackgroundFetchResultNewData);
  376. } else {
  377. // app is active
  378. completionHandler(UIBackgroundFetchResultNoData);
  379. }
  380. }
  381. #pragma FIREBASE
  382. - (void)tokenRefreshNotification:(NSNotification *)notification {
  383. // Note that this callback will be fired everytime a new token is generated, including the first
  384. // time. So if you need to retrieve the token as soon as it is available this is where that
  385. // should be done.
  386. NSString *refreshedToken = [[FIRInstanceID instanceID] token];
  387. NSLog(@"[LOG] InstanceID token: %@", refreshedToken);
  388. // Connect to FCM since connection may have failed when attempted before having a token.
  389. [self connectToFcm];
  390. // TODO: If necessary send token to application server.
  391. }
  392. - (void)connectToFcm {
  393. // Won't connect since there is no token
  394. if (![[FIRInstanceID instanceID] token]) {
  395. return;
  396. }
  397. // Disconnect previous FCM connection if it exists.
  398. [[FIRMessaging messaging] disconnect];
  399. [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
  400. if (error != nil) {
  401. NSLog(@"[LOG] Unable to connect to FCM. %@", error);
  402. } else {
  403. NSLog(@"[LOG] Connected to FCM.");
  404. }
  405. }];
  406. }
  407. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  408. // Receive data message on iOS 10 devices while app is in the foreground.
  409. - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  410. // Print full message
  411. NSLog(@"[LOG] %@", remoteMessage.appData);
  412. }
  413. #endif
  414. #pragma --------------------------------------------------------------------------------------------
  415. #pragma mark ===== Quick Actions - ShotcutItem =====
  416. #pragma --------------------------------------------------------------------------------------------
  417. - (void)configDynamicShortcutItems
  418. {
  419. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  420. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionPhotos"];
  421. UIApplicationShortcutIcon *shortcutUploadIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionUpload"];
  422. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  423. UIApplicationShortcutItem *shortcutUpload = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.upload", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadIcon userInfo:nil];
  424. // add the array to our app
  425. if (shortcutUpload && shortcutPhotos)
  426. [UIApplication sharedApplication].shortcutItems = @[shortcutUpload, shortcutPhotos];
  427. }
  428. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  429. {
  430. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  431. completionHandler(handledShortCutItem);
  432. }
  433. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  434. {
  435. BOOL handled = NO;
  436. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  437. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  438. NSString *shortcutUpload = [NSString stringWithFormat:@"%@.upload", bundleId];
  439. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  440. if ([shortcutItem.type isEqualToString:shortcutUpload] && self.activeAccount) {
  441. dispatch_async(dispatch_get_main_queue(), ^{
  442. if (_activeMain) {
  443. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  444. if (splitViewController.isCollapsed) {
  445. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  446. for (UINavigationController *nvc in tbc.viewControllers) {
  447. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  448. [nvc popToRootViewControllerAnimated:NO];
  449. }
  450. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  451. } else {
  452. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  453. [nvcDetail popToRootViewControllerAnimated:NO];
  454. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  455. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  456. }
  457. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  458. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  459. [[CCQuickActions quickActionsManager] startQuickActionsViewController:_activeMain];
  460. });
  461. }
  462. });
  463. handled = YES;
  464. }
  465. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  466. dispatch_async(dispatch_get_main_queue(), ^{
  467. if (_activeMain) {
  468. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  469. if (splitViewController.isCollapsed) {
  470. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  471. for (UINavigationController *nvc in tbc.viewControllers) {
  472. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  473. [nvc popToRootViewControllerAnimated:NO];
  474. }
  475. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  476. } else {
  477. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  478. [nvcDetail popToRootViewControllerAnimated:NO];
  479. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  480. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  481. }
  482. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  483. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  484. [[CCQuickActions quickActionsManager] startQuickActionsViewController:_activeMain];
  485. });
  486. }
  487. });
  488. handled = YES;
  489. }
  490. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  491. dispatch_async(dispatch_get_main_queue(), ^{
  492. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  493. if (splitViewController.isCollapsed) {
  494. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  495. for (UINavigationController *nvc in tbc.viewControllers) {
  496. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  497. [nvc popToRootViewControllerAnimated:NO];
  498. }
  499. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  500. } else {
  501. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  502. [nvcDetail popToRootViewControllerAnimated:NO];
  503. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  504. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  505. }
  506. });
  507. handled = YES;
  508. }
  509. return handled;
  510. }
  511. #pragma --------------------------------------------------------------------------------------------
  512. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  513. #pragma --------------------------------------------------------------------------------------------
  514. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  515. {
  516. static NSInteger errorCodePrev = 0;
  517. dispatch_async(dispatch_get_main_queue(), ^{
  518. if (visible) {
  519. if (errorcode == kCFURLErrorNotConnectedToInternet || errorcode == k_CCErrorNetworkNowAvailable) {
  520. if (errorCodePrev != errorcode)
  521. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  522. errorCodePrev = errorcode;
  523. } else {
  524. if (description.length > 0) {
  525. [TWMessageBarManager sharedInstance].styleSheet = self;
  526. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  527. }
  528. }
  529. } else {
  530. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  531. }
  532. });
  533. }
  534. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  535. {
  536. UIColor *backgroundColor = nil;
  537. switch (type)
  538. {
  539. case TWMessageBarMessageTypeError:
  540. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  541. break;
  542. case TWMessageBarMessageTypeSuccess:
  543. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  544. break;
  545. case TWMessageBarMessageTypeInfo:
  546. backgroundColor = [NCBrandColor sharedInstance].brand;
  547. break;
  548. default:
  549. break;
  550. }
  551. return backgroundColor;
  552. }
  553. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  554. {
  555. UIColor *strokeColor = nil;
  556. switch (type)
  557. {
  558. case TWMessageBarMessageTypeError:
  559. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  560. break;
  561. case TWMessageBarMessageTypeSuccess:
  562. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  563. break;
  564. case TWMessageBarMessageTypeInfo:
  565. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  566. break;
  567. default:
  568. break;
  569. }
  570. return strokeColor;
  571. }
  572. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  573. {
  574. UIImage *iconImage = nil;
  575. switch (type)
  576. {
  577. case TWMessageBarMessageTypeError:
  578. iconImage = [UIImage imageNamed:@"icon-error.png"];
  579. break;
  580. case TWMessageBarMessageTypeSuccess:
  581. iconImage = [UIImage imageNamed:@"icon-success.png"];
  582. break;
  583. case TWMessageBarMessageTypeInfo:
  584. iconImage = [UIImage imageNamed:@"icon-info.png"];
  585. break;
  586. default:
  587. break;
  588. }
  589. return iconImage;
  590. }
  591. - (void)updateApplicationIconBadgeNumber
  592. {
  593. // Test Maintenance
  594. if (self.maintenanceMode)
  595. return;
  596. NSInteger queueDownload = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  597. NSInteger queueUpload = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count];
  598. // Total
  599. NSInteger total = queueDownload + queueUpload + [[NCManageDatabase sharedInstance] countQueueDownloadWithSession:nil] + [[NCManageDatabase sharedInstance] countQueueUploadWithSession:nil];
  600. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  601. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  602. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  603. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  604. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  605. if (total > 0) {
  606. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  607. } else {
  608. [tbItem setBadgeValue:nil];
  609. NSDictionary* userInfo = @{@"fileID": @"", @"serverUrl": @"", @"progress": [NSNumber numberWithFloat:0]};
  610. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  611. }
  612. }
  613. }
  614. #pragma --------------------------------------------------------------------------------------------
  615. #pragma mark ===== TabBarController =====
  616. #pragma --------------------------------------------------------------------------------------------
  617. - (void)createTabBarController
  618. {
  619. UITabBarItem *item;
  620. NSLayoutConstraint *constraint;
  621. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  622. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  623. [app aspectTabBar:tabBarController.tabBar hidden:NO];
  624. // File
  625. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  626. [item setTitle:NSLocalizedString(@"_home_", nil)];
  627. item.image = [UIImage imageNamed:@"tabBarFiles"];
  628. item.selectedImage = [UIImage imageNamed:@"tabBarFiles"];
  629. // Favorites
  630. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  631. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  632. item.image = [UIImage imageNamed:@"tabBarFavorite"];
  633. item.selectedImage = [UIImage imageNamed:@"tabBarFavorite"];
  634. // (PLUS)
  635. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  636. item.title = nil;
  637. item.image = nil;
  638. item.enabled = false;
  639. // Photos
  640. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPhotos];
  641. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  642. item.image = [UIImage imageNamed:@"tabBarPhotos"];
  643. item.selectedImage = [UIImage imageNamed:@"tabBarPhotos"];
  644. // More
  645. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  646. [item setTitle:NSLocalizedString(@"_more_", nil)];
  647. item.image = [UIImage imageNamed:@"tabBarMore"];
  648. item.selectedImage = [UIImage imageNamed:@"tabBarMore"];
  649. // Plus Button
  650. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brand];
  651. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  652. buttonPlus.tag = 99;
  653. //buttonPlus.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
  654. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  655. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  656. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  657. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  658. [tabBarController.tabBar addSubview:buttonPlus];
  659. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  660. [tabBarController.view addConstraint:constraint];
  661. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:5];
  662. [tabBarController.view addConstraint:constraint];
  663. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:0.5 constant:0];
  664. [tabBarController.view addConstraint:constraint];
  665. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:0.5 constant:0];
  666. [tabBarController.view addConstraint:constraint];
  667. }
  668. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav online:(BOOL)online hidden:(BOOL)hidden
  669. {
  670. nav.translucent = NO;
  671. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  672. nav.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  673. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].navigationBarText}];
  674. if (!online)
  675. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  676. nav.hidden = hidden;
  677. [nav setAlpha:1];
  678. }
  679. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  680. {
  681. tab.translucent = NO;
  682. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  683. tab.tintColor = [NCBrandColor sharedInstance].brand;
  684. tab.hidden = hidden;
  685. [tab setAlpha:1];
  686. }
  687. - (void)plusButtonVisibile:(BOOL)visible
  688. {
  689. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  690. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  691. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  692. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brand];
  693. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  694. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  695. if (buttonPlus) {
  696. if (visible) {
  697. buttonPlus.hidden = false;
  698. } else {
  699. buttonPlus.hidden = true;
  700. }
  701. }
  702. }
  703. - (void)handleTouchTabbarCenter:(id)sender
  704. {
  705. // Test Maintenance
  706. if (self.maintenanceMode)
  707. return;
  708. UIView *view = [[(UIButton *)sender superview] superview];
  709. CreateMenuAdd *menuAdd = [[CreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brand];
  710. if ([CCUtility getCreateMenuEncrypted])
  711. [menuAdd createMenuEncryptedWithView:view];
  712. else
  713. [menuAdd createMenuPlainWithView:view];
  714. }
  715. - (void)selectedTabBarController:(NSInteger)index
  716. {
  717. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  718. if (splitViewController.isCollapsed) {
  719. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  720. for (UINavigationController *nvc in tbc.viewControllers) {
  721. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  722. [nvc popToRootViewControllerAnimated:NO];
  723. }
  724. [tbc setSelectedIndex: index];
  725. } else {
  726. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  727. [nvcDetail popToRootViewControllerAnimated:NO];
  728. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  729. [tbc setSelectedIndex: index];
  730. }
  731. }
  732. - (NSString *)getTabBarControllerActiveServerUrl
  733. {
  734. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  735. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  736. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  737. NSInteger index = tabBarController.selectedIndex;
  738. // select active serverUrl
  739. if (index == k_tabBarApplicationIndexFile) {
  740. serverUrl = app.activeMain.serverUrl;
  741. } else if (index == k_tabBarApplicationIndexFavorite) {
  742. if (app.activeFavorites.serverUrl)
  743. serverUrl = app.activeFavorites.serverUrl;
  744. } else if (index == k_tabBarApplicationIndexPhotos) {
  745. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  746. }
  747. return serverUrl;
  748. }
  749. #pragma --------------------------------------------------------------------------------------------
  750. #pragma mark ===== Theming Color =====
  751. #pragma --------------------------------------------------------------------------------------------
  752. - (void)settingThemingColorBrand
  753. {
  754. UIColor* newColor;
  755. if (self.activeAccount.length > 0) {
  756. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilites];
  757. if ([NCBrandOptions sharedInstance].use_themingColor && capabilities.themingColor.length == 7) {
  758. BOOL isLight = [CCGraphics isLight:[CCGraphics colorFromHexString:capabilities.themingColor]];
  759. if (isLight) {
  760. // Activity
  761. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Server Theming" note:NSLocalizedString(@"_theming_is_light_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  762. newColor = [NCBrandColor sharedInstance].customer;
  763. } else {
  764. newColor = [CCGraphics colorFromHexString:capabilities.themingColor];
  765. }
  766. } else {
  767. newColor = [NCBrandColor sharedInstance].customer;
  768. }
  769. } else {
  770. newColor = [NCBrandColor sharedInstance].customer;
  771. }
  772. if (self.activeAccount.length > 0 && ![newColor isEqual:[NCBrandColor sharedInstance].brand] && newColor) {
  773. [NCBrandColor sharedInstance].brand = newColor;
  774. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  775. }
  776. }
  777. - (void)changeTheming:(UIViewController *)vc
  778. {
  779. UIColor *color = [NCBrandColor sharedInstance].brand;
  780. // Change Navigation & TabBar color
  781. vc.navigationController.navigationBar.barTintColor = color;
  782. vc.tabBarController.tabBar.tintColor = color;
  783. // Change button Plus
  784. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  785. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  786. UIButton *button = [tabBarController.view viewWithTag:99];
  787. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:color];
  788. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  789. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  790. // Tint Color GLOBAL WINDOW
  791. [self.window setTintColor:[NCBrandColor sharedInstance].brand];
  792. }
  793. #pragma --------------------------------------------------------------------------------------------
  794. #pragma mark ===== Manager Passcode =====
  795. #pragma --------------------------------------------------------------------------------------------
  796. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  797. {
  798. // ServerUrl active
  799. NSString *serverUrl = self.activeMain.serverUrl;
  800. BOOL isBlockZone = false;
  801. // fermiamo la data della sessione
  802. self.sessionePasscodeLock = nil;
  803. // se il block code è a zero esci con NON attivare la richiesta password
  804. if ([[CCUtility getBlockCode] length] == 0) return NO;
  805. // se non c'è attivo un account esci con NON attivare la richiesta password
  806. if ([self.activeAccount length] == 0) return NO;
  807. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  808. if (serverUrl && _activeUrl) {
  809. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  810. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", self.activeAccount, serverUrl]];
  811. if (directory.lock) {
  812. isBlockZone = true;
  813. break;
  814. } else {
  815. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  816. if (serverUrl == self.activeUrl)
  817. break;
  818. }
  819. }
  820. }
  821. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  822. return YES;
  823. }
  824. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  825. {
  826. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  827. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  828. viewController.delegate = self;
  829. viewController.title = [NCBrandOptions sharedInstance].brand;
  830. viewController.fromType = CCBKPasscodeFromLockScreen;
  831. viewController.inputViewTitlePassword = YES;
  832. if ([CCUtility getSimplyBlockCode]) {
  833. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  834. viewController.passcodeInputView.maximumLength = 6;
  835. } else {
  836. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  837. viewController.passcodeInputView.maximumLength = 64;
  838. }
  839. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  840. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  841. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  842. return navigationController;
  843. }
  844. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  845. {
  846. [aViewController dismissViewControllerAnimated:YES completion:nil];
  847. // is a lock screen
  848. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  849. [aViewController dismissViewControllerAnimated:YES completion:nil];
  850. // start session Passcode Lock
  851. BOOL isBlockZone = false;
  852. NSString *serverUrl = self.activeMain.serverUrl;
  853. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  854. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", self.activeAccount, serverUrl]];
  855. if (directory.lock) {
  856. isBlockZone = true;
  857. break;
  858. } else {
  859. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  860. if (serverUrl == self.activeUrl)
  861. break;
  862. }
  863. }
  864. if (isBlockZone)
  865. self.sessionePasscodeLock = [NSDate date];
  866. }
  867. }
  868. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  869. {
  870. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  871. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  872. //self.lockUntilDate = nil;
  873. //self.failedAttempts = 0;
  874. aResultHandler(YES);
  875. } else aResultHandler(NO);
  876. } else aResultHandler(YES);
  877. }
  878. #pragma --------------------------------------------------------------------------------------------
  879. #pragma mark ===== reachabilityChanged =====
  880. #pragma --------------------------------------------------------------------------------------------
  881. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  882. {
  883. if ([self.reachability isReachable]) {
  884. if (self.lastReachability == NO) {
  885. [self messageNotification:@"_network_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:k_CCErrorNetworkNowAvailable];
  886. if (_activeMain)
  887. [_activeMain performSelector:@selector(requestServerCapabilities) withObject:nil afterDelay:3];
  888. }
  889. NSLog(@"[LOG] Reachability Changed: Reachable");
  890. self.lastReachability = YES;
  891. } else {
  892. if (self.lastReachability == YES) {
  893. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  894. }
  895. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  896. self.lastReachability = NO;
  897. }
  898. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  899. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  900. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  901. }
  902. #pragma --------------------------------------------------------------------------------------------
  903. #pragma mark ===== Fetch =====
  904. #pragma --------------------------------------------------------------------------------------------
  905. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  906. {
  907. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  908. // Verify new photo
  909. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  910. // after 20 sec
  911. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  912. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", self.activeAccount] sorted:nil ascending:NO];
  913. if ([records count] > 0) {
  914. completionHandler(UIBackgroundFetchResultNewData);
  915. } else {
  916. completionHandler(UIBackgroundFetchResultNoData);
  917. }
  918. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  919. });
  920. }
  921. #pragma --------------------------------------------------------------------------------------------
  922. #pragma mark ===== Operation Networking & Session =====
  923. #pragma --------------------------------------------------------------------------------------------
  924. //
  925. // Method called by the system when all the background task has end
  926. //
  927. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  928. {
  929. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  930. // after 20 sec
  931. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  932. self.backgroundSessionCompletionHandler = completionHandler;
  933. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  934. self.backgroundSessionCompletionHandler = nil;
  935. completionHandler();
  936. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  937. });
  938. }
  939. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  940. {
  941. id operation;
  942. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withUserID:_activeUserID withPassword:_activePassword withUrl:_activeUrl];
  943. [operation setQueuePriority:metadataNet.priority];
  944. [netQueue addOperation:operation];
  945. }
  946. // Notification change session
  947. - (void)sessionChanged:(NSNotification *)notification
  948. {
  949. NSURLSession *session;
  950. NSString *fileID;
  951. NSURLSessionTask *task;
  952. for (id object in notification.object) {
  953. if ([object isKindOfClass:[NSURLSession class]])
  954. session = object;
  955. if ([object isKindOfClass:[NSString class]])
  956. fileID = object;
  957. if ([object isKindOfClass:[NSURLSessionTask class]])
  958. task = object;
  959. }
  960. /*
  961. Task
  962. */
  963. if (fileID && [_listChangeTask objectForKey:fileID])
  964. dispatch_async(dispatch_get_main_queue(), ^{
  965. [self changeTask:fileID];
  966. });
  967. /*
  968. Session
  969. */
  970. if (session) {
  971. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  972. unsigned long numDownload = [downloadTasks count];
  973. unsigned long numUpload = [uploadTasks count];
  974. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  975. }];
  976. }
  977. }
  978. - (void)changeTask:(NSString *)fileID
  979. {
  980. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  981. if (!metadata) return;
  982. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  983. if (!serverUrl) return;
  984. if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"stopUpload"]) {
  985. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierStop predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  986. }
  987. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"reloadUpload"]) {
  988. // V 1.8 if upload_session_wwan change in upload_session
  989. if ([metadata.session isEqualToString:k_upload_session_wwan])
  990. metadata.session = k_upload_session;
  991. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  992. }
  993. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"reloadDownload"]) {
  994. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  995. [[CCNetworking sharedNetworking] downloadFile:fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:k_download_session taskStatus:k_taskStatusResume delegate:self.activeMain];
  996. });
  997. }
  998. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  999. // remove the file
  1000. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  1001. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  1002. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  1003. }
  1004. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"cancelDownload"]) {
  1005. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1006. }
  1007. // remove ChangeTask (fileID) from the list
  1008. [_listChangeTask removeObjectForKey:fileID];
  1009. // delete progress
  1010. [_listProgressMetadata removeObjectForKey:fileID];
  1011. // Progress Task
  1012. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  1013. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  1014. // Refresh
  1015. if (_activeMain && [_listChangeTask count] == 0) {
  1016. [_activeMain reloadDatasource:serverUrl];
  1017. }
  1018. }
  1019. #pragma --------------------------------------------------------------------------------------------
  1020. #pragma mark ===== Process Auto Upload < k_timerProcess seconds > =====
  1021. #pragma --------------------------------------------------------------------------------------------
  1022. - (void)processAutoDownloadUpload
  1023. {
  1024. // Test Maintenance
  1025. if (self.maintenanceMode)
  1026. return;
  1027. // BACKGROND & FOREGROUND
  1028. NSLog(@"-PROCESS-AUTO-UPLOAD-");
  1029. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1030. // ONLY BACKGROUND
  1031. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1032. } else {
  1033. // ONLY FOREFROUND
  1034. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1035. }
  1036. }
  1037. - (void)loadAutoDownloadUpload:(NSNumber *)maxConcurrent
  1038. {
  1039. CCMetadataNet *metadataNet;
  1040. // Stop Timer
  1041. [_timerProcessAutoDownloadUpload invalidate];
  1042. NSInteger maxConcurrentDownloadUpload = [maxConcurrent integerValue];
  1043. NSInteger counterDownloadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  1044. NSInteger counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1045. NSInteger counterNewUpload = 0;
  1046. // ------------------------- <selector Auto Download> -------------------------
  1047. while (counterDownloadInSession < maxConcurrentDownloadUpload) {
  1048. metadataNet = [[NCManageDatabase sharedInstance] getQueueDownload];
  1049. if (metadataNet) {
  1050. [[CCNetworking sharedNetworking] downloadFile:metadataNet.fileID serverUrl:metadataNet.serverUrl selector:metadataNet.selector selectorPost:metadataNet.selectorPost session:metadataNet.session taskStatus:metadataNet.taskStatus delegate:app.activeMain];
  1051. } else
  1052. break;
  1053. counterDownloadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  1054. }
  1055. // ------------------------- <selector Auto Upload> -------------------------
  1056. while (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload) {
  1057. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadWithSelector:selectorUploadAutoUpload];
  1058. if (metadataNet) {
  1059. // Priority Error only in Foreground
  1060. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && metadataNet.priority <= k_priorityAutoUploadError)
  1061. continue;
  1062. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1063. counterNewUpload++;
  1064. } else
  1065. break;
  1066. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1067. }
  1068. // ------------------------- <selector Auto Upload All> ----------------------
  1069. // Verify num error MAX 10 after STOP
  1070. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND sessionSelector = %@ AND sessionTaskIdentifier = %i", _activeAccount, selectorUploadAutoUploadAll, k_taskIdentifierError] sorted:nil ascending:NO];
  1071. NSInteger errorCount = [metadatas count];
  1072. if (errorCount >= 10) {
  1073. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1074. } else {
  1075. while (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload) {
  1076. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadWithSelector:selectorUploadAutoUploadAll];
  1077. if (metadataNet) {
  1078. // Priority Error only in Foreground
  1079. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && metadataNet.priority <= k_priorityAutoUploadError)
  1080. continue;
  1081. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1082. counterNewUpload++;
  1083. } else
  1084. break;
  1085. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1086. }
  1087. }
  1088. // ------------------------- <selector Upload File> -------------------------
  1089. while (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload) {
  1090. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadWithSelector:selectorUploadFile];
  1091. if (metadataNet) {
  1092. // Priority Error only in Foreground
  1093. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && metadataNet.priority <= k_priorityAutoUploadError)
  1094. continue;
  1095. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1096. counterNewUpload++;
  1097. } else
  1098. break;
  1099. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1100. }
  1101. // Verify Lock
  1102. NSInteger counterUploadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count];
  1103. NSArray *tableMetadatasInLock = [[NCManageDatabase sharedInstance] getLockQueueUpload];
  1104. if (counterNewUpload == 0 && counterUploadInSession == 0 && [tableMetadatasInLock count] > 0) {
  1105. // Unlock
  1106. for (tableMetadata *metadata in tableMetadatasInLock) {
  1107. if ([[NCManageDatabase sharedInstance] isTableInvalidated:metadata] == NO)
  1108. [[NCManageDatabase sharedInstance] unlockQueueUploadWithAssetLocalIdentifier:metadata.assetLocalIdentifier];
  1109. }
  1110. }
  1111. // In background verify Upload in error
  1112. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1113. [[CCNetworking sharedNetworking] verifyUploadInErrorOrWait];
  1114. }
  1115. // Start Timer
  1116. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:app selector:@selector(processAutoDownloadUpload) userInfo:nil repeats:YES];
  1117. }
  1118. #pragma --------------------------------------------------------------------------------------------
  1119. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1120. #pragma --------------------------------------------------------------------------------------------
  1121. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1122. {
  1123. return YES;
  1124. }
  1125. // Method called from iOS system to send a file from other app.
  1126. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1127. {
  1128. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1129. NSLog(@"[LOG] the path is: %@", url.path);
  1130. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1131. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1132. if (self.activeAccount) {
  1133. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1134. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1135. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1136. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1137. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1138. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1139. });
  1140. }
  1141. // remove from InBox
  1142. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1143. return YES;
  1144. }
  1145. #pragma --------------------------------------------------------------------------------------------
  1146. #pragma mark ===== Crashlytics =====
  1147. #pragma --------------------------------------------------------------------------------------------
  1148. - (void) logUser
  1149. {
  1150. if (self.activeAccount.length > 0)
  1151. [CrashlyticsKit setUserName:self.activeAccount];
  1152. }
  1153. #pragma --------------------------------------------------------------------------------------------
  1154. #pragma mark ===== Maintenance Mode =====
  1155. #pragma --------------------------------------------------------------------------------------------
  1156. - (void)maintenanceMode:(BOOL)mode
  1157. {
  1158. self.maintenanceMode = mode;
  1159. }
  1160. #pragma --------------------------------------------------------------------------------------------
  1161. #pragma mark ===== UPGRADE =====
  1162. #pragma --------------------------------------------------------------------------------------------
  1163. - (BOOL)upgrade
  1164. {
  1165. #ifdef DEBUG
  1166. //self.maintenanceMode = YES;
  1167. #endif
  1168. NSString *actualVersion = [CCUtility getVersion];
  1169. NSString *actualBuild = [CCUtility getBuild];
  1170. /* ---------------------- UPGRADE VERSION ----------------------- */
  1171. // VERSION < 2.17.6
  1172. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1173. // Remove All old Photo Library
  1174. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1175. }
  1176. // VERSION == 2.17.6
  1177. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1178. // Build < 10
  1179. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1180. // Remove All old Photo Library
  1181. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1182. }
  1183. }
  1184. return YES;
  1185. }
  1186. @end