AppDelegate.m 81 KB

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