AppDelegate.m 91 KB

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