AppDelegate.m 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  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. NSString *token = [CCUtility getPushNotificationToken:self.activeAccount];
  422. if (![token isEqualToString:fcmToken]) {
  423. if (token != nil) {
  424. // unsubscribing + subscribing
  425. [self unsubscribingNextcloudServerPushNotification:self.activeAccount url:self.activeUrl token:fcmToken];
  426. } else {
  427. [self subscribingNextcloudServerPushNotification:self.activeAccount url:self.activeUrl token:fcmToken];
  428. }
  429. }
  430. }
  431. #pragma --------------------------------------------------------------------------------------------
  432. #pragma mark ===== Quick Actions - ShotcutItem =====
  433. #pragma --------------------------------------------------------------------------------------------
  434. - (void)configDynamicShortcutItems
  435. {
  436. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  437. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  438. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  439. // add the array to our app
  440. if (shortcutMedia)
  441. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  442. }
  443. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  444. {
  445. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  446. completionHandler(handledShortCutItem);
  447. }
  448. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  449. {
  450. BOOL handled = NO;
  451. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  452. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  453. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  454. dispatch_async(dispatch_get_main_queue(), ^{
  455. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  456. if (splitViewController.isCollapsed) {
  457. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  458. for (UINavigationController *nvc in tbc.viewControllers) {
  459. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  460. [nvc popToRootViewControllerAnimated:NO];
  461. }
  462. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  463. } else {
  464. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  465. [nvcDetail popToRootViewControllerAnimated:NO];
  466. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  467. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  468. }
  469. });
  470. handled = YES;
  471. }
  472. return handled;
  473. }
  474. #pragma --------------------------------------------------------------------------------------------
  475. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  476. #pragma --------------------------------------------------------------------------------------------
  477. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  478. {
  479. static NSInteger errorCodePrev = 0;
  480. dispatch_async(dispatch_get_main_queue(), ^{
  481. if (visible) {
  482. switch (errorcode) {
  483. // JDStatusBarNotification
  484. case kCFURLErrorNotConnectedToInternet :
  485. if (errorCodePrev != errorcode)
  486. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  487. errorCodePrev = errorcode;
  488. break;
  489. // TWMessageBarManager
  490. default:
  491. if (description.length > 0) {
  492. [TWMessageBarManager sharedInstance].styleSheet = self;
  493. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  494. }
  495. break;
  496. }
  497. } else {
  498. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  499. }
  500. });
  501. }
  502. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  503. {
  504. UIColor *backgroundColor = nil;
  505. switch (type)
  506. {
  507. case TWMessageBarMessageTypeError:
  508. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  509. break;
  510. case TWMessageBarMessageTypeSuccess:
  511. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  512. break;
  513. case TWMessageBarMessageTypeInfo:
  514. backgroundColor = [NCBrandColor sharedInstance].brand;
  515. break;
  516. default:
  517. break;
  518. }
  519. return backgroundColor;
  520. }
  521. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  522. {
  523. UIColor *strokeColor = nil;
  524. switch (type)
  525. {
  526. case TWMessageBarMessageTypeError:
  527. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  528. break;
  529. case TWMessageBarMessageTypeSuccess:
  530. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  531. break;
  532. case TWMessageBarMessageTypeInfo:
  533. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  534. break;
  535. default:
  536. break;
  537. }
  538. return strokeColor;
  539. }
  540. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  541. {
  542. UIImage *iconImage = nil;
  543. switch (type)
  544. {
  545. case TWMessageBarMessageTypeError:
  546. iconImage = [UIImage imageNamed:@"icon-error.png"];
  547. break;
  548. case TWMessageBarMessageTypeSuccess:
  549. iconImage = [UIImage imageNamed:@"icon-success.png"];
  550. break;
  551. case TWMessageBarMessageTypeInfo:
  552. iconImage = [UIImage imageNamed:@"icon-info.png"];
  553. break;
  554. default:
  555. break;
  556. }
  557. return iconImage;
  558. }
  559. - (void)updateApplicationIconBadgeNumber
  560. {
  561. if (self.activeAccount.length == 0 || self.maintenanceMode)
  562. return;
  563. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  564. 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];
  565. 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];
  566. NSInteger total = counterDownload + counterUpload;
  567. dispatch_async(dispatch_get_main_queue(), ^{
  568. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  569. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  570. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  571. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  572. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  573. if (total > 0) {
  574. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  575. } else {
  576. [tbItem setBadgeValue:nil];
  577. }
  578. }
  579. });
  580. });
  581. }
  582. #pragma --------------------------------------------------------------------------------------------
  583. #pragma mark ===== TabBarController =====
  584. #pragma --------------------------------------------------------------------------------------------
  585. - (void)createTabBarController:(UITabBarController *)tabBarController
  586. {
  587. UITabBarItem *item;
  588. NSLayoutConstraint *constraint;
  589. CGFloat multiplier = 0;
  590. CGFloat safeAreaBottom = 0;
  591. if (@available(iOS 11, *)) {
  592. UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  593. if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
  594. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.right/2;
  595. if (safeAreaBottom > 0) safeAreaBottom -= 5;
  596. } else {
  597. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom/2;
  598. }
  599. }
  600. [self aspectTabBar:tabBarController.tabBar hidden:NO];
  601. // File
  602. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  603. [item setTitle:NSLocalizedString(@"_home_", nil)];
  604. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  605. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  606. // Favorites
  607. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  608. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  609. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  610. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  611. // (PLUS)
  612. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  613. item.title = @"";
  614. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[UIColor clearColor]];
  615. item.enabled = false;
  616. // Media
  617. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  618. [item setTitle:NSLocalizedString(@"_media_", nil)];
  619. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  620. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  621. // More
  622. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  623. [item setTitle:NSLocalizedString(@"_more_", nil)];
  624. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  625. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  626. // Plus Button
  627. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  628. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  629. buttonPlus.tag = 99;
  630. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  631. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  632. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  633. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  634. [tabBarController.tabBar addSubview:buttonPlus];
  635. multiplier = 1.0;
  636. // X
  637. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:multiplier constant:0];
  638. [tabBarController.view addConstraint:constraint];
  639. // Y
  640. if (safeAreaBottom == 0) {
  641. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:multiplier constant:0];
  642. } else {
  643. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:5];
  644. }
  645. [tabBarController.view addConstraint:constraint];
  646. multiplier = 0.8 * (tabBarController.tabBar.frame.size.height - safeAreaBottom) / tabBarController.tabBar.frame.size.height;
  647. // Width
  648. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  649. [tabBarController.view addConstraint:constraint];
  650. // Height
  651. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  652. [tabBarController.view addConstraint:constraint];
  653. }
  654. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav online:(BOOL)online hidden:(BOOL)hidden
  655. {
  656. nav.translucent = NO;
  657. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  658. nav.tintColor = [NCBrandColor sharedInstance].brandText;
  659. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].brandText}];
  660. // Change bar bottom line shadow
  661. nav.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  662. if (!online)
  663. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  664. nav.hidden = hidden;
  665. [nav setAlpha:1];
  666. }
  667. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  668. {
  669. tab.translucent = NO;
  670. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  671. tab.tintColor = [NCBrandColor sharedInstance].brandElement;
  672. tab.hidden = hidden;
  673. [tab setAlpha:1];
  674. }
  675. - (void)plusButtonVisibile:(BOOL)visible
  676. {
  677. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  678. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  679. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  680. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  681. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  682. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  683. if (buttonPlus) {
  684. if (visible) {
  685. buttonPlus.hidden = false;
  686. } else {
  687. buttonPlus.hidden = true;
  688. }
  689. }
  690. }
  691. - (void)handleTouchTabbarCenter:(id)sender
  692. {
  693. // Test Maintenance
  694. if (self.maintenanceMode)
  695. return;
  696. UIView *view = [(UIButton *)sender superview];
  697. NCCreateMenuAdd *menuAdd = [[NCCreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brandElement];
  698. [menuAdd createMenuWithViewController:self.window.rootViewController view:view];
  699. }
  700. - (void)selectedTabBarController:(NSInteger)index
  701. {
  702. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  703. if (splitViewController.isCollapsed) {
  704. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  705. for (UINavigationController *nvc in tbc.viewControllers) {
  706. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  707. [nvc popToRootViewControllerAnimated:NO];
  708. }
  709. [tbc setSelectedIndex: index];
  710. } else {
  711. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  712. [nvcDetail popToRootViewControllerAnimated:NO];
  713. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  714. [tbc setSelectedIndex: index];
  715. }
  716. }
  717. - (NSString *)getTabBarControllerActiveServerUrl
  718. {
  719. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  720. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  721. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  722. NSInteger index = tabBarController.selectedIndex;
  723. // select active serverUrl
  724. if (index == k_tabBarApplicationIndexFile) {
  725. serverUrl = self.activeMain.serverUrl;
  726. } else if (index == k_tabBarApplicationIndexFavorite) {
  727. if (self.activeFavorites.serverUrl)
  728. serverUrl = self.activeFavorites.serverUrl;
  729. } else if (index == k_tabBarApplicationIndexMedia) {
  730. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  731. }
  732. return serverUrl;
  733. }
  734. #pragma --------------------------------------------------------------------------------------------
  735. #pragma mark ===== Theming Color =====
  736. #pragma --------------------------------------------------------------------------------------------
  737. - (void)settingThemingColorBrand
  738. {
  739. if (self.activeAccount.length == 0 || self.maintenanceMode)
  740. return;
  741. if ([NCBrandOptions sharedInstance].use_themingColor) {
  742. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  743. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  744. } else {
  745. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  746. [NCBrandColor sharedInstance].brandElement = [NCBrandColor sharedInstance].customer;
  747. [NCBrandColor sharedInstance].brandText = [NCBrandColor sharedInstance].customerText;
  748. }
  749. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  750. }
  751. - (void)changeTheming:(UIViewController *)vc
  752. {
  753. // Change Navigation & TabBar color
  754. vc.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  755. vc.tabBarController.tabBar.tintColor = [NCBrandColor sharedInstance].brandElement;
  756. // Change bar bottom line shadow
  757. vc.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  758. // Change button Plus
  759. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  760. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  761. UIButton *button = [tabBarController.view viewWithTag:99];
  762. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  763. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  764. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  765. // Tint Color GLOBAL WINDOW
  766. [self.window setTintColor:[NCBrandColor sharedInstance].textView];
  767. }
  768. #pragma --------------------------------------------------------------------------------------------
  769. #pragma mark ===== Manager Passcode =====
  770. #pragma --------------------------------------------------------------------------------------------
  771. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  772. {
  773. // ServerUrl active
  774. NSString *serverUrl = self.activeMain.serverUrl;
  775. BOOL isBlockZone = false;
  776. // fermiamo la data della sessione
  777. self.sessionePasscodeLock = nil;
  778. // se il block code è a zero esci con NON attivare la richiesta password
  779. if ([[CCUtility getBlockCode] length] == 0) return NO;
  780. // se non c'è attivo un account esci con NON attivare la richiesta password
  781. if ([self.activeAccount length] == 0) return NO;
  782. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  783. if (serverUrl && _activeUrl) {
  784. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  785. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  786. if (directory.lock) {
  787. isBlockZone = true;
  788. break;
  789. } else {
  790. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  791. if (serverUrl == self.activeUrl)
  792. break;
  793. }
  794. }
  795. }
  796. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  797. return YES;
  798. }
  799. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  800. {
  801. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  802. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  803. viewController.delegate = self;
  804. viewController.title = [NCBrandOptions sharedInstance].brand;
  805. viewController.fromType = CCBKPasscodeFromLockScreen;
  806. viewController.inputViewTitlePassword = YES;
  807. if ([CCUtility getSimplyBlockCode]) {
  808. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  809. viewController.passcodeInputView.maximumLength = 6;
  810. } else {
  811. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  812. viewController.passcodeInputView.maximumLength = 64;
  813. }
  814. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  815. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  816. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  817. return navigationController;
  818. }
  819. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  820. {
  821. [aViewController dismissViewControllerAnimated:YES completion:nil];
  822. // is a lock screen
  823. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  824. [aViewController dismissViewControllerAnimated:YES completion:nil];
  825. // start session Passcode Lock
  826. BOOL isBlockZone = false;
  827. NSString *serverUrl = self.activeMain.serverUrl;
  828. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  829. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  830. if (directory.lock) {
  831. isBlockZone = true;
  832. break;
  833. } else {
  834. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  835. if (serverUrl == self.activeUrl)
  836. break;
  837. }
  838. }
  839. if (isBlockZone)
  840. self.sessionePasscodeLock = [NSDate date];
  841. }
  842. }
  843. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  844. {
  845. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  846. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  847. //self.lockUntilDate = nil;
  848. //self.failedAttempts = 0;
  849. aResultHandler(YES);
  850. } else aResultHandler(NO);
  851. } else aResultHandler(YES);
  852. }
  853. #pragma --------------------------------------------------------------------------------------------
  854. #pragma mark ===== reachabilityChanged =====
  855. #pragma --------------------------------------------------------------------------------------------
  856. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  857. {
  858. if ([self.reachability isReachable]) {
  859. if (self.lastReachability == NO) {
  860. NSLog(@"[LOG] Request Service Server Nextcloud");
  861. [[NCService sharedInstance] startRequestServicesServer];
  862. }
  863. NSLog(@"[LOG] Reachability Changed: Reachable");
  864. self.lastReachability = YES;
  865. } else {
  866. if (self.lastReachability == YES) {
  867. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  868. }
  869. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  870. self.lastReachability = NO;
  871. }
  872. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  873. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  874. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  875. }
  876. #pragma --------------------------------------------------------------------------------------------
  877. #pragma mark ===== Fetch =====
  878. #pragma --------------------------------------------------------------------------------------------
  879. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  880. {
  881. // Test Maintenance
  882. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  883. completionHandler(UIBackgroundFetchResultNoData);
  884. return;
  885. }
  886. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  887. // Verify new photo
  888. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  889. // after 20 sec
  890. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  891. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  892. if ([records count] > 0) {
  893. completionHandler(UIBackgroundFetchResultNewData);
  894. } else {
  895. completionHandler(UIBackgroundFetchResultNoData);
  896. }
  897. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  898. });
  899. }
  900. #pragma --------------------------------------------------------------------------------------------
  901. #pragma mark ===== Operation Networking & Session =====
  902. #pragma --------------------------------------------------------------------------------------------
  903. //
  904. // Method called by the system when all the background task has end
  905. //
  906. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  907. {
  908. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  909. // after 20 sec
  910. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  911. self.backgroundSessionCompletionHandler = completionHandler;
  912. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  913. self.backgroundSessionCompletionHandler = nil;
  914. completionHandler();
  915. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  916. });
  917. }
  918. #pragma --------------------------------------------------------------------------------------------
  919. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  920. #pragma --------------------------------------------------------------------------------------------
  921. - (void)loadAutoDownloadUpload
  922. {
  923. if (self.activeAccount.length == 0 || self.maintenanceMode)
  924. return;
  925. tableMetadata *metadataForUpload, *metadataForDownload;
  926. long counterDownload = 0, counterUpload = 0;
  927. NSUInteger sizeDownload = 0, sizeUpload = 0;
  928. BOOL isE2EE = false;
  929. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  930. // Detect E2EE
  931. NSString *saveserverUrl = @"";
  932. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status != %d", k_metadataStatusNormal] sorted:@"serverUrl" ascending:NO];
  933. for (tableMetadata *metadata in metadatasForE2EE) {
  934. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  935. saveserverUrl = metadata.serverUrl;
  936. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  937. isE2EE = true;
  938. break;
  939. }
  940. }
  941. }
  942. // E2EE : not in background
  943. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  944. return;
  945. }
  946. // E2EE : only 1 operation
  947. if (isE2EE) {
  948. maxConcurrentOperationDownloadUpload = 1;
  949. }
  950. // Stop Timer
  951. [_timerProcessAutoDownloadUpload invalidate];
  952. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  953. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  954. // Counter
  955. counterDownload = [metadatasDownload count];
  956. counterUpload = [metadatasUpload count];
  957. // Size
  958. for (tableMetadata *metadata in metadatasDownload) {
  959. sizeDownload = sizeDownload + metadata.size;
  960. }
  961. for (tableMetadata *metadata in metadatasUpload) {
  962. sizeUpload = sizeUpload + metadata.size;
  963. }
  964. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] -PROCESS-AUTO-UPLOAD- | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  965. // ------------------------- <selector Download> -------------------------
  966. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  967. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"session" ascending:YES];
  968. if (metadataForDownload) {
  969. metadataForDownload.status = k_metadataStatusInDownload;
  970. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  971. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  972. counterDownload++;
  973. sizeDownload = sizeDownload + metadata.size;
  974. } else {
  975. break;
  976. }
  977. }
  978. // ------------------------- <selector Upload> -------------------------
  979. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  980. if (sizeUpload > k_maxSizeOperationUpload) {
  981. break;
  982. }
  983. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  984. if (metadataForUpload) {
  985. if ([metadataForUpload.session isEqualToString:k_upload_session_extension]) {
  986. metadataForUpload.session = k_upload_session;
  987. }
  988. metadataForUpload.status = k_metadataStatusInUpload;
  989. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  990. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  991. counterUpload++;
  992. sizeUpload = sizeUpload + metadata.size;
  993. } else {
  994. break;
  995. }
  996. }
  997. // ------------------------- <selector Auto Upload> -------------------------
  998. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  999. if (sizeUpload > k_maxSizeOperationUpload) {
  1000. break;
  1001. }
  1002. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1003. if (metadataForUpload) {
  1004. metadataForUpload.status = k_metadataStatusInUpload;
  1005. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1006. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1007. counterUpload++;
  1008. sizeUpload = sizeUpload + metadata.size;
  1009. } else {
  1010. break;
  1011. }
  1012. }
  1013. // ------------------------- <selector Auto Upload All> ----------------------
  1014. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1015. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1016. NSInteger errorCount = [metadatas count];
  1017. if (errorCount >= k_maxErrorAutoUploadAll) {
  1018. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1019. } else {
  1020. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1021. if (sizeUpload > k_maxSizeOperationUpload) {
  1022. break;
  1023. }
  1024. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1025. if (metadataForUpload) {
  1026. metadataForUpload.status = k_metadataStatusInUpload;
  1027. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1028. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1029. counterUpload++;
  1030. sizeUpload = sizeUpload + metadata.size;
  1031. } else {
  1032. break;
  1033. }
  1034. }
  1035. }
  1036. // No Download/upload available ? --> remove errors for retry
  1037. //
  1038. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1039. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1040. for (tableMetadata *metadata in metadatas) {
  1041. if (metadata.status == k_metadataStatusDownloadError)
  1042. metadata.status = k_metadataStatusWaitDownload;
  1043. else if (metadata.status == k_metadataStatusUploadError)
  1044. metadata.status = k_metadataStatusWaitUpload;
  1045. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1046. }
  1047. }
  1048. // Verify internal error download (lost task)
  1049. //
  1050. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_download_session_extension, k_metadataStatusDownloading] sorted:nil ascending:true];
  1051. for (tableMetadata *metadata in matadatasInDownloading) {
  1052. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1053. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1054. NSURLSessionTask *findTask;
  1055. for (NSURLSessionTask *task in downloadTasks) {
  1056. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1057. findTask = task;
  1058. }
  1059. }
  1060. if (!findTask) {
  1061. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1062. metadata.status = k_metadataStatusWaitDownload;
  1063. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1064. }
  1065. }];
  1066. }
  1067. // Verify internal error upload (lost task)
  1068. //
  1069. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1070. for (tableMetadata *metadata in metadatasUploading) {
  1071. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1072. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1073. NSURLSessionTask *findTask;
  1074. for (NSURLSessionTask *task in uploadTasks) {
  1075. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1076. findTask = task;
  1077. }
  1078. }
  1079. if (!findTask) {
  1080. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1081. metadata.status = k_metadataStatusWaitUpload;
  1082. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1083. }
  1084. }];
  1085. }
  1086. // Upload in pending
  1087. //
  1088. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1089. for (tableMetadata *metadata in metadatasInUpload) {
  1090. if ([self.sessionPendingStatusInUpload containsObject:metadata.fileID]) {
  1091. metadata.status = k_metadataStatusWaitUpload;
  1092. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1093. } else {
  1094. [self.sessionPendingStatusInUpload addObject:metadata.fileID];
  1095. }
  1096. }
  1097. if (metadatasInUpload.count == 0) {
  1098. [self.sessionPendingStatusInUpload removeAllObjects];
  1099. }
  1100. // Start Timer
  1101. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1102. }
  1103. - (void)startLoadAutoDownloadUpload
  1104. {
  1105. if (self.timerProcessAutoDownloadUpload.isValid) {
  1106. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1107. }
  1108. }
  1109. #pragma --------------------------------------------------------------------------------------------
  1110. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1111. #pragma --------------------------------------------------------------------------------------------
  1112. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1113. {
  1114. return YES;
  1115. }
  1116. // Method called from iOS system to send a file from other app.
  1117. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1118. {
  1119. NSError *error;
  1120. NSLog(@"[LOG] the path is: %@", url.path);
  1121. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1122. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1123. if (self.activeAccount) {
  1124. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1125. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1126. if (error == nil) {
  1127. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1128. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1129. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1130. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1131. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1132. });
  1133. }
  1134. }
  1135. return YES;
  1136. }
  1137. #pragma --------------------------------------------------------------------------------------------
  1138. #pragma mark ===== Maintenance Mode =====
  1139. #pragma --------------------------------------------------------------------------------------------
  1140. - (void)maintenanceMode:(BOOL)mode
  1141. {
  1142. self.maintenanceMode = mode;
  1143. }
  1144. #pragma --------------------------------------------------------------------------------------------
  1145. #pragma mark ===== UPGRADE =====
  1146. #pragma --------------------------------------------------------------------------------------------
  1147. - (BOOL)upgrade
  1148. {
  1149. #ifdef DEBUG
  1150. //self.maintenanceMode = YES;
  1151. #endif
  1152. NSString *actualVersion = [CCUtility getVersion];
  1153. NSString *actualBuild = [CCUtility getBuild];
  1154. /* ---------------------- UPGRADE VERSION ----------------------- */
  1155. // VERSION < 2.17.6
  1156. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1157. // Remove All old Photo Library
  1158. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1159. }
  1160. // VERSION == 2.17.6
  1161. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1162. // Build < 10
  1163. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1164. // Remove All old Photo Library
  1165. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1166. }
  1167. }
  1168. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1169. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1170. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1171. }
  1172. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1173. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1174. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1175. NSString *account = @"";
  1176. NSString *directoryUser = @"";
  1177. NSString *fileName;
  1178. for (tableLocalFile *record in records) {
  1179. if (![account isEqualToString:record.account]) {
  1180. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1181. if (tableAccount) {
  1182. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1183. account = record.account;
  1184. }
  1185. }
  1186. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.fileID];
  1187. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1188. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageFileID:record.fileID fileNameView:record.fileName]];
  1189. }
  1190. }
  1191. });
  1192. }
  1193. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1194. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1195. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1196. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1197. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1198. }
  1199. }
  1200. return YES;
  1201. }
  1202. @end