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