AppDelegate.m 68 KB

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