AppDelegate.m 69 KB

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