AppDelegate.m 82 KB

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