AppDelegate.m 91 KB

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