AppDelegate.m 91 KB

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