AppDelegate.m 83 KB

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