AppDelegate.m 84 KB

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