AppDelegate.m 83 KB

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