AppDelegate.m 84 KB

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