AppDelegate.m 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720
  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 "CCDetail.h"
  29. #import <Fabric/Fabric.h>
  30. #import <Crashlytics/Crashlytics.h>
  31. #import "NCBridgeSwift.h"
  32. #import "NCAutoUpload.h"
  33. #import "NCPushNotificationEncryption.h"
  34. @class NCViewerRichdocument;
  35. @implementation AppDelegate
  36. + (void)initialize
  37. {
  38. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  39. }
  40. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  41. {
  42. [CCUtility createDirectoryStandard];
  43. // Networking
  44. [[NCCommunicationCommon sharedInstance] setupWithUserAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups delegate:[NCNetworking sharedInstance]];
  45. // Verify upgrade
  46. if ([self upgrade]) {
  47. // Set account, if no exists clear all
  48. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  49. if (tableAccount == nil) {
  50. // remove all the keys Chain
  51. [CCUtility deleteAllChainStore];
  52. // remove all the App group key
  53. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  54. } else {
  55. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  56. }
  57. }
  58. // UserDefaults
  59. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  60. // Filter ocId
  61. self.filterocId = [NSMutableArray new];
  62. // Upload Pending In Upload (crash)
  63. self.sessionPendingStatusInUpload = [NSMutableArray new];
  64. // Initialization Notification
  65. self.listOfNotifications = [NSMutableArray new];
  66. // Background Fetch
  67. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  68. // Initialization List
  69. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  70. self.listMainVC = [[NSMutableDictionary alloc] init];
  71. // Push Notification
  72. [application registerForRemoteNotifications];
  73. // Display notification (sent via APNS)
  74. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  75. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  76. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  77. }];
  78. // setting Reachable in back
  79. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  80. self.reachability = [Reachability reachabilityForInternetConnection];
  81. self.lastReachability = [self.reachability isReachable];
  82. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  83. [self.reachability startNotifier];
  84. });
  85. //AV Session
  86. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  87. // [[AVAudioSession sharedInstance] setActive:YES error:nil];
  88. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  89. // APPEARANCE: How to hide UINavigationBar 1px bottom line < iOS 11
  90. [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
  91. [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
  92. [UINavigationBar appearance].translucent = NO;
  93. // passcode
  94. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  95. dispatch_async(dispatch_get_main_queue(), ^{
  96. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  97. });
  98. // Quick Actions
  99. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  100. [self configDynamicShortcutItems];
  101. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  102. if (shortcutItem)
  103. [self handleShortCutItem:shortcutItem];
  104. }
  105. // Start Timer
  106. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  107. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  108. [self startTimerErrorNetworking];
  109. // Fabric
  110. if (![CCUtility getDisableCrashservice] && NCBrandOptions.sharedInstance.disable_crash_service == false) {
  111. [Fabric with:@[[Crashlytics class]]];
  112. }
  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:@"initializeMain" object:nil userInfo:nil];
  144. return YES;
  145. }
  146. //
  147. // L' applicazione si dimetterà dallo stato di attivo
  148. //
  149. - (void)applicationWillResignActive:(UIApplication *)application
  150. {
  151. // Test Maintenance
  152. if (self.activeAccount.length == 0 || self.maintenanceMode)
  153. return;
  154. [self updateApplicationIconBadgeNumber];
  155. }
  156. //
  157. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  158. //
  159. - (void)applicationWillEnterForeground:(UIApplication *)application
  160. {
  161. // Test Maintenance
  162. if (self.activeAccount.length == 0 || self.maintenanceMode)
  163. return;
  164. NSLog(@"[LOG] Request Service Server Nextcloud");
  165. [[NCService sharedInstance] startRequestServicesServer];
  166. NSLog(@"[LOG] Initialize Auto upload");
  167. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  168. NSLog(@"[LOG] Read active directory");
  169. [self.activeMain readFileReloadFolder];
  170. NSLog(@"[LOG] Required unsubscribing / subscribing");
  171. [self pushNotification];
  172. NSLog(@"[LOG] RichDocument");
  173. if (self.activeDetail.richDocument) {
  174. [self.activeDetail.richDocument grabFocus];
  175. }
  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:@"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 ===== Quick Actions - ShotcutItem =====
  522. #pragma --------------------------------------------------------------------------------------------
  523. - (void)configDynamicShortcutItems
  524. {
  525. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  526. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  527. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  528. // add the array to our app
  529. if (shortcutMedia)
  530. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  531. }
  532. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  533. {
  534. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  535. completionHandler(handledShortCutItem);
  536. }
  537. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  538. {
  539. BOOL handled = NO;
  540. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  541. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  542. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  543. dispatch_async(dispatch_get_main_queue(), ^{
  544. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  545. if (splitViewController.isCollapsed) {
  546. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  547. for (UINavigationController *nvc in tbc.viewControllers) {
  548. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  549. [nvc popToRootViewControllerAnimated:NO];
  550. }
  551. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  552. } else {
  553. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  554. [nvcDetail popToRootViewControllerAnimated:NO];
  555. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  556. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  557. }
  558. });
  559. handled = YES;
  560. }
  561. return handled;
  562. }
  563. #pragma --------------------------------------------------------------------------------------------
  564. #pragma mark ===== ApplicationIconBadgeNumber =====
  565. #pragma --------------------------------------------------------------------------------------------
  566. - (void)updateApplicationIconBadgeNumber
  567. {
  568. if (self.activeAccount.length == 0 || self.maintenanceMode)
  569. return;
  570. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  571. 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];
  572. 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];
  573. NSInteger total = counterDownload + counterUpload;
  574. dispatch_async(dispatch_get_main_queue(), ^{
  575. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  576. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  577. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  578. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  579. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  580. if (total > 0) {
  581. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  582. } else {
  583. [tbItem setBadgeValue:nil];
  584. }
  585. }
  586. });
  587. });
  588. }
  589. #pragma --------------------------------------------------------------------------------------------
  590. #pragma mark ===== TabBarController =====
  591. #pragma --------------------------------------------------------------------------------------------
  592. - (void)createTabBarController:(UITabBarController *)tabBarController
  593. {
  594. UITabBarItem *item;
  595. NSLayoutConstraint *constraint;
  596. CGFloat safeAreaBottom = 0;
  597. if (@available(iOS 11, *)) {
  598. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  599. }
  600. // File
  601. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  602. [item setTitle:NSLocalizedString(@"_home_", nil)];
  603. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  604. item.selectedImage = item.image;
  605. // Favorites
  606. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  607. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  608. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  609. item.selectedImage = item.image;
  610. // (PLUS INVISIBLE)
  611. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  612. item.title = @"";
  613. item.image = nil;
  614. item.enabled = false;
  615. // Media
  616. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  617. [item setTitle:NSLocalizedString(@"_media_", nil)];
  618. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  619. item.selectedImage = item.image;
  620. // More
  621. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  622. [item setTitle:NSLocalizedString(@"_more_", nil)];
  623. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] width:50 height:50 color:NCBrandColor.sharedInstance.brandElement];
  624. item.selectedImage = item.image;
  625. // Plus Button
  626. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] width:120 height:120 color:NCBrandColor.sharedInstance.brandElement];
  627. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  628. buttonPlus.tag = 99;
  629. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  630. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  631. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  632. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  633. [tabBarController.tabBar addSubview:buttonPlus];
  634. if (safeAreaBottom > 0) {
  635. // X
  636. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  637. [tabBarController.view addConstraint:constraint];
  638. // Y
  639. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:5];
  640. [tabBarController.view addConstraint:constraint];
  641. // Width
  642. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:40];
  643. [tabBarController.view addConstraint:constraint];
  644. // Height
  645. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:40];
  646. [tabBarController.view addConstraint:constraint];
  647. } else {
  648. // X
  649. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  650. [tabBarController.view addConstraint:constraint];
  651. // Y
  652. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
  653. [tabBarController.view addConstraint:constraint];
  654. // Width
  655. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:33];
  656. [tabBarController.view addConstraint:constraint];
  657. // Height
  658. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:33];
  659. [tabBarController.view addConstraint:constraint];
  660. }
  661. }
  662. - (void)handleTouchTabbarCenter:(id)sender
  663. {
  664. // Test Maintenance
  665. if (self.maintenanceMode)
  666. return;
  667. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, self.activeMain.serverUrl]];
  668. if ([tableDirectory.permissions containsString:@"CK"]) {
  669. UIViewController *vc = _activeMain.splitViewController.viewControllers[0];
  670. [self showMenuInViewController: vc];
  671. } else {
  672. [[NCContentPresenter shared] messageNotification:@"_warning_" description:@"_no_permission_add_file_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  673. }
  674. }
  675. - (void)selectedTabBarController:(NSInteger)index
  676. {
  677. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  678. if (splitViewController.isCollapsed) {
  679. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  680. for (UINavigationController *nvc in tbc.viewControllers) {
  681. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  682. [nvc popToRootViewControllerAnimated:NO];
  683. }
  684. [tbc setSelectedIndex: index];
  685. } else {
  686. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  687. [nvcDetail popToRootViewControllerAnimated:NO];
  688. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  689. [tbc setSelectedIndex: index];
  690. }
  691. }
  692. - (NSString *)getTabBarControllerActiveServerUrl
  693. {
  694. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  695. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  696. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  697. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  698. NSInteger index = tabBarController.selectedIndex;
  699. // select active serverUrl
  700. if (index == k_tabBarApplicationIndexFile) {
  701. serverUrl = self.activeMain.serverUrl;
  702. } else if (index == k_tabBarApplicationIndexFavorite) {
  703. if (self.activeFavorites.serverUrl)
  704. serverUrl = self.activeFavorites.serverUrl;
  705. } else if (index == k_tabBarApplicationIndexMedia) {
  706. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  707. }
  708. return serverUrl;
  709. }
  710. #pragma --------------------------------------------------------------------------------------------
  711. #pragma mark ===== Theming Color =====
  712. #pragma --------------------------------------------------------------------------------------------
  713. - (void)settingThemingColorBrand
  714. {
  715. if (self.activeAccount.length == 0 || self.maintenanceMode)
  716. return;
  717. if ([NCBrandOptions sharedInstance].use_themingColor) {
  718. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  719. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  720. } else {
  721. NCBrandColor.sharedInstance.brand = NCBrandColor.sharedInstance.customer;
  722. NCBrandColor.sharedInstance.brandElement = NCBrandColor.sharedInstance.customer;
  723. NCBrandColor.sharedInstance.brandText = NCBrandColor.sharedInstance.customerText;
  724. }
  725. [[NCMainCommon sharedInstance] createImagesThemingColor];
  726. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  727. }
  728. - (void)changeTheming:(UIViewController *)viewController tableView:(UITableView *)tableView collectionView:(UICollectionView *)collectionView form:(BOOL)form
  729. {
  730. // Dark Mode
  731. [NCBrandColor.sharedInstance setDarkMode];
  732. // View
  733. if (form) viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  734. else viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  735. // NavigationBar
  736. if (viewController.navigationController.navigationBar) {
  737. viewController.navigationController.navigationBar.translucent = NO;
  738. viewController.navigationController.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand;
  739. viewController.navigationController.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText;
  740. if ([self.reachability isReachable]) {
  741. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.brandText}];
  742. } else {
  743. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.connectionNo}];
  744. }
  745. viewController.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:NCBrandColor.sharedInstance.brand];
  746. [viewController.navigationController.navigationBar setAlpha:1];
  747. }
  748. //tabBar
  749. if (viewController.tabBarController.tabBar) {
  750. viewController.tabBarController.tabBar.translucent = NO;
  751. viewController.tabBarController.tabBar.barTintColor = NCBrandColor.sharedInstance.tabBar;
  752. viewController.tabBarController.tabBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  753. [viewController.tabBarController.tabBar setAlpha:1];
  754. }
  755. //tabBar button Plus
  756. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  757. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  758. UIButton *button = [tabBarController.view viewWithTag:99];
  759. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:NCBrandColor.sharedInstance.brandElement];
  760. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  761. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  762. // TableView
  763. if (tableView) {
  764. if (form) tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  765. else tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  766. tableView.separatorColor = NCBrandColor.sharedInstance.separator;
  767. [tableView reloadData];
  768. }
  769. // CollectionView
  770. if (collectionView) {
  771. if (form) collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  772. else collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  773. [collectionView reloadData];
  774. }
  775. // Tint Color GLOBAL WINDOW
  776. [self.window setTintColor:NCBrandColor.sharedInstance.textView];
  777. }
  778. #pragma --------------------------------------------------------------------------------------------
  779. #pragma mark ===== Manager Passcode =====
  780. #pragma --------------------------------------------------------------------------------------------
  781. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  782. {
  783. // ServerUrl active
  784. NSString *serverUrl = self.activeMain.serverUrl;
  785. BOOL isBlockZone = false;
  786. // fermiamo la data della sessione
  787. self.sessionePasscodeLock = nil;
  788. // se il block code è a zero esci con NON attivare la richiesta password
  789. if ([[CCUtility getBlockCode] length] == 0) return NO;
  790. // se non c'è attivo un account esci con NON attivare la richiesta password
  791. if ([self.activeAccount length] == 0) return NO;
  792. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  793. if (serverUrl && _activeUrl) {
  794. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  795. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  796. if (directory.lock) {
  797. isBlockZone = true;
  798. break;
  799. } else {
  800. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  801. if (serverUrl == self.activeUrl)
  802. break;
  803. }
  804. }
  805. }
  806. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  807. return YES;
  808. }
  809. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  810. {
  811. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  812. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  813. viewController.delegate = self;
  814. viewController.title = [NCBrandOptions sharedInstance].brand;
  815. viewController.fromType = CCBKPasscodeFromLockScreen;
  816. viewController.inputViewTitlePassword = YES;
  817. if ([CCUtility getSimplyBlockCode]) {
  818. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  819. viewController.passcodeInputView.maximumLength = 6;
  820. } else {
  821. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  822. viewController.passcodeInputView.maximumLength = 64;
  823. }
  824. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  825. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  826. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  827. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  828. return navigationController;
  829. }
  830. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  831. {
  832. [aViewController dismissViewControllerAnimated:YES completion:nil];
  833. // is a lock screen
  834. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  835. [aViewController dismissViewControllerAnimated:YES completion:nil];
  836. // start session Passcode Lock
  837. BOOL isBlockZone = false;
  838. NSString *serverUrl = self.activeMain.serverUrl;
  839. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  840. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  841. if (directory.lock) {
  842. isBlockZone = true;
  843. break;
  844. } else {
  845. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  846. if (serverUrl == self.activeUrl)
  847. break;
  848. }
  849. }
  850. if (isBlockZone)
  851. self.sessionePasscodeLock = [NSDate date];
  852. }
  853. }
  854. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  855. {
  856. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  857. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  858. //self.lockUntilDate = nil;
  859. //self.failedAttempts = 0;
  860. aResultHandler(YES);
  861. } else aResultHandler(NO);
  862. } else aResultHandler(YES);
  863. }
  864. #pragma --------------------------------------------------------------------------------------------
  865. #pragma mark ===== reachabilityChanged =====
  866. #pragma --------------------------------------------------------------------------------------------
  867. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  868. {
  869. if ([self.reachability isReachable]) {
  870. if (self.lastReachability == NO) {
  871. NSLog(@"[LOG] Request Service Server Nextcloud");
  872. [[NCService sharedInstance] startRequestServicesServer];
  873. }
  874. NSLog(@"[LOG] Reachability Changed: Reachable");
  875. self.lastReachability = YES;
  876. } else {
  877. if (self.lastReachability == YES) {
  878. [[NCContentPresenter shared] messageNotification:@"_network_not_available_" description:nil delay:k_dismissAfterSecond type:messageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  879. }
  880. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  881. self.lastReachability = NO;
  882. }
  883. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  884. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  885. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  886. }
  887. #pragma --------------------------------------------------------------------------------------------
  888. #pragma mark ===== Fetch =====
  889. #pragma --------------------------------------------------------------------------------------------
  890. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  891. {
  892. // Test Maintenance
  893. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  894. completionHandler(UIBackgroundFetchResultNoData);
  895. return;
  896. }
  897. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  898. // Verify new photo
  899. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  900. // after 20 sec
  901. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  902. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  903. if ([records count] > 0) {
  904. completionHandler(UIBackgroundFetchResultNewData);
  905. } else {
  906. completionHandler(UIBackgroundFetchResultNoData);
  907. }
  908. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  909. });
  910. }
  911. #pragma --------------------------------------------------------------------------------------------
  912. #pragma mark ===== Operation Networking & Session =====
  913. #pragma --------------------------------------------------------------------------------------------
  914. //
  915. // Method called by the system when all the background task has end
  916. //
  917. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  918. {
  919. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  920. // after 20 sec
  921. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  922. self.backgroundSessionCompletionHandler = completionHandler;
  923. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  924. self.backgroundSessionCompletionHandler = nil;
  925. completionHandler();
  926. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  927. });
  928. }
  929. #pragma --------------------------------------------------------------------------------------------
  930. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  931. #pragma --------------------------------------------------------------------------------------------
  932. - (void)loadAutoDownloadUpload
  933. {
  934. if (self.activeAccount.length == 0 || self.maintenanceMode)
  935. return;
  936. tableMetadata *metadataForUpload, *metadataForDownload;
  937. long counterDownload = 0, counterUpload = 0;
  938. NSUInteger sizeDownload = 0, sizeUpload = 0;
  939. BOOL isE2EE = false;
  940. NSMutableArray *uploaded = [NSMutableArray new];
  941. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  942. // Detect E2EE
  943. NSString *saveserverUrl = @"";
  944. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status != %d", k_metadataStatusNormal] sorted:@"serverUrl" ascending:NO];
  945. for (tableMetadata *metadata in metadatasForE2EE) {
  946. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  947. saveserverUrl = metadata.serverUrl;
  948. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  949. isE2EE = true;
  950. break;
  951. }
  952. }
  953. }
  954. // E2EE : not in background
  955. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  956. return;
  957. }
  958. // E2EE : only 1 operation
  959. if (isE2EE) {
  960. maxConcurrentOperationDownloadUpload = 1;
  961. }
  962. // Stop Timer
  963. [_timerProcessAutoDownloadUpload invalidate];
  964. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  965. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  966. // Counter
  967. counterDownload = [metadatasDownload count];
  968. counterUpload = [metadatasUpload count];
  969. // Size
  970. for (tableMetadata *metadata in metadatasDownload) {
  971. sizeDownload = sizeDownload + metadata.size;
  972. }
  973. for (tableMetadata *metadata in metadatasUpload) {
  974. sizeUpload = sizeUpload + metadata.size;
  975. }
  976. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  977. // ------------------------- <selector Download> -------------------------
  978. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  979. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"date" ascending:YES];
  980. if (metadataForDownload) {
  981. metadataForDownload.status = k_metadataStatusInDownload;
  982. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  983. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  984. counterDownload++;
  985. sizeDownload = sizeDownload + metadata.size;
  986. } else {
  987. break;
  988. }
  989. }
  990. // ------------------------- <selector Upload> -------------------------
  991. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  992. if (sizeUpload > k_maxSizeOperationUpload) {
  993. break;
  994. }
  995. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload] sorted:@"date" ascending:YES];
  996. // Verify modify file
  997. if ([uploaded containsObject:[NSString stringWithFormat:@"%@%@%@", metadataForUpload.account, metadataForUpload.serverUrl, metadataForUpload.fileName]]) {
  998. break;
  999. }
  1000. if (metadataForUpload) {
  1001. // Verify modify file
  1002. BOOL isAleadyInUpload = false;
  1003. for (tableMetadata *metadata in metadatasUpload) {
  1004. if ([metadataForUpload.account isEqualToString:metadata.account] && [metadataForUpload.serverUrl isEqualToString:metadata.serverUrl] && [metadataForUpload.fileName isEqualToString:metadata.fileName]) {
  1005. isAleadyInUpload = true;
  1006. }
  1007. }
  1008. if (isAleadyInUpload == false) {
  1009. metadataForUpload.status = k_metadataStatusInUpload;
  1010. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1011. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1012. counterUpload++;
  1013. sizeUpload = sizeUpload + metadata.size;
  1014. // For verify modify file
  1015. [uploaded addObject:[NSString stringWithFormat:@"%@%@%@", metadata.account, metadata.serverUrl, metadata.fileName]];
  1016. } else {
  1017. break;
  1018. }
  1019. } else {
  1020. break;
  1021. }
  1022. }
  1023. // ------------------------- <selector Auto Upload> -------------------------
  1024. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1025. if (sizeUpload > k_maxSizeOperationUpload) {
  1026. break;
  1027. }
  1028. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload] sorted:@"date" ascending:YES];
  1029. if (metadataForUpload) {
  1030. metadataForUpload.status = k_metadataStatusInUpload;
  1031. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1032. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1033. counterUpload++;
  1034. sizeUpload = sizeUpload + metadata.size;
  1035. } else {
  1036. break;
  1037. }
  1038. }
  1039. // ------------------------- <selector Auto Upload All> ----------------------
  1040. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1041. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:@"date" ascending:YES];
  1042. NSInteger errorCount = [metadatas count];
  1043. if (errorCount >= k_maxErrorAutoUploadAll) {
  1044. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_too_errors_automatic_all_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1045. } else {
  1046. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1047. if (sizeUpload > k_maxSizeOperationUpload) {
  1048. break;
  1049. }
  1050. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1051. if (metadataForUpload) {
  1052. metadataForUpload.status = k_metadataStatusInUpload;
  1053. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1054. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1055. counterUpload++;
  1056. sizeUpload = sizeUpload + metadata.size;
  1057. } else {
  1058. break;
  1059. }
  1060. }
  1061. }
  1062. // No Download/upload available ? --> remove errors for retry
  1063. //
  1064. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1065. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1066. for (tableMetadata *metadata in metadatas) {
  1067. if (metadata.status == k_metadataStatusDownloadError)
  1068. metadata.status = k_metadataStatusWaitDownload;
  1069. else if (metadata.status == k_metadataStatusUploadError)
  1070. metadata.status = k_metadataStatusWaitUpload;
  1071. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1072. }
  1073. }
  1074. // Verify internal error download (lost task)
  1075. //
  1076. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusDownloading] sorted:nil ascending:true];
  1077. for (tableMetadata *metadata in matadatasInDownloading) {
  1078. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1079. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1080. NSURLSessionTask *findTask;
  1081. for (NSURLSessionTask *task in downloadTasks) {
  1082. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1083. findTask = task;
  1084. }
  1085. }
  1086. if (!findTask) {
  1087. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1088. metadata.status = k_metadataStatusWaitDownload;
  1089. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1090. }
  1091. }];
  1092. }
  1093. // Verify internal error upload (lost task)
  1094. //
  1095. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1096. for (tableMetadata *metadata in metadatasUploading) {
  1097. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1098. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1099. NSURLSessionTask *findTask;
  1100. for (NSURLSessionTask *task in uploadTasks) {
  1101. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1102. findTask = task;
  1103. }
  1104. }
  1105. if (!findTask) {
  1106. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1107. metadata.status = k_metadataStatusWaitUpload;
  1108. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1109. }
  1110. }];
  1111. }
  1112. // Upload in pending
  1113. //
  1114. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1115. for (tableMetadata *metadata in metadatasInUpload) {
  1116. if ([self.sessionPendingStatusInUpload containsObject:metadata.ocId]) {
  1117. metadata.status = k_metadataStatusWaitUpload;
  1118. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1119. } else {
  1120. [self.sessionPendingStatusInUpload addObject:metadata.ocId];
  1121. }
  1122. }
  1123. if (metadatasInUpload.count == 0) {
  1124. [self.sessionPendingStatusInUpload removeAllObjects];
  1125. }
  1126. // Start Timer
  1127. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1128. }
  1129. - (void)startLoadAutoDownloadUpload
  1130. {
  1131. if (self.timerProcessAutoDownloadUpload.isValid) {
  1132. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1133. }
  1134. }
  1135. #pragma --------------------------------------------------------------------------------------------
  1136. #pragma mark ===== OpenURL =====
  1137. #pragma --------------------------------------------------------------------------------------------
  1138. // Method called from iOS system to send a file from other app.
  1139. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1140. {
  1141. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1142. return YES;
  1143. NSString *scheme = url.scheme;
  1144. dispatch_time_t timer = 0;
  1145. if (self.activeMain == nil) timer = 1;
  1146. if ([scheme isEqualToString:@"nextcloud"]) {
  1147. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1148. NSString *action = url.host;
  1149. if ([action isEqualToString:@"open-file"]) {
  1150. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1151. NSArray *queryItems = urlComponents.queryItems;
  1152. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1153. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1154. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1155. tableAccount *matchedAccount = nil;
  1156. // verify parameter
  1157. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1158. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1159. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1160. [alertController addAction:okAction];
  1161. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1162. } else {
  1163. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1164. if (account) {
  1165. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1166. NSString *activeAccountUser = account.user;
  1167. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1168. matchedAccount = account;
  1169. } else {
  1170. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1171. for (tableAccount *account in accounts) {
  1172. NSURL *accountURL = [NSURL URLWithString:account.url];
  1173. NSString *accountUser = account.user;
  1174. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1175. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1176. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1177. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1178. }
  1179. }
  1180. }
  1181. if (matchedAccount) {
  1182. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1183. UITabBarController *tbc;
  1184. if (splitViewController.isCollapsed) {
  1185. tbc = splitViewController.viewControllers.firstObject;
  1186. for (UINavigationController *nvc in tbc.viewControllers) {
  1187. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  1188. [nvc popToRootViewControllerAnimated:NO];
  1189. }
  1190. } else {
  1191. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  1192. [nvcDetail popToRootViewControllerAnimated:NO];
  1193. tbc = splitViewController.viewControllers.firstObject;
  1194. }
  1195. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1196. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  1197. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1198. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1199. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1200. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1201. if ([path containsString:@"/"]) {
  1202. // Push
  1203. NSString *directoryName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1204. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1205. 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:@""];
  1206. [self.activeMain performSegueDirectoryWithControlPasscode:true metadata:metadata blinkFileNamePath:fileNamePath];
  1207. } else {
  1208. // Reload folder
  1209. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1210. self.activeMain.blinkFileNamePath = fileNamePath;
  1211. [self.activeMain readFolder:serverUrl];
  1212. }
  1213. });
  1214. });
  1215. });
  1216. } else {
  1217. NSString *domain = [[NSURL URLWithString:link] host];
  1218. NSString *fileName = [path lastPathComponent];
  1219. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1220. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1221. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1222. [alertController addAction:okAction];
  1223. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1224. }
  1225. }
  1226. }
  1227. }
  1228. });
  1229. return YES;
  1230. }
  1231. NSError *error;
  1232. NSLog(@"[LOG] the path is: %@", url.path);
  1233. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1234. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1235. if (self.activeAccount) {
  1236. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1237. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1238. if (error == nil) {
  1239. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1240. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1241. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1242. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1243. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1244. });
  1245. }
  1246. }
  1247. return YES;
  1248. }
  1249. #pragma --------------------------------------------------------------------------------------------
  1250. #pragma mark ===== Maintenance Mode =====
  1251. #pragma --------------------------------------------------------------------------------------------
  1252. - (void)maintenanceMode:(BOOL)mode
  1253. {
  1254. self.maintenanceMode = mode;
  1255. }
  1256. #pragma --------------------------------------------------------------------------------------------
  1257. #pragma mark ===== UPGRADE =====
  1258. #pragma --------------------------------------------------------------------------------------------
  1259. - (BOOL)upgrade
  1260. {
  1261. #ifdef DEBUG
  1262. //self.maintenanceMode = YES;
  1263. #endif
  1264. NSString *actualVersion = [CCUtility getVersion];
  1265. NSString *actualBuild = [CCUtility getBuild];
  1266. /* ---------------------- UPGRADE VERSION ----------------------- */
  1267. // VERSION < 2.17.6
  1268. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1269. // Remove All old Photo Library
  1270. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1271. }
  1272. // VERSION == 2.17.6
  1273. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1274. // Build < 10
  1275. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1276. // Remove All old Photo Library
  1277. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1278. }
  1279. }
  1280. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1281. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1282. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1283. }
  1284. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1285. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1286. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1287. NSString *account = @"";
  1288. NSString *directoryUser = @"";
  1289. NSString *fileName;
  1290. for (tableLocalFile *record in records) {
  1291. if (![account isEqualToString:record.account]) {
  1292. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1293. if (tableAccount) {
  1294. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1295. account = record.account;
  1296. }
  1297. }
  1298. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.ocId];
  1299. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1300. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageOcId:record.ocId fileNameView:record.fileName]];
  1301. }
  1302. }
  1303. });
  1304. }
  1305. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1306. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1307. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1308. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1309. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1310. }
  1311. }
  1312. if (([actualVersion compare:@"2.23.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1313. NSArray *records = [[NCManageDatabase sharedInstance] getAllAccount];
  1314. for (tableAccount *record in records) {
  1315. [CCUtility setPassword:record.account password:record.password];
  1316. [[NCManageDatabase sharedInstance] removePasswordAccount:record.account];
  1317. }
  1318. }
  1319. return YES;
  1320. }
  1321. @end