AppDelegate.m 91 KB

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