AppDelegate.m 69 KB

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