AppDelegate.m 70 KB

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