AppDelegate.m 68 KB

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