AppDelegate.m 88 KB

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