AppDelegate.m 93 KB

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