AppDelegate.m 67 KB

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