AppDelegate.m 69 KB

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