AppDelegate.m 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621
  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 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. if ([NCBrandOptions sharedInstance].use_login_web) {
  271. if (!_activeLoginWeb.isViewLoaded || !_activeLoginWeb.view.window) {
  272. _activeLoginWeb = [CCLoginWeb new];
  273. _activeLoginWeb.delegate = delegate;
  274. _activeLoginWeb.loginType = loginType;
  275. dispatch_async(dispatch_get_main_queue(), ^ {
  276. [_activeLoginWeb presentModalWithDefaultTheme:delegate];
  277. });
  278. }
  279. } else {
  280. if (!_activeLogin.isViewLoaded || !_activeLogin.view.window) {
  281. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  282. _activeLogin.delegate = delegate;
  283. _activeLogin.loginType = loginType;
  284. dispatch_async(dispatch_get_main_queue(), ^ {
  285. [self.window makeKeyAndVisible];
  286. [self.window.rootViewController presentViewController:_activeLogin animated:YES completion:nil];
  287. });
  288. }
  289. }
  290. }
  291. #pragma --------------------------------------------------------------------------------------------
  292. #pragma mark ===== Setting Active Account for all APP =====
  293. #pragma --------------------------------------------------------------------------------------------
  294. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activePassword:(NSString *)activePassword
  295. {
  296. self.activeAccount = activeAccount;
  297. self.activeUrl = activeUrl;
  298. self.activeUser = activeUser;
  299. self.activePassword = activePassword;
  300. self.directoryUser = [CCUtility getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  301. // Setting Account to CCNetworking
  302. [[CCNetworking sharedNetworking] settingAccount];
  303. }
  304. #pragma --------------------------------------------------------------------------------------------
  305. #pragma mark ===== Push Notification =====
  306. #pragma --------------------------------------------------------------------------------------------
  307. - (void)subscribingNextcloudServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  308. {
  309. NSLog(@"[LOG] Error Subscribing Nextcloud Server %@", message);
  310. }
  311. - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
  312. {
  313. [application registerForRemoteNotifications];
  314. }
  315. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  316. {
  317. // test
  318. if (self.activeAccount.length == 0)
  319. return;
  320. // FIREBASE registered token
  321. [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
  322. NSString *pushToken = [[FIRInstanceID instanceID] token];
  323. // NSString *pushToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
  324. NSString *pushTokenHash = [[NCClientEncryption sharedManager] createSHA512:pushToken];
  325. NSDictionary *devicePushKey = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DevicePushKey-Info" ofType:@"plist"]];
  326. #ifdef DEBUG
  327. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyDevelopment"];
  328. #else
  329. NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyProduction"];
  330. #endif
  331. if ([devicePublicKey length] > 0 && [pushTokenHash length] > 0) {
  332. NSLog(@"[LOG] Firebase InstanceID push token: %@", pushToken);
  333. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  334. NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:pushToken, @"pushToken", pushTokenHash, @"pushTokenHash", devicePublicKey, @"devicePublicKey", nil];
  335. metadataNet.action = actionSubscribingNextcloudServer;
  336. metadataNet.options = options;
  337. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  338. }
  339. }
  340. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  341. {
  342. NSLog(@"[LOG] Error register remote notification %@", error);
  343. }
  344. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  345. UIApplicationState state = [application applicationState];
  346. if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
  347. NSLog(@"[LOG] Receive Notification on Inactive or Background state");
  348. } else {
  349. NSLog(@"[LOG] Receive Notification on Active state");
  350. }
  351. // If you are receiving a notification message while your app is in the background,
  352. // this callback will not be fired till the user taps on the notification launching the application.
  353. // TODO: Handle data of notification
  354. // Print message ID.
  355. //if (userInfo[kGCMMessageIDKey]) {
  356. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  357. //}
  358. // Print full message.
  359. NSLog(@"[LOG] %@", userInfo);
  360. }
  361. - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  362. {
  363. UIApplicationState state = [application applicationState];
  364. // Print message ID.
  365. //if (userInfo[kGCMMessageIDKey]) {
  366. // NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  367. //}
  368. // Print full message.
  369. NSLog(@"[LOG] %@", userInfo);
  370. if (state == UIApplicationStateBackground || (state == UIApplicationStateInactive)) {
  371. } else if (state == UIApplicationStateInactive) {
  372. // user tapped notification
  373. completionHandler(UIBackgroundFetchResultNewData);
  374. } else {
  375. // app is active
  376. completionHandler(UIBackgroundFetchResultNoData);
  377. }
  378. }
  379. #pragma FIREBASE
  380. - (void)tokenRefreshNotification:(NSNotification *)notification {
  381. // Note that this callback will be fired everytime a new token is generated, including the first
  382. // time. So if you need to retrieve the token as soon as it is available this is where that
  383. // should be done.
  384. NSString *refreshedToken = [[FIRInstanceID instanceID] token];
  385. NSLog(@"[LOG] InstanceID token: %@", refreshedToken);
  386. // Connect to FCM since connection may have failed when attempted before having a token.
  387. [self connectToFcm];
  388. // TODO: If necessary send token to application server.
  389. }
  390. - (void)connectToFcm {
  391. // Won't connect since there is no token
  392. if (![[FIRInstanceID instanceID] token]) {
  393. return;
  394. }
  395. // Disconnect previous FCM connection if it exists.
  396. [[FIRMessaging messaging] disconnect];
  397. [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
  398. if (error != nil) {
  399. NSLog(@"[LOG] Unable to connect to FCM. %@", error);
  400. } else {
  401. NSLog(@"[LOG] Connected to FCM.");
  402. }
  403. }];
  404. }
  405. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  406. // Receive data message on iOS 10 devices while app is in the foreground.
  407. - (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  408. // Print full message
  409. NSLog(@"[LOG] %@", remoteMessage.appData);
  410. }
  411. #endif
  412. #pragma --------------------------------------------------------------------------------------------
  413. #pragma mark ===== Quick Actions - ShotcutItem =====
  414. #pragma --------------------------------------------------------------------------------------------
  415. - (void)configDynamicShortcutItems
  416. {
  417. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  418. UIApplicationShortcutIcon *shortcutPhotosIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionPhotos"];
  419. UIApplicationShortcutIcon *shortcutUploadIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"quickActionUpload"];
  420. UIApplicationShortcutItem *shortcutPhotos = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.photos", bundleId] localizedTitle:NSLocalizedString(@"_photo_camera_", nil) localizedSubtitle:nil icon:shortcutPhotosIcon userInfo:nil];
  421. UIApplicationShortcutItem *shortcutUpload = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.upload", bundleId] localizedTitle:NSLocalizedString(@"_upload_file_", nil) localizedSubtitle:nil icon:shortcutUploadIcon userInfo:nil];
  422. // add the array to our app
  423. if (shortcutUpload && shortcutPhotos)
  424. [UIApplication sharedApplication].shortcutItems = @[shortcutUpload, shortcutPhotos];
  425. }
  426. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  427. {
  428. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  429. completionHandler(handledShortCutItem);
  430. }
  431. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  432. {
  433. BOOL handled = NO;
  434. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  435. NSString *shortcutPhotos = [NSString stringWithFormat:@"%@.photos", bundleId];
  436. NSString *shortcutUpload = [NSString stringWithFormat:@"%@.upload", bundleId];
  437. NSString *shortcutUploadEncrypted = [NSString stringWithFormat:@"%@.uploadEncrypted", bundleId];
  438. if ([shortcutItem.type isEqualToString:shortcutUpload] && self.activeAccount) {
  439. dispatch_async(dispatch_get_main_queue(), ^{
  440. if (_activeMain) {
  441. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  442. if (splitViewController.isCollapsed) {
  443. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  444. for (UINavigationController *nvc in tbc.viewControllers) {
  445. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  446. [nvc popToRootViewControllerAnimated:NO];
  447. }
  448. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  449. } else {
  450. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  451. [nvcDetail popToRootViewControllerAnimated:NO];
  452. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  453. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  454. }
  455. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  456. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  457. [[CCQuickActions quickActionsManager] startQuickActionsViewController:_activeMain];
  458. });
  459. }
  460. });
  461. handled = YES;
  462. }
  463. else if ([shortcutItem.type isEqualToString:shortcutUploadEncrypted] && self.activeAccount) {
  464. dispatch_async(dispatch_get_main_queue(), ^{
  465. if (_activeMain) {
  466. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  467. if (splitViewController.isCollapsed) {
  468. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  469. for (UINavigationController *nvc in tbc.viewControllers) {
  470. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  471. [nvc popToRootViewControllerAnimated:NO];
  472. }
  473. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  474. } else {
  475. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  476. [nvcDetail popToRootViewControllerAnimated:NO];
  477. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  478. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  479. }
  480. [_activeMain.navigationController popToRootViewControllerAnimated:NO];
  481. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  482. [[CCQuickActions quickActionsManager] startQuickActionsViewController:_activeMain];
  483. });
  484. }
  485. });
  486. handled = YES;
  487. }
  488. else if ([shortcutItem.type isEqualToString:shortcutPhotos] && self.activeAccount) {
  489. dispatch_async(dispatch_get_main_queue(), ^{
  490. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  491. if (splitViewController.isCollapsed) {
  492. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  493. for (UINavigationController *nvc in tbc.viewControllers) {
  494. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  495. [nvc popToRootViewControllerAnimated:NO];
  496. }
  497. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  498. } else {
  499. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  500. [nvcDetail popToRootViewControllerAnimated:NO];
  501. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  502. [tbc setSelectedIndex: k_tabBarApplicationIndexPhotos];
  503. }
  504. });
  505. handled = YES;
  506. }
  507. return handled;
  508. }
  509. #pragma --------------------------------------------------------------------------------------------
  510. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  511. #pragma --------------------------------------------------------------------------------------------
  512. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  513. {
  514. static NSInteger errorCodePrev = 0;
  515. dispatch_async(dispatch_get_main_queue(), ^{
  516. if (visible) {
  517. if (errorcode == kCFURLErrorNotConnectedToInternet || errorcode == k_CCErrorNetworkNowAvailable) {
  518. if (errorCodePrev != errorcode)
  519. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  520. errorCodePrev = errorcode;
  521. } else {
  522. if (description.length > 0) {
  523. [TWMessageBarManager sharedInstance].styleSheet = self;
  524. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  525. }
  526. }
  527. } else {
  528. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  529. }
  530. });
  531. }
  532. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  533. {
  534. UIColor *backgroundColor = nil;
  535. switch (type)
  536. {
  537. case TWMessageBarMessageTypeError:
  538. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  539. break;
  540. case TWMessageBarMessageTypeSuccess:
  541. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  542. break;
  543. case TWMessageBarMessageTypeInfo:
  544. backgroundColor = [NCBrandColor sharedInstance].brand;
  545. break;
  546. default:
  547. break;
  548. }
  549. return backgroundColor;
  550. }
  551. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  552. {
  553. UIColor *strokeColor = nil;
  554. switch (type)
  555. {
  556. case TWMessageBarMessageTypeError:
  557. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  558. break;
  559. case TWMessageBarMessageTypeSuccess:
  560. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  561. break;
  562. case TWMessageBarMessageTypeInfo:
  563. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  564. break;
  565. default:
  566. break;
  567. }
  568. return strokeColor;
  569. }
  570. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  571. {
  572. UIImage *iconImage = nil;
  573. switch (type)
  574. {
  575. case TWMessageBarMessageTypeError:
  576. iconImage = [UIImage imageNamed:@"icon-error.png"];
  577. break;
  578. case TWMessageBarMessageTypeSuccess:
  579. iconImage = [UIImage imageNamed:@"icon-success.png"];
  580. break;
  581. case TWMessageBarMessageTypeInfo:
  582. iconImage = [UIImage imageNamed:@"icon-info.png"];
  583. break;
  584. default:
  585. break;
  586. }
  587. return iconImage;
  588. }
  589. - (void)updateApplicationIconBadgeNumber
  590. {
  591. // Test Maintenance
  592. if (self.maintenanceMode)
  593. return;
  594. NSInteger queueDownload = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  595. NSInteger queueUpload = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count];
  596. // Total
  597. NSInteger total = queueDownload + queueUpload + [[NCManageDatabase sharedInstance] countQueueDownloadWithSession:nil] + [[NCManageDatabase sharedInstance] countQueueUploadWithSession:nil];
  598. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  599. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  600. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  601. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  602. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  603. if (total > 0) {
  604. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  605. } else {
  606. [tbItem setBadgeValue:nil];
  607. NSDictionary* userInfo = @{@"fileID": @"", @"serverUrl": @"", @"progress": [NSNumber numberWithFloat:0]};
  608. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  609. }
  610. }
  611. }
  612. #pragma --------------------------------------------------------------------------------------------
  613. #pragma mark ===== TabBarController =====
  614. #pragma --------------------------------------------------------------------------------------------
  615. - (void)createTabBarController
  616. {
  617. UITabBarItem *item;
  618. NSLayoutConstraint *constraint;
  619. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  620. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  621. [app aspectTabBar:tabBarController.tabBar hidden:NO];
  622. // File
  623. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  624. [item setTitle:NSLocalizedString(@"_home_", nil)];
  625. item.image = [UIImage imageNamed:@"tabBarFiles"];
  626. item.selectedImage = [UIImage imageNamed:@"tabBarFiles"];
  627. // Favorites
  628. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  629. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  630. item.image = [UIImage imageNamed:@"tabBarFavorite"];
  631. item.selectedImage = [UIImage imageNamed:@"tabBarFavorite"];
  632. // (PLUS)
  633. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  634. item.title = nil;
  635. item.image = nil;
  636. item.enabled = false;
  637. // Photos
  638. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPhotos];
  639. [item setTitle:NSLocalizedString(@"_photo_camera_", nil)];
  640. item.image = [UIImage imageNamed:@"tabBarPhotos"];
  641. item.selectedImage = [UIImage imageNamed:@"tabBarPhotos"];
  642. // More
  643. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  644. [item setTitle:NSLocalizedString(@"_more_", nil)];
  645. item.image = [UIImage imageNamed:@"tabBarMore"];
  646. item.selectedImage = [UIImage imageNamed:@"tabBarMore"];
  647. // Plus Button
  648. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brand];
  649. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  650. buttonPlus.tag = 99;
  651. buttonPlus.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
  652. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  653. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  654. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  655. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  656. [tabBarController.tabBar addSubview:buttonPlus];
  657. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  658. [tabBarController.view addConstraint:constraint];
  659. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:5];
  660. [tabBarController.view addConstraint:constraint];
  661. }
  662. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav online:(BOOL)online hidden:(BOOL)hidden
  663. {
  664. nav.translucent = NO;
  665. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  666. nav.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  667. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].navigationBarText}];
  668. if (!online)
  669. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  670. nav.hidden = hidden;
  671. [nav setAlpha:1];
  672. }
  673. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  674. {
  675. tab.translucent = NO;
  676. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  677. tab.tintColor = [NCBrandColor sharedInstance].brand;
  678. tab.hidden = hidden;
  679. [tab setAlpha:1];
  680. }
  681. - (void)plusButtonVisibile:(BOOL)visible
  682. {
  683. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  684. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  685. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  686. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:[NCBrandColor sharedInstance].brand];
  687. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  688. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  689. if (buttonPlus) {
  690. if (visible) {
  691. buttonPlus.hidden = false;
  692. } else {
  693. buttonPlus.hidden = true;
  694. }
  695. }
  696. }
  697. - (void)handleTouchTabbarCenter:(id)sender
  698. {
  699. // Test Maintenance
  700. if (self.maintenanceMode)
  701. return;
  702. UIView *view = [[(UIButton *)sender superview] superview];
  703. CreateMenuAdd *menuAdd = [[CreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brand];
  704. if ([CCUtility getCreateMenuEncrypted])
  705. [menuAdd createMenuEncryptedWithView:view];
  706. else
  707. [menuAdd createMenuPlainWithView:view];
  708. }
  709. - (void)selectedTabBarController:(NSInteger)index
  710. {
  711. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  712. if (splitViewController.isCollapsed) {
  713. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  714. for (UINavigationController *nvc in tbc.viewControllers) {
  715. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  716. [nvc popToRootViewControllerAnimated:NO];
  717. }
  718. [tbc setSelectedIndex: index];
  719. } else {
  720. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  721. [nvcDetail popToRootViewControllerAnimated:NO];
  722. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  723. [tbc setSelectedIndex: index];
  724. }
  725. }
  726. - (NSString *)getTabBarControllerActiveServerUrl
  727. {
  728. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  729. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  730. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  731. NSInteger index = tabBarController.selectedIndex;
  732. // select active serverUrl
  733. if (index == k_tabBarApplicationIndexFile) {
  734. serverUrl = app.activeMain.serverUrl;
  735. } else if (index == k_tabBarApplicationIndexFavorite) {
  736. if (app.activeFavorites.serverUrl)
  737. serverUrl = app.activeFavorites.serverUrl;
  738. } else if (index == k_tabBarApplicationIndexPhotos) {
  739. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  740. }
  741. return serverUrl;
  742. }
  743. #pragma --------------------------------------------------------------------------------------------
  744. #pragma mark ===== Theming Color =====
  745. #pragma --------------------------------------------------------------------------------------------
  746. - (void)settingThemingColorBrand
  747. {
  748. UIColor* newColor;
  749. if (self.activeAccount.length > 0) {
  750. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilites];
  751. if ([NCBrandOptions sharedInstance].use_themingColor && capabilities.themingColor.length == 7) {
  752. BOOL isLight = [CCGraphics isLight:[CCGraphics colorFromHexString:capabilities.themingColor]];
  753. if (isLight) {
  754. // Activity
  755. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Server Theming" note:NSLocalizedString(@"_theming_is_light_", nil) type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:_activeUrl];
  756. newColor = [NCBrandColor sharedInstance].customer;
  757. } else {
  758. newColor = [CCGraphics colorFromHexString:capabilities.themingColor];
  759. }
  760. } else {
  761. newColor = [NCBrandColor sharedInstance].customer;
  762. }
  763. } else {
  764. newColor = [NCBrandColor sharedInstance].customer;
  765. }
  766. if (self.activeAccount.length > 0 && ![newColor isEqual:[NCBrandColor sharedInstance].brand] && newColor) {
  767. [NCBrandColor sharedInstance].brand = newColor;
  768. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  769. }
  770. }
  771. - (void)changeTheming:(UIViewController *)vc
  772. {
  773. UIColor *color = [NCBrandColor sharedInstance].brand;
  774. // Change Navigation & TabBar color
  775. vc.navigationController.navigationBar.barTintColor = color;
  776. vc.tabBarController.tabBar.tintColor = color;
  777. // Change button Plus
  778. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  779. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  780. UIButton *button = [tabBarController.view viewWithTag:99];
  781. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] color:color];
  782. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  783. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  784. // Tint Color GLOBAL WINDOW
  785. [self.window setTintColor:[NCBrandColor sharedInstance].brand];
  786. }
  787. #pragma --------------------------------------------------------------------------------------------
  788. #pragma mark ===== Manager Passcode =====
  789. #pragma --------------------------------------------------------------------------------------------
  790. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  791. {
  792. // ServerUrl active
  793. NSString *serverUrl = self.activeMain.serverUrl;
  794. BOOL isBlockZone = false;
  795. // fermiamo la data della sessione
  796. self.sessionePasscodeLock = nil;
  797. // se il block code è a zero esci con NON attivare la richiesta password
  798. if ([[CCUtility getBlockCode] length] == 0) return NO;
  799. // se non c'è attivo un account esci con NON attivare la richiesta password
  800. if ([self.activeAccount length] == 0) return NO;
  801. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  802. if (serverUrl && _activeUrl) {
  803. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  804. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", self.activeAccount, serverUrl]];
  805. if (directory.lock) {
  806. isBlockZone = true;
  807. break;
  808. } else {
  809. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  810. if (serverUrl == self.activeUrl)
  811. break;
  812. }
  813. }
  814. }
  815. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  816. return YES;
  817. }
  818. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  819. {
  820. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  821. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  822. viewController.delegate = self;
  823. viewController.title = [NCBrandOptions sharedInstance].brand;
  824. viewController.fromType = CCBKPasscodeFromLockScreen;
  825. viewController.inputViewTitlePassword = YES;
  826. if ([CCUtility getSimplyBlockCode]) {
  827. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  828. viewController.passcodeInputView.maximumLength = 6;
  829. } else {
  830. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  831. viewController.passcodeInputView.maximumLength = 64;
  832. }
  833. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  834. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  835. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  836. return navigationController;
  837. }
  838. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  839. {
  840. [aViewController dismissViewControllerAnimated:YES completion:nil];
  841. // is a lock screen
  842. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  843. [aViewController dismissViewControllerAnimated:YES completion:nil];
  844. // start session Passcode Lock
  845. BOOL isBlockZone = false;
  846. NSString *serverUrl = self.activeMain.serverUrl;
  847. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  848. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", self.activeAccount, serverUrl]];
  849. if (directory.lock) {
  850. isBlockZone = true;
  851. break;
  852. } else {
  853. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  854. if (serverUrl == self.activeUrl)
  855. break;
  856. }
  857. }
  858. if (isBlockZone)
  859. self.sessionePasscodeLock = [NSDate date];
  860. }
  861. }
  862. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  863. {
  864. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  865. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  866. //self.lockUntilDate = nil;
  867. //self.failedAttempts = 0;
  868. aResultHandler(YES);
  869. } else aResultHandler(NO);
  870. } else aResultHandler(YES);
  871. }
  872. #pragma --------------------------------------------------------------------------------------------
  873. #pragma mark ===== reachabilityChanged =====
  874. #pragma --------------------------------------------------------------------------------------------
  875. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  876. {
  877. if ([self.reachability isReachable]) {
  878. if (self.lastReachability == NO) {
  879. [self messageNotification:@"_network_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:k_CCErrorNetworkNowAvailable];
  880. if (_activeMain)
  881. [_activeMain performSelector:@selector(requestServerCapabilities) withObject:nil afterDelay:3];
  882. }
  883. NSLog(@"[LOG] Reachability Changed: Reachable");
  884. self.lastReachability = YES;
  885. } else {
  886. if (self.lastReachability == YES) {
  887. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  888. }
  889. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  890. self.lastReachability = NO;
  891. }
  892. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  893. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  894. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  895. }
  896. #pragma --------------------------------------------------------------------------------------------
  897. #pragma mark ===== Fetch =====
  898. #pragma --------------------------------------------------------------------------------------------
  899. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  900. {
  901. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  902. // Verify new photo
  903. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  904. // after 20 sec
  905. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  906. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", self.activeAccount] sorted:nil ascending:NO];
  907. if ([records count] > 0) {
  908. completionHandler(UIBackgroundFetchResultNewData);
  909. } else {
  910. completionHandler(UIBackgroundFetchResultNoData);
  911. }
  912. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  913. });
  914. }
  915. #pragma --------------------------------------------------------------------------------------------
  916. #pragma mark ===== Operation Networking & Session =====
  917. #pragma --------------------------------------------------------------------------------------------
  918. //
  919. // Method called by the system when all the background task has end
  920. //
  921. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  922. {
  923. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  924. // after 20 sec
  925. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  926. self.backgroundSessionCompletionHandler = completionHandler;
  927. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  928. self.backgroundSessionCompletionHandler = nil;
  929. completionHandler();
  930. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  931. });
  932. }
  933. - (void)addNetworkingOperationQueue:(NSOperationQueue *)netQueue delegate:(id)delegate metadataNet:(CCMetadataNet *)metadataNet
  934. {
  935. id operation;
  936. operation = [[OCnetworking alloc] initWithDelegate:delegate metadataNet:metadataNet withUser:_activeUser withPassword:_activePassword withUrl:_activeUrl];
  937. [operation setQueuePriority:metadataNet.priority];
  938. [netQueue addOperation:operation];
  939. }
  940. // Notification change session
  941. - (void)sessionChanged:(NSNotification *)notification
  942. {
  943. NSURLSession *session;
  944. NSString *fileID;
  945. NSURLSessionTask *task;
  946. for (id object in notification.object) {
  947. if ([object isKindOfClass:[NSURLSession class]])
  948. session = object;
  949. if ([object isKindOfClass:[NSString class]])
  950. fileID = object;
  951. if ([object isKindOfClass:[NSURLSessionTask class]])
  952. task = object;
  953. }
  954. /*
  955. Task
  956. */
  957. if (fileID && [_listChangeTask objectForKey:fileID])
  958. dispatch_async(dispatch_get_main_queue(), ^{
  959. [self changeTask:fileID];
  960. });
  961. /*
  962. Session
  963. */
  964. if (session) {
  965. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  966. unsigned long numDownload = [downloadTasks count];
  967. unsigned long numUpload = [uploadTasks count];
  968. NSLog(@"[LOG] Num Download in queue %lu, num upload in queue %lu", numDownload, numUpload);
  969. }];
  970. }
  971. }
  972. - (void)changeTask:(NSString *)fileID
  973. {
  974. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  975. if (!metadata) return;
  976. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  977. if (!serverUrl) return;
  978. if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"stopUpload"]) {
  979. [[NCManageDatabase sharedInstance] setMetadataSession:nil sessionError:@"" sessionSelector:nil sessionSelectorPost:nil sessionTaskIdentifier:k_taskIdentifierStop predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  980. }
  981. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"reloadUpload"]) {
  982. // V 1.8 if upload_session_wwan change in upload_session
  983. if ([metadata.session isEqualToString:k_upload_session_wwan])
  984. metadata.session = k_upload_session;
  985. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  986. }
  987. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"reloadDownload"]) {
  988. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  989. [[CCNetworking sharedNetworking] downloadFile:fileID serverUrl:serverUrl selector:metadata.sessionSelector selectorPost:metadata.sessionSelectorPost session:k_download_session taskStatus:k_taskStatusResume delegate:self.activeMain];
  990. });
  991. }
  992. else if ([[_listChangeTask objectForKey:metadata.fileID] isEqualToString:@"cancelUpload"]) {
  993. // remove the file
  994. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  995. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  996. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  997. }
  998. else if ([[_listChangeTask objectForKey:fileID] isEqualToString:@"cancelDownload"]) {
  999. [[NCManageDatabase sharedInstance] setMetadataSession:@"" sessionError:@"" sessionSelector:@"" sessionSelectorPost:@"" sessionTaskIdentifier:k_taskIdentifierDone predicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1000. }
  1001. // remove ChangeTask (fileID) from the list
  1002. [_listChangeTask removeObjectForKey:fileID];
  1003. // delete progress
  1004. [_listProgressMetadata removeObjectForKey:fileID];
  1005. // Progress Task
  1006. NSDictionary* userInfo = @{@"fileID": (fileID), @"serverUrl": (serverUrl), @"cryptated": ([NSNumber numberWithBool:NO]), @"progress": ([NSNumber numberWithFloat:0.0])};
  1007. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"NotificationProgressTask" object:nil userInfo:userInfo];
  1008. // Refresh
  1009. if (_activeMain && [_listChangeTask count] == 0) {
  1010. [_activeMain reloadDatasource:serverUrl];
  1011. }
  1012. }
  1013. #pragma --------------------------------------------------------------------------------------------
  1014. #pragma mark ===== Process Auto Upload < k_timerProcess seconds > =====
  1015. #pragma --------------------------------------------------------------------------------------------
  1016. - (void)processAutoDownloadUpload
  1017. {
  1018. // Test Maintenance
  1019. if (self.maintenanceMode)
  1020. return;
  1021. // BACKGROND & FOREGROUND
  1022. NSLog(@"-PROCESS-AUTO-UPLOAD-");
  1023. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1024. // ONLY BACKGROUND
  1025. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1026. } else {
  1027. // ONLY FOREFROUND
  1028. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1029. }
  1030. }
  1031. - (void)loadAutoDownloadUpload:(NSNumber *)maxConcurrent
  1032. {
  1033. CCMetadataNet *metadataNet;
  1034. // Stop Timer
  1035. [_timerProcessAutoDownloadUpload invalidate];
  1036. NSInteger maxConcurrentDownloadUpload = [maxConcurrent integerValue];
  1037. NSInteger counterDownloadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  1038. NSInteger counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1039. NSInteger counterNewUpload = 0;
  1040. // ------------------------- <selector Auto Download> -------------------------
  1041. while (counterDownloadInSession < maxConcurrentDownloadUpload) {
  1042. metadataNet = [[NCManageDatabase sharedInstance] getQueueDownload];
  1043. if (metadataNet) {
  1044. [[CCNetworking sharedNetworking] downloadFile:metadataNet.fileID serverUrl:metadataNet.serverUrl selector:metadataNet.selector selectorPost:metadataNet.selectorPost session:metadataNet.session taskStatus:metadataNet.taskStatus delegate:app.activeMain];
  1045. } else
  1046. break;
  1047. counterDownloadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataDownload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataDownloadWWan] count];
  1048. }
  1049. // ------------------------- <selector Auto Upload> -------------------------
  1050. while (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload) {
  1051. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadWithSelector:selectorUploadAutoUpload];
  1052. if (metadataNet) {
  1053. // Priority Error only in Foreground
  1054. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && metadataNet.priority <= k_priorityAutoUploadError)
  1055. continue;
  1056. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1057. counterNewUpload++;
  1058. } else
  1059. break;
  1060. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1061. }
  1062. // ------------------------- <selector Auto Upload All> ----------------------
  1063. // Verify num error MAX 10 after STOP
  1064. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND sessionSelector = %@ AND sessionTaskIdentifier = %i", _activeAccount, selectorUploadAutoUploadAll, k_taskIdentifierError] sorted:nil ascending:NO];
  1065. NSInteger errorCount = [metadatas count];
  1066. if (errorCount >= 10) {
  1067. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1068. } else {
  1069. while (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload) {
  1070. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadWithSelector:selectorUploadAutoUploadAll];
  1071. if (metadataNet) {
  1072. // Priority Error only in Foreground
  1073. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && metadataNet.priority <= k_priorityAutoUploadError)
  1074. continue;
  1075. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1076. counterNewUpload++;
  1077. } else
  1078. break;
  1079. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1080. }
  1081. }
  1082. // ------------------------- <selector Upload File> -------------------------
  1083. while (counterUploadInSessionAndInLock < maxConcurrentDownloadUpload) {
  1084. metadataNet = [[NCManageDatabase sharedInstance] getQueueUploadWithSelector:selectorUploadFile];
  1085. if (metadataNet) {
  1086. // Priority Error only in Foreground
  1087. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && metadataNet.priority <= k_priorityAutoUploadError)
  1088. continue;
  1089. [[CCNetworking sharedNetworking] uploadFileFromAssetLocalIdentifier:metadataNet delegate:_activeMain];
  1090. counterNewUpload++;
  1091. } else
  1092. break;
  1093. counterUploadInSessionAndInLock = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count] + [[[NCManageDatabase sharedInstance] getLockQueueUpload] count];
  1094. }
  1095. // Verify Lock
  1096. NSInteger counterUploadInSession = [[[NCManageDatabase sharedInstance] getTableMetadataUpload] count] + [[[NCManageDatabase sharedInstance] getTableMetadataUploadWWan] count];
  1097. NSArray *tableMetadatasInLock = [[NCManageDatabase sharedInstance] getLockQueueUpload];
  1098. if (counterNewUpload == 0 && counterUploadInSession == 0 && [tableMetadatasInLock count] > 0) {
  1099. // Unlock
  1100. for (tableMetadata *metadata in tableMetadatasInLock) {
  1101. if ([[NCManageDatabase sharedInstance] isTableInvalidated:metadata] == NO)
  1102. [[NCManageDatabase sharedInstance] unlockQueueUploadWithAssetLocalIdentifier:metadata.assetLocalIdentifier];
  1103. }
  1104. }
  1105. // In background verify Upload in error
  1106. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1107. [[CCNetworking sharedNetworking] verifyUploadInErrorOrWait];
  1108. }
  1109. // Start Timer
  1110. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:app selector:@selector(processAutoDownloadUpload) userInfo:nil repeats:YES];
  1111. }
  1112. #pragma --------------------------------------------------------------------------------------------
  1113. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1114. #pragma --------------------------------------------------------------------------------------------
  1115. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1116. {
  1117. return YES;
  1118. }
  1119. // Method called from iOS system to send a file from other app.
  1120. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
  1121. {
  1122. NSLog(@"[LOG] URL from %@ application", sourceApplication);
  1123. NSLog(@"[LOG] the path is: %@", url.path);
  1124. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1125. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1126. if (self.activeAccount) {
  1127. [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:self.fileNameUpload] toPath:[NSString stringWithFormat:@"%@/%@", self.directoryUser, self.fileNameUpload] error:nil];
  1128. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1129. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1130. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1131. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1132. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1133. });
  1134. }
  1135. // remove from InBox
  1136. [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] error:nil];
  1137. return YES;
  1138. }
  1139. #pragma --------------------------------------------------------------------------------------------
  1140. #pragma mark ===== Crashlytics =====
  1141. #pragma --------------------------------------------------------------------------------------------
  1142. - (void) logUser
  1143. {
  1144. if (self.activeAccount.length > 0)
  1145. [CrashlyticsKit setUserName:self.activeAccount];
  1146. }
  1147. #pragma --------------------------------------------------------------------------------------------
  1148. #pragma mark ===== Maintenance Mode =====
  1149. #pragma --------------------------------------------------------------------------------------------
  1150. - (void)maintenanceMode:(BOOL)mode
  1151. {
  1152. self.maintenanceMode = mode;
  1153. }
  1154. #pragma --------------------------------------------------------------------------------------------
  1155. #pragma mark ===== UPGRADE =====
  1156. #pragma --------------------------------------------------------------------------------------------
  1157. - (BOOL)upgrade
  1158. {
  1159. #ifdef DEBUG
  1160. //self.maintenanceMode = YES;
  1161. #endif
  1162. NSString *actualVersion = [CCUtility getVersion];
  1163. NSString *actualBuild = [CCUtility getBuild];
  1164. /* ---------------------- UPGRADE VERSION ----------------------- */
  1165. // VERSION < 2.17.6
  1166. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1167. // Remove All old Photo Library
  1168. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1169. }
  1170. // VERSION == 2.17.6
  1171. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1172. // Build < 10
  1173. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1174. // Remove All old Photo Library
  1175. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1176. }
  1177. }
  1178. return YES;
  1179. }
  1180. @end