AppDelegate.m 68 KB

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