AppDelegate.m 91 KB

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