AppDelegate.m 86 KB

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