AppDelegate.m 85 KB

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