AppDelegate.m 68 KB

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