AppDelegate.m 93 KB

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