AppDelegate.m 91 KB

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