AppDelegate.m 68 KB

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