AppDelegate.m 87 KB

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