AppDelegate.m 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744
  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)plusButtonVisibile:(BOOL)visible
  663. {
  664. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  665. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  666. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  667. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:NCBrandColor.sharedInstance.brandElement];
  668. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  669. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  670. if (buttonPlus) {
  671. if (visible) {
  672. buttonPlus.hidden = false;
  673. } else {
  674. buttonPlus.hidden = true;
  675. }
  676. }
  677. }
  678. - (void)handleTouchTabbarCenter:(id)sender
  679. {
  680. // Test Maintenance
  681. if (self.maintenanceMode)
  682. return;
  683. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, self.activeMain.serverUrl]];
  684. if ([tableDirectory.permissions containsString:@"CK"]) {
  685. UIViewController *vc = _activeMain.splitViewController.viewControllers[0];
  686. [self showMenuInViewController: vc];
  687. } else {
  688. [[NCContentPresenter shared] messageNotification:@"_warning_" description:@"_no_permission_add_file_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  689. }
  690. }
  691. - (void)selectedTabBarController:(NSInteger)index
  692. {
  693. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  694. if (splitViewController.isCollapsed) {
  695. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  696. for (UINavigationController *nvc in tbc.viewControllers) {
  697. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  698. [nvc popToRootViewControllerAnimated:NO];
  699. }
  700. [tbc setSelectedIndex: index];
  701. } else {
  702. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  703. [nvcDetail popToRootViewControllerAnimated:NO];
  704. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  705. [tbc setSelectedIndex: index];
  706. }
  707. }
  708. - (NSString *)getTabBarControllerActiveServerUrl
  709. {
  710. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  711. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  712. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  713. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  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. return serverUrl;
  725. }
  726. #pragma --------------------------------------------------------------------------------------------
  727. #pragma mark ===== Theming Color =====
  728. #pragma --------------------------------------------------------------------------------------------
  729. - (void)settingThemingColorBrand
  730. {
  731. if (self.activeAccount.length == 0 || self.maintenanceMode)
  732. return;
  733. if ([NCBrandOptions sharedInstance].use_themingColor) {
  734. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  735. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  736. } else {
  737. NCBrandColor.sharedInstance.brand = NCBrandColor.sharedInstance.customer;
  738. NCBrandColor.sharedInstance.brandElement = NCBrandColor.sharedInstance.customer;
  739. NCBrandColor.sharedInstance.brandText = NCBrandColor.sharedInstance.customerText;
  740. }
  741. [[NCMainCommon sharedInstance] createImagesThemingColor];
  742. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  743. }
  744. - (void)changeTheming:(UIViewController *)viewController tableView:(UITableView *)tableView collectionView:(UICollectionView *)collectionView form:(BOOL)form
  745. {
  746. // Dark Mode
  747. [NCBrandColor.sharedInstance setDarkMode];
  748. // View
  749. if (form) viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  750. else viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  751. // NavigationBar
  752. if (viewController.navigationController.navigationBar) {
  753. viewController.navigationController.navigationBar.translucent = NO;
  754. viewController.navigationController.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand;
  755. viewController.navigationController.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText;
  756. if ([self.reachability isReachable]) {
  757. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.brandText}];
  758. } else {
  759. [viewController.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : NCBrandColor.sharedInstance.connectionNo}];
  760. }
  761. viewController.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:NCBrandColor.sharedInstance.brand];
  762. [viewController.navigationController.navigationBar setAlpha:1];
  763. }
  764. //tabBar
  765. if (viewController.tabBarController.tabBar) {
  766. viewController.tabBarController.tabBar.translucent = NO;
  767. viewController.tabBarController.tabBar.barTintColor = NCBrandColor.sharedInstance.tabBar;
  768. viewController.tabBarController.tabBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  769. [viewController.tabBarController.tabBar setAlpha:1];
  770. }
  771. //tabBar button Plus
  772. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  773. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  774. UIButton *button = [tabBarController.view viewWithTag:99];
  775. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:NCBrandColor.sharedInstance.brandElement];
  776. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  777. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  778. // TableView
  779. if (tableView) {
  780. if (form) tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  781. else tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  782. tableView.separatorColor = NCBrandColor.sharedInstance.separator;
  783. [tableView reloadData];
  784. }
  785. // CollectionView
  786. if (collectionView) {
  787. if (form) collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  788. else collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  789. [collectionView reloadData];
  790. }
  791. // Tint Color GLOBAL WINDOW
  792. [self.window setTintColor:NCBrandColor.sharedInstance.textView];
  793. }
  794. #pragma --------------------------------------------------------------------------------------------
  795. #pragma mark ===== Manager Passcode =====
  796. #pragma --------------------------------------------------------------------------------------------
  797. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  798. {
  799. // ServerUrl active
  800. NSString *serverUrl = self.activeMain.serverUrl;
  801. BOOL isBlockZone = false;
  802. // fermiamo la data della sessione
  803. self.sessionePasscodeLock = nil;
  804. // se il block code è a zero esci con NON attivare la richiesta password
  805. if ([[CCUtility getBlockCode] length] == 0) return NO;
  806. // se non c'è attivo un account esci con NON attivare la richiesta password
  807. if ([self.activeAccount length] == 0) return NO;
  808. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  809. if (serverUrl && _activeUrl) {
  810. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  811. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  812. if (directory.lock) {
  813. isBlockZone = true;
  814. break;
  815. } else {
  816. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  817. if (serverUrl == self.activeUrl)
  818. break;
  819. }
  820. }
  821. }
  822. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  823. return YES;
  824. }
  825. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  826. {
  827. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  828. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  829. viewController.delegate = self;
  830. viewController.title = [NCBrandOptions sharedInstance].brand;
  831. viewController.fromType = CCBKPasscodeFromLockScreen;
  832. viewController.inputViewTitlePassword = YES;
  833. if ([CCUtility getSimplyBlockCode]) {
  834. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  835. viewController.passcodeInputView.maximumLength = 6;
  836. } else {
  837. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  838. viewController.passcodeInputView.maximumLength = 64;
  839. }
  840. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  841. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  842. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  843. navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
  844. return navigationController;
  845. }
  846. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  847. {
  848. [aViewController dismissViewControllerAnimated:YES completion:nil];
  849. // is a lock screen
  850. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  851. [aViewController dismissViewControllerAnimated:YES completion:nil];
  852. // start session Passcode Lock
  853. BOOL isBlockZone = false;
  854. NSString *serverUrl = self.activeMain.serverUrl;
  855. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  856. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  857. if (directory.lock) {
  858. isBlockZone = true;
  859. break;
  860. } else {
  861. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  862. if (serverUrl == self.activeUrl)
  863. break;
  864. }
  865. }
  866. if (isBlockZone)
  867. self.sessionePasscodeLock = [NSDate date];
  868. }
  869. }
  870. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  871. {
  872. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  873. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  874. //self.lockUntilDate = nil;
  875. //self.failedAttempts = 0;
  876. aResultHandler(YES);
  877. } else aResultHandler(NO);
  878. } else aResultHandler(YES);
  879. }
  880. #pragma --------------------------------------------------------------------------------------------
  881. #pragma mark ===== reachabilityChanged =====
  882. #pragma --------------------------------------------------------------------------------------------
  883. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  884. {
  885. if ([self.reachability isReachable]) {
  886. if (self.lastReachability == NO) {
  887. NSLog(@"[LOG] Request Service Server Nextcloud");
  888. [[NCService sharedInstance] startRequestServicesServer];
  889. }
  890. NSLog(@"[LOG] Reachability Changed: Reachable");
  891. self.lastReachability = YES;
  892. } else {
  893. if (self.lastReachability == YES) {
  894. [[NCContentPresenter shared] messageNotification:@"_network_not_available_" description:nil delay:k_dismissAfterSecond type:messageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  895. }
  896. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  897. self.lastReachability = NO;
  898. }
  899. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  900. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  901. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  902. }
  903. #pragma --------------------------------------------------------------------------------------------
  904. #pragma mark ===== Fetch =====
  905. #pragma --------------------------------------------------------------------------------------------
  906. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  907. {
  908. // Test Maintenance
  909. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  910. completionHandler(UIBackgroundFetchResultNoData);
  911. return;
  912. }
  913. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  914. // Verify new photo
  915. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  916. // after 20 sec
  917. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  918. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  919. if ([records count] > 0) {
  920. completionHandler(UIBackgroundFetchResultNewData);
  921. } else {
  922. completionHandler(UIBackgroundFetchResultNoData);
  923. }
  924. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  925. });
  926. }
  927. #pragma --------------------------------------------------------------------------------------------
  928. #pragma mark ===== Operation Networking & Session =====
  929. #pragma --------------------------------------------------------------------------------------------
  930. //
  931. // Method called by the system when all the background task has end
  932. //
  933. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  934. {
  935. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  936. // after 20 sec
  937. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  938. self.backgroundSessionCompletionHandler = completionHandler;
  939. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  940. self.backgroundSessionCompletionHandler = nil;
  941. completionHandler();
  942. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  943. });
  944. }
  945. #pragma --------------------------------------------------------------------------------------------
  946. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  947. #pragma --------------------------------------------------------------------------------------------
  948. - (void)loadAutoDownloadUpload
  949. {
  950. if (self.activeAccount.length == 0 || self.maintenanceMode)
  951. return;
  952. tableMetadata *metadataForUpload, *metadataForDownload;
  953. long counterDownload = 0, counterUpload = 0;
  954. NSUInteger sizeDownload = 0, sizeUpload = 0;
  955. BOOL isE2EE = false;
  956. NSMutableArray *uploaded = [NSMutableArray new];
  957. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  958. // Detect E2EE
  959. NSString *saveserverUrl = @"";
  960. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status != %d", k_metadataStatusNormal] sorted:@"serverUrl" ascending:NO];
  961. for (tableMetadata *metadata in metadatasForE2EE) {
  962. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  963. saveserverUrl = metadata.serverUrl;
  964. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  965. isE2EE = true;
  966. break;
  967. }
  968. }
  969. }
  970. // E2EE : not in background
  971. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  972. return;
  973. }
  974. // E2EE : only 1 operation
  975. if (isE2EE) {
  976. maxConcurrentOperationDownloadUpload = 1;
  977. }
  978. // Stop Timer
  979. [_timerProcessAutoDownloadUpload invalidate];
  980. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  981. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  982. // Counter
  983. counterDownload = [metadatasDownload count];
  984. counterUpload = [metadatasUpload count];
  985. // Size
  986. for (tableMetadata *metadata in metadatasDownload) {
  987. sizeDownload = sizeDownload + metadata.size;
  988. }
  989. for (tableMetadata *metadata in metadatasUpload) {
  990. sizeUpload = sizeUpload + metadata.size;
  991. }
  992. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  993. // ------------------------- <selector Download> -------------------------
  994. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  995. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"date" ascending:YES];
  996. if (metadataForDownload) {
  997. metadataForDownload.status = k_metadataStatusInDownload;
  998. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  999. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  1000. counterDownload++;
  1001. sizeDownload = sizeDownload + metadata.size;
  1002. } else {
  1003. break;
  1004. }
  1005. }
  1006. // ------------------------- <selector Upload> -------------------------
  1007. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1008. if (sizeUpload > k_maxSizeOperationUpload) {
  1009. break;
  1010. }
  1011. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload] sorted:@"date" ascending:YES];
  1012. // Verify modify file
  1013. if ([uploaded containsObject:[NSString stringWithFormat:@"%@%@%@", metadataForUpload.account, metadataForUpload.serverUrl, metadataForUpload.fileName]]) {
  1014. break;
  1015. }
  1016. if (metadataForUpload) {
  1017. // Verify modify file
  1018. BOOL isAleadyInUpload = false;
  1019. for (tableMetadata *metadata in metadatasUpload) {
  1020. if ([metadataForUpload.account isEqualToString:metadata.account] && [metadataForUpload.serverUrl isEqualToString:metadata.serverUrl] && [metadataForUpload.fileName isEqualToString:metadata.fileName]) {
  1021. isAleadyInUpload = true;
  1022. }
  1023. }
  1024. if (isAleadyInUpload == false) {
  1025. metadataForUpload.status = k_metadataStatusInUpload;
  1026. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1027. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1028. counterUpload++;
  1029. sizeUpload = sizeUpload + metadata.size;
  1030. // For verify modify file
  1031. [uploaded addObject:[NSString stringWithFormat:@"%@%@%@", metadata.account, metadata.serverUrl, metadata.fileName]];
  1032. } else {
  1033. break;
  1034. }
  1035. } else {
  1036. break;
  1037. }
  1038. }
  1039. // ------------------------- <selector Auto Upload> -------------------------
  1040. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1041. if (sizeUpload > k_maxSizeOperationUpload) {
  1042. break;
  1043. }
  1044. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload] sorted:@"date" ascending:YES];
  1045. if (metadataForUpload) {
  1046. metadataForUpload.status = k_metadataStatusInUpload;
  1047. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1048. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1049. counterUpload++;
  1050. sizeUpload = sizeUpload + metadata.size;
  1051. } else {
  1052. break;
  1053. }
  1054. }
  1055. // ------------------------- <selector Auto Upload All> ----------------------
  1056. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1057. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:@"date" ascending:YES];
  1058. NSInteger errorCount = [metadatas count];
  1059. if (errorCount >= k_maxErrorAutoUploadAll) {
  1060. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_too_errors_automatic_all_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1061. } else {
  1062. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1063. if (sizeUpload > k_maxSizeOperationUpload) {
  1064. break;
  1065. }
  1066. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1067. if (metadataForUpload) {
  1068. metadataForUpload.status = k_metadataStatusInUpload;
  1069. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1070. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1071. counterUpload++;
  1072. sizeUpload = sizeUpload + metadata.size;
  1073. } else {
  1074. break;
  1075. }
  1076. }
  1077. }
  1078. // No Download/upload available ? --> remove errors for retry
  1079. //
  1080. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1081. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1082. for (tableMetadata *metadata in metadatas) {
  1083. if (metadata.status == k_metadataStatusDownloadError)
  1084. metadata.status = k_metadataStatusWaitDownload;
  1085. else if (metadata.status == k_metadataStatusUploadError)
  1086. metadata.status = k_metadataStatusWaitUpload;
  1087. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1088. }
  1089. }
  1090. // Verify internal error download (lost task)
  1091. //
  1092. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusDownloading] sorted:nil ascending:true];
  1093. for (tableMetadata *metadata in matadatasInDownloading) {
  1094. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1095. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1096. NSURLSessionTask *findTask;
  1097. for (NSURLSessionTask *task in downloadTasks) {
  1098. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1099. findTask = task;
  1100. }
  1101. }
  1102. if (!findTask) {
  1103. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1104. metadata.status = k_metadataStatusWaitDownload;
  1105. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1106. }
  1107. }];
  1108. }
  1109. // Verify internal error upload (lost task)
  1110. //
  1111. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1112. for (tableMetadata *metadata in metadatasUploading) {
  1113. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1114. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1115. NSURLSessionTask *findTask;
  1116. for (NSURLSessionTask *task in uploadTasks) {
  1117. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1118. findTask = task;
  1119. }
  1120. }
  1121. if (!findTask) {
  1122. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1123. metadata.status = k_metadataStatusWaitUpload;
  1124. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1125. }
  1126. }];
  1127. }
  1128. // Upload in pending
  1129. //
  1130. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1131. for (tableMetadata *metadata in metadatasInUpload) {
  1132. if ([self.sessionPendingStatusInUpload containsObject:metadata.ocId]) {
  1133. metadata.status = k_metadataStatusWaitUpload;
  1134. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1135. } else {
  1136. [self.sessionPendingStatusInUpload addObject:metadata.ocId];
  1137. }
  1138. }
  1139. if (metadatasInUpload.count == 0) {
  1140. [self.sessionPendingStatusInUpload removeAllObjects];
  1141. }
  1142. // Start Timer
  1143. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1144. }
  1145. - (void)startLoadAutoDownloadUpload
  1146. {
  1147. if (self.timerProcessAutoDownloadUpload.isValid) {
  1148. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1149. }
  1150. }
  1151. #pragma --------------------------------------------------------------------------------------------
  1152. #pragma mark ===== OpenURL =====
  1153. #pragma --------------------------------------------------------------------------------------------
  1154. // Method called from iOS system to send a file from other app.
  1155. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1156. {
  1157. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1158. return YES;
  1159. NSString *scheme = url.scheme;
  1160. dispatch_time_t timer = 0;
  1161. if (self.activeMain == nil) timer = 1;
  1162. if ([scheme isEqualToString:@"nextcloud"]) {
  1163. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1164. NSString *action = url.host;
  1165. if ([action isEqualToString:@"open-file"]) {
  1166. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1167. NSArray *queryItems = urlComponents.queryItems;
  1168. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1169. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1170. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1171. tableAccount *matchedAccount = nil;
  1172. // verify parameter
  1173. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1174. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1175. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1176. [alertController addAction:okAction];
  1177. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1178. } else {
  1179. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1180. if (account) {
  1181. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1182. NSString *activeAccountUser = account.user;
  1183. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1184. matchedAccount = account;
  1185. } else {
  1186. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1187. for (tableAccount *account in accounts) {
  1188. NSURL *accountURL = [NSURL URLWithString:account.url];
  1189. NSString *accountUser = account.user;
  1190. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1191. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1192. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1193. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1194. }
  1195. }
  1196. }
  1197. if (matchedAccount) {
  1198. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1199. UITabBarController *tbc;
  1200. if (splitViewController.isCollapsed) {
  1201. tbc = splitViewController.viewControllers.firstObject;
  1202. for (UINavigationController *nvc in tbc.viewControllers) {
  1203. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  1204. [nvc popToRootViewControllerAnimated:NO];
  1205. }
  1206. } else {
  1207. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  1208. [nvcDetail popToRootViewControllerAnimated:NO];
  1209. tbc = splitViewController.viewControllers.firstObject;
  1210. }
  1211. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1212. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  1213. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1214. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1215. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1216. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1217. if ([path containsString:@"/"]) {
  1218. // Push
  1219. NSString *directoryName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1220. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1221. 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:@""];
  1222. [self.activeMain performSegueDirectoryWithControlPasscode:true metadata:metadata blinkFileNamePath:fileNamePath];
  1223. } else {
  1224. // Reload folder
  1225. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1226. self.activeMain.blinkFileNamePath = fileNamePath;
  1227. [self.activeMain readFolder:serverUrl];
  1228. }
  1229. });
  1230. });
  1231. });
  1232. } else {
  1233. NSString *domain = [[NSURL URLWithString:link] host];
  1234. NSString *fileName = [path lastPathComponent];
  1235. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1236. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1237. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1238. [alertController addAction:okAction];
  1239. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1240. }
  1241. }
  1242. }
  1243. }
  1244. });
  1245. return YES;
  1246. }
  1247. NSError *error;
  1248. NSLog(@"[LOG] the path is: %@", url.path);
  1249. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1250. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1251. if (self.activeAccount) {
  1252. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1253. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1254. if (error == nil) {
  1255. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1256. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1257. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1258. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1259. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1260. });
  1261. }
  1262. }
  1263. return YES;
  1264. }
  1265. #pragma --------------------------------------------------------------------------------------------
  1266. #pragma mark ===== Maintenance Mode =====
  1267. #pragma --------------------------------------------------------------------------------------------
  1268. - (void)maintenanceMode:(BOOL)mode
  1269. {
  1270. self.maintenanceMode = mode;
  1271. }
  1272. #pragma --------------------------------------------------------------------------------------------
  1273. #pragma mark ===== UPGRADE =====
  1274. #pragma --------------------------------------------------------------------------------------------
  1275. - (BOOL)upgrade
  1276. {
  1277. #ifdef DEBUG
  1278. //self.maintenanceMode = YES;
  1279. #endif
  1280. NSString *actualVersion = [CCUtility getVersion];
  1281. NSString *actualBuild = [CCUtility getBuild];
  1282. /* ---------------------- UPGRADE VERSION ----------------------- */
  1283. // VERSION < 2.17.6
  1284. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1285. // Remove All old Photo Library
  1286. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1287. }
  1288. // VERSION == 2.17.6
  1289. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1290. // Build < 10
  1291. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1292. // Remove All old Photo Library
  1293. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1294. }
  1295. }
  1296. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1297. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1298. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1299. }
  1300. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1301. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1302. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1303. NSString *account = @"";
  1304. NSString *directoryUser = @"";
  1305. NSString *fileName;
  1306. for (tableLocalFile *record in records) {
  1307. if (![account isEqualToString:record.account]) {
  1308. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1309. if (tableAccount) {
  1310. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1311. account = record.account;
  1312. }
  1313. }
  1314. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.ocId];
  1315. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1316. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageOcId:record.ocId fileNameView:record.fileName]];
  1317. }
  1318. }
  1319. });
  1320. }
  1321. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1322. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1323. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1324. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1325. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1326. }
  1327. }
  1328. if (([actualVersion compare:@"2.23.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1329. NSArray *records = [[NCManageDatabase sharedInstance] getAllAccount];
  1330. for (tableAccount *record in records) {
  1331. [CCUtility setPassword:record.account password:record.password];
  1332. [[NCManageDatabase sharedInstance] removePasswordAccount:record.account];
  1333. }
  1334. }
  1335. return YES;
  1336. }
  1337. @end