AppDelegate.m 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  1. //
  2. // AppDelegate.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 "CCNetworking.h"
  25. #import "CCGraphics.h"
  26. #import "CCSynchronize.h"
  27. #import "CCMain.h"
  28. #import "CCDetail.h"
  29. #import <Fabric/Fabric.h>
  30. #import <Crashlytics/Crashlytics.h>
  31. #import "NCBridgeSwift.h"
  32. #import "NCAutoUpload.h"
  33. #import "NCPushNotificationEncryption.h"
  34. @class NCViewerRichdocument;
  35. @implementation AppDelegate
  36. + (void)initialize
  37. {
  38. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  39. }
  40. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  41. {
  42. [CCUtility createDirectoryStandard];
  43. // Networking
  44. [[NCCommunicationCommon sharedInstance] setupWithUserAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups delegate:[NCNetworking sharedInstance]];
  45. // Verify upgrade
  46. if ([self upgrade]) {
  47. // Set account, if no exists clear all
  48. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  49. if (tableAccount == nil) {
  50. // remove all the keys Chain
  51. [CCUtility deleteAllChainStore];
  52. // remove all the App group key
  53. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  54. } else {
  55. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  56. }
  57. }
  58. // UserDefaults
  59. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  60. // Filter ocId
  61. self.filterocId = [NSMutableArray new];
  62. // Upload Pending In Upload (crash)
  63. self.sessionPendingStatusInUpload = [NSMutableArray new];
  64. // Initialization Notification
  65. self.listOfNotifications = [NSMutableArray new];
  66. // Background Fetch
  67. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  68. // Initialization List
  69. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  70. self.listMainVC = [[NSMutableDictionary alloc] init];
  71. // Push Notification
  72. [application registerForRemoteNotifications];
  73. // Display notification (sent via APNS)
  74. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  75. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  76. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  77. }];
  78. // setting Reachable in back
  79. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  80. self.reachability = [Reachability reachabilityForInternetConnection];
  81. self.lastReachability = [self.reachability isReachable];
  82. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  83. [self.reachability startNotifier];
  84. });
  85. //AV Session
  86. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  87. // [[AVAudioSession sharedInstance] setActive:YES error:nil];
  88. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  89. // APPEARANCE: How to hide UINavigationBar 1px bottom line < iOS 11
  90. [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
  91. [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
  92. [UINavigationBar appearance].translucent = NO;
  93. // passcode
  94. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  95. dispatch_async(dispatch_get_main_queue(), ^{
  96. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  97. });
  98. // Quick Actions
  99. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  100. [self configDynamicShortcutItems];
  101. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  102. if (shortcutItem)
  103. [self handleShortCutItem:shortcutItem];
  104. }
  105. // Start Timer
  106. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  107. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  108. [self startTimerErrorNetworking];
  109. // Fabric
  110. if (![CCUtility getDisableCrashservice] && NCBrandOptions.sharedInstance.disable_crash_service == false) {
  111. [Fabric with:@[[Crashlytics class]]];
  112. }
  113. // Store review
  114. if ([[NCUtility sharedInstance] isSimulatorOrTestFlight] == false) {
  115. NCStoreReview *review = [NCStoreReview new];
  116. [review incrementAppRuns];
  117. [review showStoreReview];
  118. }
  119. // Detect Dark mode
  120. if (@available(iOS 13.0, *)) {
  121. if ([CCUtility getDarkModeDetect]) {
  122. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  123. [CCUtility setDarkMode:YES];
  124. } else {
  125. [CCUtility setDarkMode:NO];
  126. }
  127. }
  128. }
  129. if ([NCBrandOptions sharedInstance].disable_intro) {
  130. [CCUtility setIntro:YES];
  131. if (self.activeAccount.length == 0) {
  132. [self openLoginView:nil selector:k_intro_login openLoginWeb:false];
  133. }
  134. } else {
  135. if ([CCUtility getIntro] == NO) {
  136. UIViewController *introViewController = [[UIStoryboard storyboardWithName:@"NCIntro" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
  137. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: introViewController];
  138. self.window.rootViewController = navController;
  139. [self.window makeKeyAndVisible];
  140. }
  141. }
  142. // init home
  143. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  144. return YES;
  145. }
  146. //
  147. // L' applicazione si dimetterà dallo stato di attivo
  148. //
  149. - (void)applicationWillResignActive:(UIApplication *)application
  150. {
  151. // Test Maintenance
  152. if (self.activeAccount.length == 0 || self.maintenanceMode)
  153. return;
  154. [self updateApplicationIconBadgeNumber];
  155. }
  156. //
  157. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  158. //
  159. - (void)applicationWillEnterForeground:(UIApplication *)application
  160. {
  161. // Test Maintenance
  162. if (self.activeAccount.length == 0 || self.maintenanceMode)
  163. return;
  164. NSLog(@"[LOG] Request Service Server Nextcloud");
  165. [[NCService sharedInstance] startRequestServicesServer];
  166. NSLog(@"[LOG] Initialize Auto upload");
  167. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  168. NSLog(@"[LOG] Read active directory");
  169. [self.activeMain readFileReloadFolder];
  170. NSLog(@"[LOG] Required unsubscribing / subscribing");
  171. [self pushNotification];
  172. NSLog(@"[LOG] RichDocument");
  173. if (self.activeDetail.richDocument) {
  174. [self.activeDetail.richDocument grabFocus];
  175. }
  176. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"applicationWillEnterForeground" object:nil];
  177. }
  178. //
  179. // L' applicazione entrerà in primo piano (attivo sempre)
  180. //
  181. - (void)applicationDidBecomeActive:(UIApplication *)application
  182. {
  183. // Test Maintenance
  184. if (self.activeAccount.length == 0 || self.maintenanceMode)
  185. return;
  186. // middelware ping
  187. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  188. NSLog(@"[LOG] Middleware Ping");
  189. [[NCService sharedInstance] middlewarePing];
  190. }
  191. // Brand
  192. #if defined(HC)
  193. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  194. if (account.hcIsTrial == true || account.hcTrialExpired == true || account.hcNextGroupExpirationGroupExpired == true) {
  195. HCTrial *vc = [[UIStoryboard storyboardWithName:@"HCTrial" bundle:nil] instantiateInitialViewController];
  196. vc.account = account;
  197. [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
  198. }
  199. #endif
  200. }
  201. //
  202. // L' applicazione è entrata nello sfondo
  203. //
  204. - (void)applicationDidEnterBackground:(UIApplication *)application
  205. {
  206. NSLog(@"[LOG] Enter in Background");
  207. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  208. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  209. __block UIBackgroundTaskIdentifier background_task;
  210. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  211. //Clean up code. Tell the system that we are done.
  212. [application endBackgroundTask: background_task];
  213. background_task = UIBackgroundTaskInvalid;
  214. }];
  215. }
  216. }
  217. //
  218. // L'applicazione terminerà
  219. //
  220. - (void)applicationWillTerminate:(UIApplication *)application
  221. {
  222. NSLog(@"[LOG] bye bye, Nextcloud !");
  223. }
  224. #pragma --------------------------------------------------------------------------------------------
  225. #pragma mark ===== Login / checkErrorNetworking =====
  226. #pragma --------------------------------------------------------------------------------------------
  227. - (void)checkErrorNetworking
  228. {
  229. // test
  230. if (self.activeAccount.length == 0 || self.maintenanceMode)
  231. return;
  232. // check unauthorized server (401)
  233. if ([CCUtility getPassword:self.activeAccount].length == 0) {
  234. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:true];
  235. }
  236. // check certificate untrusted (-1202)
  237. if ([CCUtility getCertificateError:self.activeAccount]) {
  238. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  239. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  240. [[NCNetworking sharedInstance] wrtiteCertificateWithDirectoryCertificate:[CCUtility getDirectoryCerificates]];
  241. [self startTimerErrorNetworking];
  242. }]];
  243. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  244. [self startTimerErrorNetworking];
  245. }]];
  246. [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
  247. // Stop timer error network
  248. [self.timerErrorNetworking invalidate];
  249. }];
  250. }
  251. }
  252. - (void)openLoginView:(UIViewController *)viewController selector:(NSInteger)selector openLoginWeb:(BOOL)openLoginWeb
  253. {
  254. // use appConfig [MDM]
  255. if ([NCBrandOptions sharedInstance].use_configuration) {
  256. if (!(_appConfigView.isViewLoaded && _appConfigView.view.window)) {
  257. self.appConfigView = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCAppConfigView"];
  258. [self showLoginViewController:self.appConfigView forContext:viewController];
  259. }
  260. return;
  261. }
  262. // only for personalized LoginWeb [customer]
  263. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  264. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  265. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  266. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  267. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  268. }
  269. return;
  270. }
  271. // normal login
  272. if (selector == k_intro_signup) {
  273. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  274. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  275. if (selector == k_intro_signup) {
  276. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  277. } else {
  278. self.activeLoginWeb.urlBase = self.activeUrl;
  279. }
  280. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  281. }
  282. } else if ([NCBrandOptions sharedInstance].disable_intro && [NCBrandOptions sharedInstance].disable_request_login_url) {
  283. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  284. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  285. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  286. } else if (openLoginWeb) {
  287. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  288. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  289. self.activeLoginWeb.urlBase = self.activeUrl;
  290. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  291. }
  292. } else {
  293. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  294. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  295. [self showLoginViewController:_activeLogin forContext:viewController];
  296. }
  297. }
  298. }
  299. -(void)showLoginViewController:(UIViewController *)viewController forContext:(UIViewController *)contextViewController
  300. {
  301. if (contextViewController == NULL) {
  302. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  303. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  304. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  305. self.window.rootViewController = navController;
  306. [self.window makeKeyAndVisible];
  307. } else if ([contextViewController isKindOfClass:[UINavigationController class]]) {
  308. UINavigationController *navController = ((UINavigationController *)contextViewController);
  309. [navController pushViewController:viewController animated:true];
  310. } else {
  311. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  312. navController.modalPresentationStyle = UIModalPresentationFullScreen;
  313. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  314. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  315. [contextViewController presentViewController:navController animated:true completion:nil];
  316. }
  317. }
  318. - (void)startTimerErrorNetworking
  319. {
  320. self.timerErrorNetworking = [NSTimer scheduledTimerWithTimeInterval:k_timerErrorNetworking target:self selector:@selector(checkErrorNetworking) userInfo:nil repeats:YES];
  321. }
  322. #pragma --------------------------------------------------------------------------------------------
  323. #pragma mark ===== Account =====
  324. #pragma --------------------------------------------------------------------------------------------
  325. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activeUserID:(NSString *)activeUserID activePassword:(NSString *)activePassword
  326. {
  327. self.activeAccount = activeAccount;
  328. self.activeUrl = activeUrl;
  329. self.activeUser = activeUser;
  330. self.activeUserID = activeUserID;
  331. self.activePassword = activePassword;
  332. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:activeAccount];
  333. // Setting Account to Networking
  334. [CCNetworking sharedNetworking].delegate = [NCNetworkingMain sharedInstance];
  335. [[NCNetworking sharedInstance] setupWithAccount:activeAccount delegate:nil];
  336. [[NCCommunicationCommon sharedInstance] setupWithUsername:activeUser userID:activeUserID password:activePassword userAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups nextcloudVersion:capabilities.versionMajor delegate:[NCNetworking sharedInstance]];
  337. }
  338. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  339. {
  340. [self unsubscribingNextcloudServerPushNotification:account url:self.activeUrl withSubscribing:false];
  341. [self settingActiveAccount:nil activeUrl:nil activeUser:nil activeUserID:nil activePassword:nil];
  342. /* DELETE ALL FILES LOCAL FS */
  343. NSArray *results = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  344. for (tableLocalFile *result in results) {
  345. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  346. }
  347. // Clear database
  348. [[NCManageDatabase sharedInstance] clearDatabaseWithAccount:account removeAccount:true];
  349. [CCUtility clearAllKeysEndToEnd:account];
  350. [CCUtility clearAllKeysPushNotification:account];
  351. [CCUtility setCertificateError:account error:false];
  352. [CCUtility setPassword:account password:nil];
  353. if (wipe) {
  354. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  355. if ([listAccount count] > 0) {
  356. NSString *newAccount = listAccount[0];
  357. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:newAccount];
  358. [self settingActiveAccount:newAccount activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  359. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  360. } else {
  361. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:false];
  362. }
  363. }
  364. }
  365. #pragma --------------------------------------------------------------------------------------------
  366. #pragma mark ===== Push Notifications =====
  367. #pragma --------------------------------------------------------------------------------------------
  368. - (void)pushNotification
  369. {
  370. // test
  371. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  372. return;
  373. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  374. NSString *token = [CCUtility getPushNotificationToken:result.account];
  375. if (![token isEqualToString:self.pushKitToken]) {
  376. if (token != nil) {
  377. // unsubscribing + subscribing
  378. [self unsubscribingNextcloudServerPushNotification:result.account url:result.url withSubscribing:true];
  379. } else {
  380. [self subscribingNextcloudServerPushNotification:result.account url:result.url];
  381. }
  382. }
  383. }
  384. }
  385. - (void)subscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url
  386. {
  387. // test
  388. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  389. return;
  390. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair:account];
  391. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken];
  392. NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account];
  393. NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding];
  394. [[OCNetworking sharedManager] subscribingPushNotificationWithAccount:account url:url pushToken:self.pushKitToken Hash:pushTokenHash devicePublicKey:pushDevicePublicKey completion:^(NSString *accountCompletion, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode) {
  395. if (errorCode == 0 && [accountCompletion isEqualToString:account]) {
  396. NSLog(@"[LOG] Subscribed to Push Notification server & proxy successfully.");
  397. [CCUtility setPushNotificationToken:account token:self.pushKitToken];
  398. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier];
  399. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:deviceIdentifierSignature];
  400. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  401. } else if (errorCode != 0) {
  402. NSLog(@"[LOG] Subscribed to Push Notification server & proxy error.");
  403. } else {
  404. NSLog(@"[LOG] It has been changed user during networking process, error.");
  405. }
  406. }];
  407. }
  408. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url withSubscribing:(BOOL)subscribing
  409. {
  410. // test
  411. if (self.activeAccount.length == 0 || self.maintenanceMode)
  412. return;
  413. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  414. NSString *deviceIdentifierSignature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  415. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  416. [[OCNetworking sharedManager] unsubscribingPushNotificationWithAccount:account url:url deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  417. if (errorCode == 0) {
  418. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  419. [CCUtility setPushNotificationPublicKey:account data:nil];
  420. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  421. [CCUtility setPushNotificationPrivateKey:account data:nil];
  422. [CCUtility setPushNotificationToken:account token:nil];
  423. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  424. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  425. if (self.pushKitToken != nil && subscribing) {
  426. [self subscribingNextcloudServerPushNotification:account url:url];
  427. }
  428. } else if (errorCode != 0) {
  429. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy error.");
  430. } else {
  431. NSLog(@"[LOG] It has been changed user during networking process, error.");
  432. }
  433. }];
  434. }
  435. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  436. {
  437. //Called when a notification is delivered to a foreground app.
  438. completionHandler(UNNotificationPresentationOptionAlert);
  439. }
  440. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  441. {
  442. completionHandler();
  443. }
  444. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  445. {
  446. self.pushKitToken = [self stringWithDeviceToken:deviceToken];
  447. [self pushNotification];
  448. }
  449. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  450. {
  451. NSString *message = [userInfo objectForKey:@"subject"];
  452. if (message) {
  453. NSArray *results = [[NCManageDatabase sharedInstance] getAllAccount];
  454. for (tableAccount *result in results) {
  455. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  456. NSData *decryptionKey = [CCUtility getPushNotificationPrivateKey:result.account];
  457. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:decryptionKey];
  458. if (decryptedMessage) {
  459. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  460. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  461. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  462. BOOL delete = [[json objectForKey:@"delete"] boolValue];
  463. BOOL deleteAll = [[json objectForKey:@"delete-all"] boolValue];
  464. if (delete) {
  465. [self removeNotificationWithNotificationId:nid usingDecryptionKey:decryptionKey];
  466. } else if (deleteAll) {
  467. [self cleanAllNotifications];
  468. }
  469. }
  470. }
  471. }
  472. }
  473. completionHandler(UIBackgroundFetchResultNoData);
  474. }
  475. - (void)cleanAllNotifications
  476. {
  477. [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  478. }
  479. - (void)removeNotificationWithNotificationId:(NSInteger)notificationId usingDecryptionKey:(NSData *)key
  480. {
  481. // Check in pending notifications
  482. [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
  483. for (UNNotificationRequest *notificationRequest in requests) {
  484. NSString *message = [notificationRequest.content.userInfo objectForKey:@"subject"];
  485. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  486. if (decryptedMessage) {
  487. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  488. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  489. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  490. if (nid == notificationId) {
  491. [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[notificationRequest.identifier]];
  492. }
  493. }
  494. }
  495. }];
  496. // Check in delivered notifications
  497. [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
  498. for (UNNotification *notification in notifications) {
  499. NSString *message = [notification.request.content.userInfo objectForKey:@"subject"];
  500. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  501. if (decryptedMessage) {
  502. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  503. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  504. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  505. if (nid == notificationId) {
  506. [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
  507. }
  508. }
  509. }
  510. }];
  511. }
  512. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  513. {
  514. const char *data = [deviceToken bytes];
  515. NSMutableString *token = [NSMutableString string];
  516. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  517. [token appendFormat:@"%02.2hhX", data[i]];
  518. }
  519. return [token copy];
  520. }
  521. #pragma --------------------------------------------------------------------------------------------
  522. #pragma mark ===== Quick Actions - ShotcutItem =====
  523. #pragma --------------------------------------------------------------------------------------------
  524. - (void)configDynamicShortcutItems
  525. {
  526. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  527. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  528. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  529. // add the array to our app
  530. if (shortcutMedia)
  531. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  532. }
  533. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  534. {
  535. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  536. completionHandler(handledShortCutItem);
  537. }
  538. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  539. {
  540. BOOL handled = NO;
  541. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  542. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  543. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  544. dispatch_async(dispatch_get_main_queue(), ^{
  545. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  546. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  547. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  548. if (splitViewController.isCollapsed) {
  549. [navigationControllerMaster popToRootViewControllerAnimated:false];
  550. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  551. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  552. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  553. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  554. }
  555. } else {
  556. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  557. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  558. }
  559. }
  560. });
  561. handled = YES;
  562. }
  563. return handled;
  564. }
  565. #pragma --------------------------------------------------------------------------------------------
  566. #pragma mark ===== ApplicationIconBadgeNumber =====
  567. #pragma --------------------------------------------------------------------------------------------
  568. - (void)updateApplicationIconBadgeNumber
  569. {
  570. if (self.activeAccount.length == 0 || self.maintenanceMode)
  571. return;
  572. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  573. NSInteger counterDownload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status = %d OR status == %d OR status == %d", k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:@"fileName" ascending:true] count];
  574. NSInteger counterUpload = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d OR status == %d", k_metadataStatusWaitUpload, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:@"fileName" ascending:true] count];
  575. NSInteger total = counterDownload + counterUpload;
  576. dispatch_async(dispatch_get_main_queue(), ^{
  577. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  578. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  579. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  580. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  581. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  582. UITabBarItem *tabBarItem = [tabBarController.tabBar.items objectAtIndex:0];
  583. if (total > 0) {
  584. [tabBarItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  585. } else {
  586. [tabBarItem setBadgeValue:nil];
  587. }
  588. }
  589. });
  590. });
  591. }
  592. #pragma --------------------------------------------------------------------------------------------
  593. #pragma mark ===== TabBarController =====
  594. #pragma --------------------------------------------------------------------------------------------
  595. - (void)createTabBarController:(UITabBarController *)tabBarController
  596. {
  597. UITabBarItem *item;
  598. NSLayoutConstraint *constraint;
  599. CGFloat safeAreaBottom = 0;
  600. if (@available(iOS 11, *)) {
  601. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  602. }
  603. // File
  604. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  605. [item setTitle:NSLocalizedString(@"_home_", nil)];
  606. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  607. item.selectedImage = item.image;
  608. // Favorites
  609. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  610. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  611. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  612. item.selectedImage = item.image;
  613. // (PLUS INVISIBLE)
  614. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  615. item.title = @"";
  616. item.image = nil;
  617. item.enabled = false;
  618. // Media
  619. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  620. [item setTitle:NSLocalizedString(@"_media_", nil)];
  621. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  622. item.selectedImage = item.image;
  623. // More
  624. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  625. [item setTitle:NSLocalizedString(@"_more_", nil)];
  626. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  627. item.selectedImage = item.image;
  628. // Plus Button
  629. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] width:120 height:120 color:NCBrandColor.sharedInstance.brandElement];
  630. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  631. buttonPlus.tag = 99;
  632. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  633. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  634. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  635. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  636. [tabBarController.tabBar addSubview:buttonPlus];
  637. if (safeAreaBottom > 0) {
  638. // X
  639. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  640. [tabBarController.view addConstraint:constraint];
  641. // Y
  642. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:5];
  643. [tabBarController.view addConstraint:constraint];
  644. // Width
  645. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:40];
  646. [tabBarController.view addConstraint:constraint];
  647. // Height
  648. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:40];
  649. [tabBarController.view addConstraint:constraint];
  650. } else {
  651. // X
  652. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  653. [tabBarController.view addConstraint:constraint];
  654. // Y
  655. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
  656. [tabBarController.view addConstraint:constraint];
  657. // Width
  658. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:33];
  659. [tabBarController.view addConstraint:constraint];
  660. // Height
  661. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:33];
  662. [tabBarController.view addConstraint:constraint];
  663. }
  664. }
  665. - (void)handleTouchTabbarCenter:(id)sender
  666. {
  667. // Test Maintenance
  668. if (self.maintenanceMode)
  669. return;
  670. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, self.activeMain.serverUrl]];
  671. if ([tableDirectory.permissions containsString:@"CK"]) {
  672. UIViewController *vc = _activeMain.splitViewController.viewControllers[0];
  673. [self showMenuInViewController: vc];
  674. } else {
  675. [[NCContentPresenter shared] messageNotification:@"_warning_" description:@"_no_permission_add_file_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  676. }
  677. }
  678. - (NSString *)getTabBarControllerActiveServerUrl
  679. {
  680. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  681. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  682. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  683. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  684. NSInteger index = tabBarController.selectedIndex;
  685. // select active serverUrl
  686. if (index == k_tabBarApplicationIndexFile) {
  687. serverUrl = self.activeMain.serverUrl;
  688. } else if (index == k_tabBarApplicationIndexFavorite) {
  689. if (self.activeFavorites.serverUrl)
  690. serverUrl = self.activeFavorites.serverUrl;
  691. } else if (index == k_tabBarApplicationIndexMedia) {
  692. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  693. }
  694. return serverUrl;
  695. }
  696. #pragma --------------------------------------------------------------------------------------------
  697. #pragma mark ===== Theming Color =====
  698. #pragma --------------------------------------------------------------------------------------------
  699. - (void)settingThemingColorBrand
  700. {
  701. if (self.activeAccount.length == 0 || self.maintenanceMode)
  702. return;
  703. if ([NCBrandOptions sharedInstance].use_themingColor) {
  704. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  705. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  706. } else {
  707. NCBrandColor.sharedInstance.brand = NCBrandColor.sharedInstance.customer;
  708. NCBrandColor.sharedInstance.brandElement = NCBrandColor.sharedInstance.customer;
  709. NCBrandColor.sharedInstance.brandText = NCBrandColor.sharedInstance.customerText;
  710. }
  711. [[NCMainCommon sharedInstance] createImagesThemingColor];
  712. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  713. }
  714. - (void)changeTheming:(UIViewController *)viewController tableView:(UITableView *)tableView collectionView:(UICollectionView *)collectionView form:(BOOL)form
  715. {
  716. // Dark Mode
  717. [NCBrandColor.sharedInstance setDarkMode];
  718. // View
  719. if (form) viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  720. else viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  721. // NavigationBar
  722. if (viewController.navigationController.navigationBar) {
  723. viewController.navigationController.navigationBar.translucent = NO;
  724. viewController.navigationController.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand;
  725. viewController.navigationController.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText;
  726. if ([self.reachability isReachable]) {
  727. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.brandText}];
  728. } else {
  729. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.connectionNo}];
  730. }
  731. viewController.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:NCBrandColor.sharedInstance.brand];
  732. [viewController.navigationController.navigationBar setAlpha:1];
  733. }
  734. //tabBar
  735. if (viewController.tabBarController.tabBar) {
  736. viewController.tabBarController.tabBar.translucent = NO;
  737. viewController.tabBarController.tabBar.barTintColor = NCBrandColor.sharedInstance.tabBar;
  738. viewController.tabBarController.tabBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  739. [viewController.tabBarController.tabBar setAlpha:1];
  740. }
  741. //tabBar button Plus
  742. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  743. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  744. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  745. UIButton *button = [tabBarController.view viewWithTag:99];
  746. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:NCBrandColor.sharedInstance.brandElement];
  747. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  748. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  749. // TableView
  750. if (tableView) {
  751. if (form) tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  752. else tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  753. tableView.separatorColor = NCBrandColor.sharedInstance.separator;
  754. [tableView reloadData];
  755. }
  756. // CollectionView
  757. if (collectionView) {
  758. if (form) collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  759. else collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  760. [collectionView reloadData];
  761. }
  762. // Tint Color GLOBAL WINDOW
  763. [self.window setTintColor:NCBrandColor.sharedInstance.textView];
  764. }
  765. #pragma --------------------------------------------------------------------------------------------
  766. #pragma mark ===== Manager Passcode =====
  767. #pragma --------------------------------------------------------------------------------------------
  768. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  769. {
  770. // ServerUrl active
  771. NSString *serverUrl = self.activeMain.serverUrl;
  772. BOOL isBlockZone = false;
  773. // fermiamo la data della sessione
  774. self.sessionePasscodeLock = nil;
  775. // se il block code è a zero esci con NON attivare la richiesta password
  776. if ([[CCUtility getBlockCode] length] == 0) return NO;
  777. // se non c'è attivo un account esci con NON attivare la richiesta password
  778. if ([self.activeAccount length] == 0) return NO;
  779. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  780. if (serverUrl && _activeUrl) {
  781. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  782. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  783. if (directory.lock) {
  784. isBlockZone = true;
  785. break;
  786. } else {
  787. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  788. if (serverUrl == self.activeUrl)
  789. break;
  790. }
  791. }
  792. }
  793. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  794. return YES;
  795. }
  796. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  797. {
  798. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  799. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  800. viewController.delegate = self;
  801. viewController.title = [NCBrandOptions sharedInstance].brand;
  802. viewController.fromType = CCBKPasscodeFromLockScreen;
  803. viewController.inputViewTitlePassword = YES;
  804. if ([CCUtility getSimplyBlockCode]) {
  805. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  806. viewController.passcodeInputView.maximumLength = 6;
  807. } else {
  808. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  809. viewController.passcodeInputView.maximumLength = 64;
  810. }
  811. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  812. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  813. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  814. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  815. return navigationController;
  816. }
  817. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  818. {
  819. [aViewController dismissViewControllerAnimated:YES completion:nil];
  820. // is a lock screen
  821. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  822. [aViewController dismissViewControllerAnimated:YES completion:nil];
  823. // start session Passcode Lock
  824. BOOL isBlockZone = false;
  825. NSString *serverUrl = self.activeMain.serverUrl;
  826. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  827. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  828. if (directory.lock) {
  829. isBlockZone = true;
  830. break;
  831. } else {
  832. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  833. if (serverUrl == self.activeUrl)
  834. break;
  835. }
  836. }
  837. if (isBlockZone)
  838. self.sessionePasscodeLock = [NSDate date];
  839. }
  840. }
  841. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  842. {
  843. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  844. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  845. //self.lockUntilDate = nil;
  846. //self.failedAttempts = 0;
  847. aResultHandler(YES);
  848. } else aResultHandler(NO);
  849. } else aResultHandler(YES);
  850. }
  851. #pragma --------------------------------------------------------------------------------------------
  852. #pragma mark ===== reachabilityChanged =====
  853. #pragma --------------------------------------------------------------------------------------------
  854. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  855. {
  856. if ([self.reachability isReachable]) {
  857. if (self.lastReachability == NO) {
  858. NSLog(@"[LOG] Request Service Server Nextcloud");
  859. [[NCService sharedInstance] startRequestServicesServer];
  860. }
  861. NSLog(@"[LOG] Reachability Changed: Reachable");
  862. self.lastReachability = YES;
  863. } else {
  864. if (self.lastReachability == YES) {
  865. [[NCContentPresenter shared] messageNotification:@"_network_not_available_" description:nil delay:k_dismissAfterSecond type:messageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  866. }
  867. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  868. self.lastReachability = NO;
  869. }
  870. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  871. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  872. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  873. }
  874. #pragma --------------------------------------------------------------------------------------------
  875. #pragma mark ===== Fetch =====
  876. #pragma --------------------------------------------------------------------------------------------
  877. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  878. {
  879. // Test Maintenance
  880. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  881. completionHandler(UIBackgroundFetchResultNoData);
  882. return;
  883. }
  884. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  885. // Verify new photo
  886. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  887. // after 20 sec
  888. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  889. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  890. if ([records count] > 0) {
  891. completionHandler(UIBackgroundFetchResultNewData);
  892. } else {
  893. completionHandler(UIBackgroundFetchResultNoData);
  894. }
  895. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  896. });
  897. }
  898. #pragma --------------------------------------------------------------------------------------------
  899. #pragma mark ===== Operation Networking & Session =====
  900. #pragma --------------------------------------------------------------------------------------------
  901. //
  902. // Method called by the system when all the background task has end
  903. //
  904. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  905. {
  906. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  907. // after 20 sec
  908. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  909. self.backgroundSessionCompletionHandler = completionHandler;
  910. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  911. self.backgroundSessionCompletionHandler = nil;
  912. completionHandler();
  913. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  914. });
  915. }
  916. #pragma --------------------------------------------------------------------------------------------
  917. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  918. #pragma --------------------------------------------------------------------------------------------
  919. - (void)loadAutoDownloadUpload
  920. {
  921. if (self.activeAccount.length == 0 || self.maintenanceMode)
  922. return;
  923. tableMetadata *metadataForUpload, *metadataForDownload;
  924. long counterDownload = 0, counterUpload = 0;
  925. NSUInteger sizeDownload = 0, sizeUpload = 0;
  926. BOOL isE2EE = false;
  927. NSMutableArray *uploaded = [NSMutableArray new];
  928. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  929. // Detect E2EE
  930. NSString *saveserverUrl = @"";
  931. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status != %d", k_metadataStatusNormal] sorted:@"serverUrl" ascending:NO];
  932. for (tableMetadata *metadata in metadatasForE2EE) {
  933. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  934. saveserverUrl = metadata.serverUrl;
  935. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  936. isE2EE = true;
  937. break;
  938. }
  939. }
  940. }
  941. // E2EE : not in background
  942. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  943. return;
  944. }
  945. // E2EE : only 1 operation
  946. if (isE2EE) {
  947. maxConcurrentOperationDownloadUpload = 1;
  948. }
  949. // Stop Timer
  950. [_timerProcessAutoDownloadUpload invalidate];
  951. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  952. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  953. // Counter
  954. counterDownload = [metadatasDownload count];
  955. counterUpload = [metadatasUpload count];
  956. // Size
  957. for (tableMetadata *metadata in metadatasDownload) {
  958. sizeDownload = sizeDownload + metadata.size;
  959. }
  960. for (tableMetadata *metadata in metadatasUpload) {
  961. sizeUpload = sizeUpload + metadata.size;
  962. }
  963. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  964. // ------------------------- <selector Download> -------------------------
  965. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  966. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"date" ascending:YES];
  967. if (metadataForDownload) {
  968. metadataForDownload.status = k_metadataStatusInDownload;
  969. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  970. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  971. counterDownload++;
  972. sizeDownload = sizeDownload + metadata.size;
  973. } else {
  974. break;
  975. }
  976. }
  977. // ------------------------- <selector Upload> -------------------------
  978. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  979. if (sizeUpload > k_maxSizeOperationUpload) {
  980. break;
  981. }
  982. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload] sorted:@"date" ascending:YES];
  983. // Verify modify file
  984. if ([uploaded containsObject:[NSString stringWithFormat:@"%@%@%@", metadataForUpload.account, metadataForUpload.serverUrl, metadataForUpload.fileName]]) {
  985. break;
  986. }
  987. if (metadataForUpload) {
  988. // Verify modify file
  989. BOOL isAleadyInUpload = false;
  990. for (tableMetadata *metadata in metadatasUpload) {
  991. if ([metadataForUpload.account isEqualToString:metadata.account] && [metadataForUpload.serverUrl isEqualToString:metadata.serverUrl] && [metadataForUpload.fileName isEqualToString:metadata.fileName]) {
  992. isAleadyInUpload = true;
  993. }
  994. }
  995. if (isAleadyInUpload == false) {
  996. metadataForUpload.status = k_metadataStatusInUpload;
  997. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  998. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  999. counterUpload++;
  1000. sizeUpload = sizeUpload + metadata.size;
  1001. // For verify modify file
  1002. [uploaded addObject:[NSString stringWithFormat:@"%@%@%@", metadata.account, metadata.serverUrl, metadata.fileName]];
  1003. } else {
  1004. break;
  1005. }
  1006. } else {
  1007. break;
  1008. }
  1009. }
  1010. // ------------------------- <selector Auto Upload> -------------------------
  1011. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1012. if (sizeUpload > k_maxSizeOperationUpload) {
  1013. break;
  1014. }
  1015. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload] sorted:@"date" ascending:YES];
  1016. if (metadataForUpload) {
  1017. metadataForUpload.status = k_metadataStatusInUpload;
  1018. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1019. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1020. counterUpload++;
  1021. sizeUpload = sizeUpload + metadata.size;
  1022. } else {
  1023. break;
  1024. }
  1025. }
  1026. // ------------------------- <selector Auto Upload All> ----------------------
  1027. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1028. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:@"date" ascending:YES];
  1029. NSInteger errorCount = [metadatas count];
  1030. if (errorCount >= k_maxErrorAutoUploadAll) {
  1031. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_too_errors_automatic_all_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1032. } else {
  1033. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1034. if (sizeUpload > k_maxSizeOperationUpload) {
  1035. break;
  1036. }
  1037. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1038. if (metadataForUpload) {
  1039. metadataForUpload.status = k_metadataStatusInUpload;
  1040. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1041. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1042. counterUpload++;
  1043. sizeUpload = sizeUpload + metadata.size;
  1044. } else {
  1045. break;
  1046. }
  1047. }
  1048. }
  1049. // No Download/upload available ? --> remove errors for retry
  1050. //
  1051. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1052. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1053. for (tableMetadata *metadata in metadatas) {
  1054. if (metadata.status == k_metadataStatusDownloadError)
  1055. metadata.status = k_metadataStatusWaitDownload;
  1056. else if (metadata.status == k_metadataStatusUploadError)
  1057. metadata.status = k_metadataStatusWaitUpload;
  1058. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1059. }
  1060. }
  1061. // Verify internal error download (lost task)
  1062. //
  1063. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusDownloading] sorted:nil ascending:true];
  1064. for (tableMetadata *metadata in matadatasInDownloading) {
  1065. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1066. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1067. NSURLSessionTask *findTask;
  1068. for (NSURLSessionTask *task in downloadTasks) {
  1069. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1070. findTask = task;
  1071. }
  1072. }
  1073. if (!findTask) {
  1074. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1075. metadata.status = k_metadataStatusWaitDownload;
  1076. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1077. }
  1078. }];
  1079. }
  1080. // Verify internal error upload (lost task)
  1081. //
  1082. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1083. for (tableMetadata *metadata in metadatasUploading) {
  1084. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1085. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1086. NSURLSessionTask *findTask;
  1087. for (NSURLSessionTask *task in uploadTasks) {
  1088. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1089. findTask = task;
  1090. }
  1091. }
  1092. if (!findTask) {
  1093. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1094. metadata.status = k_metadataStatusWaitUpload;
  1095. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1096. }
  1097. }];
  1098. }
  1099. // Upload in pending
  1100. //
  1101. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1102. for (tableMetadata *metadata in metadatasInUpload) {
  1103. if ([self.sessionPendingStatusInUpload containsObject:metadata.ocId]) {
  1104. metadata.status = k_metadataStatusWaitUpload;
  1105. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1106. } else {
  1107. [self.sessionPendingStatusInUpload addObject:metadata.ocId];
  1108. }
  1109. }
  1110. if (metadatasInUpload.count == 0) {
  1111. [self.sessionPendingStatusInUpload removeAllObjects];
  1112. }
  1113. // Start Timer
  1114. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1115. }
  1116. - (void)startLoadAutoDownloadUpload
  1117. {
  1118. if (self.timerProcessAutoDownloadUpload.isValid) {
  1119. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1120. }
  1121. }
  1122. #pragma --------------------------------------------------------------------------------------------
  1123. #pragma mark ===== OpenURL =====
  1124. #pragma --------------------------------------------------------------------------------------------
  1125. // Method called from iOS system to send a file from other app.
  1126. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1127. {
  1128. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1129. return YES;
  1130. NSString *scheme = url.scheme;
  1131. dispatch_time_t timer = 0;
  1132. if (self.activeMain == nil) timer = 1;
  1133. if ([scheme isEqualToString:@"nextcloud"]) {
  1134. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1135. NSString *action = url.host;
  1136. if ([action isEqualToString:@"open-file"]) {
  1137. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1138. NSArray *queryItems = urlComponents.queryItems;
  1139. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1140. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1141. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1142. tableAccount *matchedAccount = nil;
  1143. // verify parameter
  1144. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1145. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1146. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1147. [alertController addAction:okAction];
  1148. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1149. } else {
  1150. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1151. if (account) {
  1152. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1153. NSString *activeAccountUser = account.user;
  1154. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1155. matchedAccount = account;
  1156. } else {
  1157. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1158. for (tableAccount *account in accounts) {
  1159. NSURL *accountURL = [NSURL URLWithString:account.url];
  1160. NSString *accountUser = account.user;
  1161. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1162. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1163. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1164. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1165. }
  1166. }
  1167. }
  1168. if (matchedAccount) {
  1169. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1170. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1171. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1172. if (splitViewController.isCollapsed) {
  1173. [navigationControllerMaster popToRootViewControllerAnimated:false];
  1174. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1175. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1176. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1177. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1178. }
  1179. } else {
  1180. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1181. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1182. }
  1183. }
  1184. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1185. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1186. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1187. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1188. if ([path containsString:@"/"]) {
  1189. // Push
  1190. NSString *directoryName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1191. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1192. tableMetadata *metadata = [CCUtility createMetadataWithAccount:matchedAccount.account date:[NSDate date] directory:NO ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl fileName:directoryName etag:@"" size:0 status:k_metadataStatusNormal url:@"" contentType:@""];
  1193. [self.activeMain performSegueDirectoryWithControlPasscode:true metadata:metadata blinkFileNamePath:fileNamePath];
  1194. } else {
  1195. // Reload folder
  1196. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1197. self.activeMain.blinkFileNamePath = fileNamePath;
  1198. [self.activeMain readFolder:serverUrl];
  1199. }
  1200. });
  1201. });
  1202. } else {
  1203. NSString *domain = [[NSURL URLWithString:link] host];
  1204. NSString *fileName = [path lastPathComponent];
  1205. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1206. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1207. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1208. [alertController addAction:okAction];
  1209. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1210. }
  1211. }
  1212. }
  1213. }
  1214. });
  1215. return YES;
  1216. }
  1217. NSError *error;
  1218. NSLog(@"[LOG] the path is: %@", url.path);
  1219. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1220. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1221. if (self.activeAccount) {
  1222. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1223. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1224. if (error == nil) {
  1225. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1226. UINavigationController *navigationController = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1227. UIViewController *uploadNavigationViewController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1228. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1229. [navigationController presentViewController:uploadNavigationViewController animated:YES completion:nil];
  1230. });
  1231. }
  1232. }
  1233. return YES;
  1234. }
  1235. #pragma --------------------------------------------------------------------------------------------
  1236. #pragma mark ===== Maintenance Mode =====
  1237. #pragma --------------------------------------------------------------------------------------------
  1238. - (void)maintenanceMode:(BOOL)mode
  1239. {
  1240. self.maintenanceMode = mode;
  1241. }
  1242. #pragma --------------------------------------------------------------------------------------------
  1243. #pragma mark ===== UPGRADE =====
  1244. #pragma --------------------------------------------------------------------------------------------
  1245. - (BOOL)upgrade
  1246. {
  1247. #ifdef DEBUG
  1248. //self.maintenanceMode = YES;
  1249. #endif
  1250. NSString *actualVersion = [CCUtility getVersion];
  1251. NSString *actualBuild = [CCUtility getBuild];
  1252. /* ---------------------- UPGRADE VERSION ----------------------- */
  1253. // VERSION < 2.17.6
  1254. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1255. // Remove All old Photo Library
  1256. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1257. }
  1258. // VERSION == 2.17.6
  1259. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1260. // Build < 10
  1261. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1262. // Remove All old Photo Library
  1263. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1264. }
  1265. }
  1266. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1267. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1268. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1269. }
  1270. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1271. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1272. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1273. NSString *account = @"";
  1274. NSString *directoryUser = @"";
  1275. NSString *fileName;
  1276. for (tableLocalFile *record in records) {
  1277. if (![account isEqualToString:record.account]) {
  1278. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1279. if (tableAccount) {
  1280. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1281. account = record.account;
  1282. }
  1283. }
  1284. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.ocId];
  1285. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1286. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageOcId:record.ocId fileNameView:record.fileName]];
  1287. }
  1288. }
  1289. });
  1290. }
  1291. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1292. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1293. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1294. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1295. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1296. }
  1297. }
  1298. if (([actualVersion compare:@"2.23.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1299. NSArray *records = [[NCManageDatabase sharedInstance] getAllAccount];
  1300. for (tableAccount *record in records) {
  1301. [CCUtility setPassword:record.account password:record.password];
  1302. [[NCManageDatabase sharedInstance] removePasswordAccount:record.account];
  1303. }
  1304. }
  1305. return YES;
  1306. }
  1307. @end