AppDelegate.m 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  1. //
  2. // AppDelegate.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 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 "CCGraphics.h"
  25. #import "CCSynchronize.h"
  26. #import "CCMain.h"
  27. #import "NCBridgeSwift.h"
  28. #import "NCAutoUpload.h"
  29. #import "NCPushNotificationEncryption.h"
  30. #import <QuartzCore/QuartzCore.h>
  31. @import Sentry;
  32. @class NCViewerRichdocument;
  33. @interface AppDelegate() <TOPasscodeViewControllerDelegate>
  34. @end
  35. @implementation AppDelegate
  36. + (void)initialize
  37. {
  38. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  39. }
  40. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  41. {
  42. if (![CCUtility getDisableCrashservice] && NCBrandOptions.sharedInstance.disable_crash_service == false) {
  43. [SentrySDK startWithOptions: @{
  44. @"dsn": @"https://42eaf570ec2646b1a564a4c4bfc8c279@o394108.ingest.sentry.io/5243836",
  45. @"debug": @(YES),
  46. @"enableAutoSessionTracking": @(YES)
  47. /* PRIVACY : https://github.com/getsentry/sentry-cocoa
  48. By default, we don’t apply the user identification provided to the SDK via the API. Instead, we use
  49. the installation ID generated with the first use of the application. The ID doesn’t contain any
  50. private or public data of your users or any public or shared data of their device.
  51. */
  52. }];
  53. }
  54. [CCUtility createDirectoryStandard];
  55. [CCUtility emptyTemporaryDirectory];
  56. // Networking
  57. [[NCCommunicationCommon shared] setupWithDelegate:[NCNetworking shared]];
  58. [[NCCommunicationCommon shared] setupWithUserAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups];
  59. // Set account, if no exists clear all
  60. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  61. if (tableAccount == nil) {
  62. // remove all the keys Chain
  63. [CCUtility deleteAllChainStore];
  64. // remove all the App group key
  65. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  66. } else {
  67. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  68. }
  69. // UserDefaults
  70. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  71. // Background Fetch
  72. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  73. self.listProgressMetadata = [NSMutableDictionary new];
  74. self.listMainVC = [NSMutableDictionary new];
  75. self.arrayDeleteMetadata = [NSMutableArray new];
  76. self.arrayMoveMetadata = [NSMutableArray new];
  77. self.arrayMoveServerUrlTo = [NSMutableArray new];
  78. self.arrayCopyMetadata = [NSMutableArray new];
  79. self.arrayCopyServerUrlTo = [NSMutableArray new];
  80. // Push Notification
  81. [application registerForRemoteNotifications];
  82. // Display notification
  83. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  84. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  85. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { }];
  86. //AV Session
  87. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  88. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  89. // ProgressView Detail
  90. self.progressViewDetail = [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleBar];
  91. // Quick Actions
  92. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  93. [self configDynamicShortcutItems];
  94. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  95. if (shortcutItem)
  96. [self handleShortCutItem:shortcutItem];
  97. }
  98. // Start Timer
  99. self.timerProcessAutoUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoUpload target:self selector:@selector(loadAutoUpload) userInfo:nil repeats:YES];
  100. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  101. [self startTimerErrorNetworking];
  102. // Store review
  103. if ([[NCUtility sharedInstance] isSimulatorOrTestFlight] == false) {
  104. NCStoreReview *review = [NCStoreReview new];
  105. [review incrementAppRuns];
  106. [review showStoreReview];
  107. }
  108. // Detect Dark mode
  109. if (@available(iOS 13.0, *)) {
  110. if ([CCUtility getDarkModeDetect]) {
  111. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  112. [CCUtility setDarkMode:YES];
  113. } else {
  114. [CCUtility setDarkMode:NO];
  115. }
  116. }
  117. }
  118. if ([NCBrandOptions sharedInstance].disable_intro) {
  119. [CCUtility setIntro:YES];
  120. if (self.activeAccount.length == 0) {
  121. [self openLoginView:nil selector:k_intro_login openLoginWeb:false];
  122. }
  123. } else {
  124. if ([CCUtility getIntro] == NO) {
  125. UIViewController *introViewController = [[UIStoryboard storyboardWithName:@"NCIntro" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
  126. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController: introViewController];
  127. self.window.rootViewController = navController;
  128. [self.window makeKeyAndVisible];
  129. }
  130. }
  131. // init home
  132. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  133. // Observer
  134. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteFile:) name:k_notificationCenter_deleteFile object:nil];
  135. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moveFile:) name:k_notificationCenter_moveFile object:nil];
  136. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(copyFile:) name:k_notificationCenter_copyFile object:nil];
  137. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadedFile:) name:k_notificationCenter_uploadedFile object:nil];
  138. // Passcode
  139. dispatch_async(dispatch_get_main_queue(), ^{
  140. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  141. });
  142. return YES;
  143. }
  144. //
  145. // L' applicazione si dimetterà dallo stato di attivo
  146. //
  147. - (void)applicationWillResignActive:(UIApplication *)application
  148. {
  149. // Test Maintenance
  150. if (self.activeAccount.length == 0 || self.maintenanceMode)
  151. return;
  152. [self updateApplicationIconBadgeNumber];
  153. }
  154. //
  155. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  156. //
  157. - (void)applicationWillEnterForeground:(UIApplication *)application
  158. {
  159. // Test Maintenance
  160. if (self.activeAccount.length == 0 || self.maintenanceMode)
  161. return;
  162. NSLog(@"[LOG] Request Passcode");
  163. [self passcodeWithAutomaticallyPromptForBiometricValidation:true];
  164. NSLog(@"[LOG] Request Service Server Nextcloud");
  165. [[NCService shared] startRequestServicesServer];
  166. NSLog(@"[LOG] Initialize Auto upload");
  167. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  168. NSLog(@"[LOG] Read active directory");
  169. [self.activeMain readFileReloadFolder];
  170. NSLog(@"[LOG] Required unsubscribing / subscribing");
  171. [self pushNotification];
  172. NSLog(@"[LOG] RichDocument");
  173. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_richdocumentGrabFocus object:nil];
  174. }
  175. //
  176. // L' applicazione entrerà in primo piano (attivo sempre)
  177. //
  178. - (void)applicationDidBecomeActive:(UIApplication *)application
  179. {
  180. // Test Maintenance
  181. if (self.activeAccount.length == 0 || self.maintenanceMode)
  182. return;
  183. // middelware ping
  184. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  185. NSLog(@"[LOG] Middleware Ping");
  186. [[NCService shared] middlewarePing];
  187. }
  188. // Brand
  189. #if defined(HC)
  190. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  191. if (account.hcIsTrial == true || account.hcTrialExpired == true || account.hcNextGroupExpirationGroupExpired == true) {
  192. HCTrial *vc = [[UIStoryboard storyboardWithName:@"HCTrial" bundle:nil] instantiateInitialViewController];
  193. vc.account = account;
  194. [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
  195. }
  196. #endif
  197. }
  198. //
  199. // L' applicazione è entrata nello sfondo
  200. //
  201. - (void)applicationDidEnterBackground:(UIApplication *)application
  202. {
  203. NSLog(@"[LOG] Enter in Background");
  204. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_applicationDidEnterBackground object:nil];
  205. [self passcodeWithAutomaticallyPromptForBiometricValidation:false];
  206. }
  207. //
  208. // L'applicazione terminerà
  209. //
  210. - (void)applicationWillTerminate:(UIApplication *)application
  211. {
  212. NSLog(@"[LOG] bye bye, Nextcloud !");
  213. }
  214. #pragma --------------------------------------------------------------------------------------------
  215. #pragma mark ===== Login / checkErrorNetworking =====
  216. #pragma --------------------------------------------------------------------------------------------
  217. - (void)checkErrorNetworking
  218. {
  219. // test
  220. if (self.activeAccount.length == 0 || self.maintenanceMode)
  221. return;
  222. // check unauthorized server (401)
  223. if ([CCUtility getPassword:self.activeAccount].length == 0) {
  224. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:true];
  225. }
  226. // check certificate untrusted (-1202)
  227. if ([CCUtility getCertificateError:self.activeAccount]) {
  228. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_ssl_certificate_untrusted_", nil) message:NSLocalizedString(@"_connect_server_anyway_", nil) preferredStyle:UIAlertControllerStyleAlert];
  229. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_yes_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  230. [[NCNetworking shared] wrtiteCertificateWithDirectoryCertificate:[CCUtility getDirectoryCerificates]];
  231. [self startTimerErrorNetworking];
  232. }]];
  233. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_no_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  234. [self startTimerErrorNetworking];
  235. }]];
  236. [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
  237. // Stop timer error network
  238. [self.timerErrorNetworking invalidate];
  239. }];
  240. }
  241. }
  242. - (void)openLoginView:(UIViewController *)viewController selector:(NSInteger)selector openLoginWeb:(BOOL)openLoginWeb
  243. {
  244. // use appConfig [MDM]
  245. if ([NCBrandOptions sharedInstance].use_configuration) {
  246. if (!(_appConfigView.isViewLoaded && _appConfigView.view.window)) {
  247. self.appConfigView = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCAppConfigView"];
  248. [self showLoginViewController:self.appConfigView forContext:viewController];
  249. }
  250. return;
  251. }
  252. // only for personalized LoginWeb [customer]
  253. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  254. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  255. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  256. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  257. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  258. }
  259. return;
  260. }
  261. // normal login
  262. if (selector == k_intro_signup) {
  263. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  264. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  265. if (selector == k_intro_signup) {
  266. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  267. } else {
  268. self.activeLoginWeb.urlBase = self.activeUrl;
  269. }
  270. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  271. }
  272. } else if ([NCBrandOptions sharedInstance].disable_intro && [NCBrandOptions sharedInstance].disable_request_login_url) {
  273. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  274. self.activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  275. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  276. } else if (openLoginWeb) {
  277. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  278. self.activeLoginWeb = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"NCLoginWeb"];
  279. self.activeLoginWeb.urlBase = self.activeUrl;
  280. [self showLoginViewController:self.activeLoginWeb forContext:viewController];
  281. }
  282. } else {
  283. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  284. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  285. [self showLoginViewController:_activeLogin forContext:viewController];
  286. }
  287. }
  288. }
  289. -(void)showLoginViewController:(UIViewController *)viewController forContext:(UIViewController *)contextViewController
  290. {
  291. if (contextViewController == NULL) {
  292. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  293. navController.navigationBar.barStyle = UIBarStyleBlack;
  294. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  295. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  296. [navController.navigationBar setTranslucent:false];
  297. self.window.rootViewController = navController;
  298. [self.window makeKeyAndVisible];
  299. } else if ([contextViewController isKindOfClass:[UINavigationController class]]) {
  300. UINavigationController *navController = ((UINavigationController *)contextViewController);
  301. [navController pushViewController:viewController animated:true];
  302. } else {
  303. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  304. navController.modalPresentationStyle = UIModalPresentationFullScreen;
  305. navController.navigationBar.barStyle = UIBarStyleBlack;
  306. navController.navigationBar.tintColor = NCBrandColor.sharedInstance.customerText;
  307. navController.navigationBar.barTintColor = NCBrandColor.sharedInstance.customer;
  308. [navController.navigationBar setTranslucent:false];
  309. [contextViewController presentViewController:navController animated:true completion:nil];
  310. }
  311. }
  312. - (void)startTimerErrorNetworking
  313. {
  314. self.timerErrorNetworking = [NSTimer scheduledTimerWithTimeInterval:k_timerErrorNetworking target:self selector:@selector(checkErrorNetworking) userInfo:nil repeats:YES];
  315. }
  316. #pragma --------------------------------------------------------------------------------------------
  317. #pragma mark ===== Account & Communication =====
  318. #pragma --------------------------------------------------------------------------------------------
  319. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activeUserID:(NSString *)activeUserID activePassword:(NSString *)activePassword
  320. {
  321. self.activeAccount = activeAccount;
  322. self.activeUrl = activeUrl;
  323. self.activeUser = activeUser;
  324. self.activeUserID = activeUserID;
  325. self.activePassword = activePassword;
  326. (void)[NCNetworkingNotificationCenter shared];
  327. [[NCCommunicationCommon shared] setupWithAccount:activeAccount user:activeUser userId:activeUserID password:activePassword url:activeUrl];
  328. [self settingSetupCommunicationCapabilities:activeAccount];
  329. }
  330. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  331. {
  332. // Push Notification
  333. tableAccount *accountPN = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
  334. [self unsubscribingNextcloudServerPushNotification:accountPN.account url:accountPN.url user:accountPN.user withSubscribing:false];
  335. [self settingActiveAccount:nil activeUrl:nil activeUser:nil activeUserID:nil activePassword:nil];
  336. /* DELETE ALL FILES LOCAL FS */
  337. NSArray *results = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  338. for (tableLocalFile *result in results) {
  339. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  340. }
  341. // Clear database
  342. [[NCManageDatabase sharedInstance] clearDatabaseWithAccount:account removeAccount:true];
  343. [CCUtility clearAllKeysEndToEnd:account];
  344. [CCUtility clearAllKeysPushNotification:account];
  345. [CCUtility setCertificateError:account error:false];
  346. [CCUtility setPassword:account password:nil];
  347. if (wipe) {
  348. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  349. if ([listAccount count] > 0) {
  350. NSString *newAccount = listAccount[0];
  351. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:newAccount];
  352. [self settingActiveAccount:newAccount activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  353. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  354. } else {
  355. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:false];
  356. }
  357. }
  358. }
  359. - (void)settingSetupCommunicationCapabilities:(NSString *)account
  360. {
  361. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  362. if (serverVersionMajor > 0) {
  363. [[OCNetworking sharedManager].sharedOCCommunication setupNextcloudVersion: serverVersionMajor];
  364. [[NCCommunicationCommon shared] setupWithNextcloudVersion:serverVersionMajor];
  365. }
  366. NSString *webDavRoot = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:account elements:NCElementsJSON.shared.capabilitiesWebDavRoot];
  367. if (webDavRoot != nil) {
  368. [[NCCommunicationCommon shared] setupWithWebDavRoot:webDavRoot];
  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 user:result.user withSubscribing:true];
  385. } else {
  386. [self subscribingNextcloudServerPushNotification:result.account url:result.url user:result.user];
  387. }
  388. }
  389. }
  390. }
  391. - (void)subscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url user:(NSString *)user
  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. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  401. [[NCCommunication shared] subscribingPushNotificationWithServerUrl:url account:account user:user password:[CCUtility getPassword:account] pushTokenHash:pushTokenHash devicePublicKey:pushDevicePublicKey proxyServerUrl:proxyServerPath customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSString *deviceIdentifier, NSString *signature, NSString *publicKey, NSInteger errorCode, NSString *errorDescription) {
  402. if (errorCode == 0) {
  403. NSString *userAgent = [NSString stringWithFormat:@"%@ (Strict VoIP)", [CCUtility getUserAgent]];
  404. [[NCCommunication shared] subscribingPushProxyWithProxyServerUrl:proxyServerPath pushToken:self.pushKitToken deviceIdentifier:deviceIdentifier signature:signature publicKey:publicKey userAgent:userAgent completionHandler:^(NSInteger errorCode, NSString *errorDescription) {
  405. if (errorCode == 0) {
  406. NSLog(@"[LOG] Subscribed to Push Notification server & proxy successfully.");
  407. [CCUtility setPushNotificationToken:account token:self.pushKitToken];
  408. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier];
  409. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:signature];
  410. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  411. }
  412. }];
  413. }
  414. }];
  415. }
  416. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url user:(NSString *)user withSubscribing:(BOOL)subscribing
  417. {
  418. // test
  419. if (self.activeAccount.length == 0 || self.maintenanceMode)
  420. return;
  421. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  422. NSString *signature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  423. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  424. [[NCCommunication shared] unsubscribingPushNotificationWithServerUrl:url account:account user:user password:[CCUtility getPassword:account] customUserAgent:nil addCustomHeaders:nil completionHandler:^(NSString *account, NSInteger errorCode, NSString *errorDescription) {
  425. if (errorCode == 0) {
  426. NSString *userAgent = [NSString stringWithFormat:@"%@ (Strict VoIP)", [CCUtility getUserAgent]];
  427. NSString *proxyServerPath = [NCBrandOptions sharedInstance].pushNotificationServerProxy;
  428. [[NCCommunication shared] unsubscribingPushProxyWithProxyServerUrl:proxyServerPath deviceIdentifier:deviceIdentifier signature:signature publicKey:publicKey userAgent:userAgent completionHandler:^(NSInteger errorCode, NSString *errorDescription) {
  429. if (errorCode == 0) {
  430. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  431. [CCUtility setPushNotificationPublicKey:account data:nil];
  432. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  433. [CCUtility setPushNotificationPrivateKey:account data:nil];
  434. [CCUtility setPushNotificationToken:account token:nil];
  435. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  436. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  437. if (self.pushKitToken != nil && subscribing) {
  438. [self subscribingNextcloudServerPushNotification:account url:url user:user];
  439. }
  440. }
  441. }];
  442. }
  443. }];
  444. }
  445. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  446. {
  447. //Called when a notification is delivered to a foreground app.
  448. completionHandler(UNNotificationPresentationOptionAlert);
  449. }
  450. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  451. {
  452. completionHandler();
  453. }
  454. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  455. {
  456. self.pushKitToken = [self stringWithDeviceToken:deviceToken];
  457. [self pushNotification];
  458. }
  459. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  460. {
  461. NSString *message = [userInfo objectForKey:@"subject"];
  462. if (message) {
  463. NSArray *results = [[NCManageDatabase sharedInstance] getAllAccount];
  464. for (tableAccount *result in results) {
  465. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  466. NSData *decryptionKey = [CCUtility getPushNotificationPrivateKey:result.account];
  467. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:decryptionKey];
  468. if (decryptedMessage) {
  469. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  470. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  471. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  472. BOOL delete = [[json objectForKey:@"delete"] boolValue];
  473. BOOL deleteAll = [[json objectForKey:@"delete-all"] boolValue];
  474. if (delete) {
  475. [self removeNotificationWithNotificationId:nid usingDecryptionKey:decryptionKey];
  476. } else if (deleteAll) {
  477. [self cleanAllNotifications];
  478. }
  479. }
  480. }
  481. }
  482. }
  483. completionHandler(UIBackgroundFetchResultNoData);
  484. }
  485. - (void)cleanAllNotifications
  486. {
  487. [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  488. }
  489. - (void)removeNotificationWithNotificationId:(NSInteger)notificationId usingDecryptionKey:(NSData *)key
  490. {
  491. // Check in pending notifications
  492. [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
  493. for (UNNotificationRequest *notificationRequest in requests) {
  494. NSString *message = [notificationRequest.content.userInfo objectForKey:@"subject"];
  495. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  496. if (decryptedMessage) {
  497. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  498. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  499. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  500. if (nid == notificationId) {
  501. [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[notificationRequest.identifier]];
  502. }
  503. }
  504. }
  505. }];
  506. // Check in delivered notifications
  507. [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
  508. for (UNNotification *notification in notifications) {
  509. NSString *message = [notification.request.content.userInfo objectForKey:@"subject"];
  510. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey:key];
  511. if (decryptedMessage) {
  512. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  513. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  514. NSInteger nid = [[json objectForKey:@"nid"] integerValue];
  515. if (nid == notificationId) {
  516. [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notification.request.identifier]];
  517. }
  518. }
  519. }
  520. }];
  521. }
  522. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  523. {
  524. const char *data = [deviceToken bytes];
  525. NSMutableString *token = [NSMutableString string];
  526. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  527. [token appendFormat:@"%02.2hhX", data[i]];
  528. }
  529. return [token copy];
  530. }
  531. #pragma --------------------------------------------------------------------------------------------
  532. #pragma mark ==== NotificationCenter ====
  533. #pragma --------------------------------------------------------------------------------------------
  534. - (void)deleteFile:(NSNotification *)notification
  535. {
  536. if (self.arrayDeleteMetadata.count > 0) {
  537. tableMetadata *metadata = self.arrayDeleteMetadata.firstObject;
  538. [self.arrayDeleteMetadata removeObjectAtIndex:0];
  539. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  540. if (account) {
  541. [[NCNetworking shared] deleteMetadata:metadata account:metadata.account url:account.url completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  542. } else {
  543. [self deleteFile:[NSNotification new]];
  544. }
  545. }
  546. }
  547. - (void)moveFile:(NSNotification *)notification
  548. {
  549. if (self.arrayMoveMetadata.count > 0) {
  550. tableMetadata *metadata = self.arrayMoveMetadata.firstObject;
  551. NSString *serverUrlTo = self.arrayMoveServerUrlTo.firstObject;
  552. [self.arrayMoveMetadata removeObjectAtIndex:0];
  553. [self.arrayMoveServerUrlTo removeObjectAtIndex:0];
  554. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  555. if (account) {
  556. [[NCNetworking shared] moveMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  557. } else {
  558. [self moveFile:[NSNotification new]];
  559. }
  560. }
  561. }
  562. - (void)copyFile:(NSNotification *)notification
  563. {
  564. if (self.arrayCopyMetadata.count > 0) {
  565. tableMetadata *metadata = self.arrayCopyMetadata.firstObject;
  566. NSString *serverUrlTo = self.arrayCopyServerUrlTo.firstObject;
  567. [self.arrayCopyMetadata removeObjectAtIndex:0];
  568. [self.arrayCopyServerUrlTo removeObjectAtIndex:0];
  569. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  570. if (account) {
  571. [[NCNetworking shared] copyMetadata:metadata serverUrlTo:serverUrlTo overwrite:true completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  572. } else {
  573. [self copyFile:[NSNotification new]];
  574. }
  575. }
  576. }
  577. - (void)uploadedFile:(NSNotification *)notification
  578. {
  579. // NSDictionary *userInfo = notification.userInfo;
  580. // tableMetadata *metadata = userInfo[@"metadata"];
  581. // NSInteger errorCode = [userInfo[@"errorCode"] integerValue];
  582. }
  583. #pragma --------------------------------------------------------------------------------------------
  584. #pragma mark ===== Quick Actions - ShotcutItem =====
  585. #pragma --------------------------------------------------------------------------------------------
  586. - (void)configDynamicShortcutItems
  587. {
  588. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  589. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  590. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  591. // add the array to our app
  592. if (shortcutMedia)
  593. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  594. }
  595. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  596. {
  597. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  598. completionHandler(handledShortCutItem);
  599. }
  600. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  601. {
  602. BOOL handled = NO;
  603. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  604. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  605. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  606. dispatch_async(dispatch_get_main_queue(), ^{
  607. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  608. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  609. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  610. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  611. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  612. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  613. if (splitViewController.isCollapsed) {
  614. [navigationControllerMaster popToRootViewControllerAnimated:false];
  615. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  616. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  617. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  618. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  619. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  620. }
  621. }
  622. } else {
  623. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  624. [tabBarController setSelectedIndex: k_tabBarApplicationIndexMedia];
  625. }
  626. }
  627. }
  628. }
  629. }
  630. });
  631. handled = YES;
  632. }
  633. return handled;
  634. }
  635. #pragma --------------------------------------------------------------------------------------------
  636. #pragma mark ===== ApplicationIconBadgeNumber =====
  637. #pragma --------------------------------------------------------------------------------------------
  638. - (void)updateApplicationIconBadgeNumber
  639. {
  640. if (self.activeAccount.length == 0 || self.maintenanceMode)
  641. return;
  642. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  643. NSInteger counterDownload = [[NCOperationQueue shared] downloadCount];
  644. 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];
  645. NSInteger total = counterDownload + counterUpload;
  646. dispatch_async(dispatch_get_main_queue(), ^{
  647. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  648. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  649. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  650. UINavigationController *navigationController = (UINavigationController *)[splitViewController.viewControllers firstObject];
  651. if ([navigationController isKindOfClass:[UINavigationController class]]) {
  652. UITabBarController *tabBarController = (UITabBarController *)navigationController.topViewController;
  653. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  654. UITabBarItem *tabBarItem = [tabBarController.tabBar.items objectAtIndex:0];
  655. if (total > 0) {
  656. [tabBarItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  657. } else {
  658. [tabBarItem setBadgeValue:nil];
  659. }
  660. }
  661. }
  662. }
  663. });
  664. });
  665. }
  666. #pragma --------------------------------------------------------------------------------------------
  667. #pragma mark ===== TabBarController =====
  668. #pragma --------------------------------------------------------------------------------------------
  669. - (void)createTabBarController:(UITabBarController *)tabBarController
  670. {
  671. UITabBarItem *item;
  672. NSLayoutConstraint *constraint;
  673. CGFloat safeAreaBottom = safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  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:@"favorite"] 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:@"media"] 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. int buttonSize = 57;
  701. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] width:120 height:120 color:UIColor.whiteColor];
  702. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  703. buttonPlus.tag = 99;
  704. [buttonPlus setImage:buttonImage forState:UIControlStateNormal];
  705. buttonPlus.backgroundColor = NCBrandColor.sharedInstance.brand;
  706. buttonPlus.layer.cornerRadius = buttonSize / 2;
  707. buttonPlus.layer.masksToBounds = NO;
  708. buttonPlus.layer.shadowOffset = CGSizeMake(0, 0);
  709. buttonPlus.layer.shadowRadius = 3.0f;
  710. buttonPlus.layer.shadowOpacity = 0.5;
  711. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  712. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  713. [tabBarController.tabBar addSubview:buttonPlus];
  714. if (safeAreaBottom > 0) {
  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:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeTop multiplier:1.0 constant:-(buttonSize / 2)];
  720. [tabBarController.view addConstraint:constraint];
  721. // Width
  722. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  723. [tabBarController.view addConstraint:constraint];
  724. // Height
  725. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  726. [tabBarController.view addConstraint:constraint];
  727. } else {
  728. // X
  729. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
  730. [tabBarController.view addConstraint:constraint];
  731. // Y
  732. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:-(buttonSize / 2)];
  733. [tabBarController.view addConstraint:constraint];
  734. // Width
  735. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  736. [tabBarController.view addConstraint:constraint];
  737. // Height
  738. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1.0 constant:buttonSize];
  739. [tabBarController.view addConstraint:constraint];
  740. }
  741. }
  742. - (void)handleTouchTabbarCenter:(id)sender
  743. {
  744. // Test Maintenance
  745. if (self.maintenanceMode)
  746. return;
  747. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, self.activeMain.serverUrl]];
  748. if ([tableDirectory.permissions containsString:@"CK"]) {
  749. UIViewController *vc = _activeMain.splitViewController.viewControllers[0];
  750. [self showMenuInViewController: vc];
  751. } else {
  752. [[NCContentPresenter shared] messageNotification:@"_warning_" description:@"_no_permission_add_file_" delay:k_dismissAfterSecond type:messageTypeInfo errorCode:0];
  753. }
  754. }
  755. - (NSString *)getTabBarControllerActiveServerUrl
  756. {
  757. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  758. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  759. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  760. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  761. if ([masterNavigationController isKindOfClass:[UINavigationController class]]) {
  762. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  763. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  764. NSInteger index = tabBarController.selectedIndex;
  765. // select active serverUrl
  766. if (index == k_tabBarApplicationIndexFile) {
  767. serverUrl = self.activeMain.serverUrl;
  768. } else if (index == k_tabBarApplicationIndexFavorite) {
  769. if (self.activeFavorites.serverUrl)
  770. serverUrl = self.activeFavorites.serverUrl;
  771. } else if (index == k_tabBarApplicationIndexMedia) {
  772. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  773. }
  774. }
  775. }
  776. }
  777. return serverUrl;
  778. }
  779. #pragma --------------------------------------------------------------------------------------------
  780. #pragma mark ===== Theming Color =====
  781. #pragma --------------------------------------------------------------------------------------------
  782. - (void)settingThemingColorBrand
  783. {
  784. if (self.activeAccount.length == 0 || self.maintenanceMode)
  785. return;
  786. if ([NCBrandOptions sharedInstance].use_themingColor) {
  787. NSString *themingColor = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.activeAccount elements:NCElementsJSON.shared.capabilitiesThemingColor];
  788. NSString *themingColorElement = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.activeAccount elements:NCElementsJSON.shared.capabilitiesThemingColorElement];
  789. NSString *themingColorText = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:self.activeAccount elements:NCElementsJSON.shared.capabilitiesThemingColorText];
  790. [CCGraphics settingThemingColor:themingColor themingColorElement:themingColorElement themingColorText:themingColorText];
  791. UIColor *color = NCBrandColor.sharedInstance.brand;
  792. BOOL isTooLight = NCBrandColor.sharedInstance.brand.isTooLight;
  793. BOOL isTooDark = NCBrandColor.sharedInstance.brand.isTooDark;
  794. if (isTooLight) {
  795. color = [NCBrandColor.sharedInstance.brand darkerBy:10];
  796. } else if (isTooDark) {
  797. color = [NCBrandColor.sharedInstance.brand lighterBy:10];
  798. }
  799. NCBrandColor.sharedInstance.brand = color;
  800. } else {
  801. NCBrandColor.sharedInstance.brand = NCBrandColor.sharedInstance.customer;
  802. NCBrandColor.sharedInstance.brandElement = NCBrandColor.sharedInstance.customer;
  803. NCBrandColor.sharedInstance.brandText = NCBrandColor.sharedInstance.customerText;
  804. }
  805. [NCBrandColor.sharedInstance setDarkMode];
  806. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  807. [[NCMainCommon sharedInstance] createImagesThemingColor];
  808. });
  809. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_changeTheming object:nil];
  810. }
  811. - (void)changeTheming:(UIViewController *)viewController tableView:(UITableView *)tableView collectionView:(UICollectionView *)collectionView form:(BOOL)form
  812. {
  813. [NCBrandColor.sharedInstance setDarkMode];
  814. [self.window setTintColor:NCBrandColor.sharedInstance.textView];
  815. //Tab bar
  816. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  817. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  818. UINavigationController *masterNavigationController = [splitViewController.viewControllers firstObject];
  819. if ([masterNavigationController isKindOfClass:[UINavigationController class]]) {
  820. UITabBarController *tabBarController = [masterNavigationController.viewControllers firstObject];
  821. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  822. tabBarController.tabBar.barTintColor = NCBrandColor.sharedInstance.backgroundView;
  823. tabBarController.tabBar.backgroundColor = NCBrandColor.sharedInstance.tabBar;
  824. tabBarController.tabBar.tintColor = NCBrandColor.sharedInstance.brandElement;
  825. [tabBarController.tabBar viewWithTag:99].backgroundColor = NCBrandColor.sharedInstance.brandElement;
  826. }
  827. }
  828. }
  829. // Nav bar
  830. [self configureNavBarForViewController:viewController];
  831. // View
  832. if (form) viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  833. else viewController.view.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  834. // TableView
  835. if (tableView) {
  836. if (form) tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  837. else tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  838. tableView.separatorColor = NCBrandColor.sharedInstance.separator;
  839. [tableView reloadData];
  840. }
  841. // CollectionView
  842. if (collectionView) {
  843. if (form) collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm;
  844. else collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView;
  845. [collectionView reloadData];
  846. }
  847. }
  848. #pragma --------------------------------------------------------------------------------------------
  849. #pragma mark ===== Fetch =====
  850. #pragma --------------------------------------------------------------------------------------------
  851. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  852. {
  853. // Test Maintenance
  854. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  855. completionHandler(UIBackgroundFetchResultNoData);
  856. return;
  857. }
  858. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  859. // Verify new photo
  860. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  861. // after 20 sec
  862. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  863. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  864. if ([records count] > 0) {
  865. completionHandler(UIBackgroundFetchResultNewData);
  866. } else {
  867. completionHandler(UIBackgroundFetchResultNoData);
  868. }
  869. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  870. });
  871. }
  872. #pragma --------------------------------------------------------------------------------------------
  873. #pragma mark ===== Operation Networking & Session =====
  874. #pragma --------------------------------------------------------------------------------------------
  875. //
  876. // Method called by the system when all the background task has end
  877. //
  878. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  879. {
  880. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  881. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  882. self.backgroundSessionCompletionHandler = completionHandler;
  883. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  884. self.backgroundSessionCompletionHandler = nil;
  885. completionHandler();
  886. });
  887. }
  888. #pragma --------------------------------------------------------------------------------------------
  889. #pragma mark ===== Process Load Upload < k_timerProcess seconds > =====
  890. #pragma --------------------------------------------------------------------------------------------
  891. - (void)loadAutoUpload
  892. {
  893. if (self.activeAccount.length == 0 || self.maintenanceMode)
  894. return;
  895. tableMetadata *metadataForUpload;
  896. long counterUpload = 0;
  897. NSUInteger sizeUpload = 0;
  898. NSPredicate *predicate;
  899. long maxConcurrentOperationUpload = k_maxConcurrentOperation;
  900. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  901. for(tableMetadata *metadata in metadatasUpload) {
  902. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:metadata.account]) return;
  903. }
  904. // Counter
  905. counterUpload = [metadatasUpload count];
  906. // Size
  907. for (tableMetadata *metadata in metadatasUpload) {
  908. sizeUpload = sizeUpload + metadata.size;
  909. }
  910. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD %ld - %@", counterUpload, [CCUtility transformedSize:sizeUpload]]);
  911. // Stop Timer
  912. [_timerProcessAutoUpload invalidate];
  913. // ------------------------- <selector Upload> -------------------------
  914. while (counterUpload < maxConcurrentOperationUpload) {
  915. if (sizeUpload > k_maxSizeOperationUpload) {
  916. break;
  917. }
  918. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  919. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadFile, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  920. } else {
  921. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload];
  922. }
  923. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"date" ascending:YES];
  924. if (metadataForUpload) {
  925. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  926. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  927. maxConcurrentOperationUpload = 1;
  928. metadataForUpload.status = k_metadataStatusInUpload;
  929. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  930. [[NCNetworking shared] uploadWithMetadata:metadata];
  931. break;
  932. } else {
  933. metadataForUpload.status = k_metadataStatusInUpload;
  934. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  935. [[NCNetworking shared] uploadWithMetadata:metadata];
  936. counterUpload++;
  937. sizeUpload = sizeUpload + metadata.size;
  938. }
  939. } else {
  940. break;
  941. }
  942. }
  943. // ------------------------- <selector Auto Upload> -------------------------
  944. while (counterUpload < maxConcurrentOperationUpload) {
  945. if (sizeUpload > k_maxSizeOperationUpload) {
  946. break;
  947. }
  948. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  949. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadAutoUpload, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  950. } else {
  951. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload];
  952. }
  953. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"date" ascending:YES];
  954. if (metadataForUpload) {
  955. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  956. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  957. maxConcurrentOperationUpload = 1;
  958. metadataForUpload.status = k_metadataStatusInUpload;
  959. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  960. [[NCNetworking shared] uploadWithMetadata:metadata];
  961. break;
  962. } else {
  963. metadataForUpload.status = k_metadataStatusInUpload;
  964. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  965. [[NCNetworking shared] uploadWithMetadata:metadata];
  966. counterUpload++;
  967. sizeUpload = sizeUpload + metadata.size;
  968. }
  969. } else {
  970. break;
  971. }
  972. }
  973. // ------------------------- <selector Auto Upload All> ----------------------
  974. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  975. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:@"date" ascending:YES];
  976. NSInteger errorCount = [metadatas count];
  977. if (errorCount >= k_maxErrorAutoUploadAll) {
  978. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_too_errors_automatic_all_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  979. } else {
  980. while (counterUpload < maxConcurrentOperationUpload) {
  981. if (sizeUpload > k_maxSizeOperationUpload) {
  982. break;
  983. }
  984. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  985. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  986. } else {
  987. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload];
  988. }
  989. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"session" ascending:YES];
  990. if (metadataForUpload) {
  991. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  992. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  993. maxConcurrentOperationUpload = 1;
  994. metadataForUpload.status = k_metadataStatusInUpload;
  995. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  996. [[NCNetworking shared] uploadWithMetadata:metadata];
  997. break;
  998. } else {
  999. metadataForUpload.status = k_metadataStatusInUpload;
  1000. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1001. [[NCNetworking shared] uploadWithMetadata:metadata];
  1002. counterUpload++;
  1003. sizeUpload = sizeUpload + metadata.size;
  1004. }
  1005. } else {
  1006. break;
  1007. }
  1008. }
  1009. }
  1010. // No upload available ? --> Retry Upload in Error
  1011. if (counterUpload == 0) {
  1012. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusUploadError] sorted:nil ascending:NO];
  1013. for (tableMetadata *metadata in metadatas) {
  1014. metadata.session = NCCommunicationCommon.shared.sessionIdentifierBackground;
  1015. metadata.sessionError = @"";
  1016. metadata.sessionTaskIdentifier = 0;
  1017. metadata.status = k_metadataStatusInUpload;
  1018. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  1019. }
  1020. }
  1021. // verify delete Asset Local Identifiers in auto upload (Photos album)
  1022. if (counterUpload == 0 && self.passcodeViewController == nil) {
  1023. [[NCUtility sharedInstance] deleteAssetLocalIdentifiersWithAccount:self.activeAccount sessionSelector:selectorUploadAutoUpload];
  1024. }
  1025. // Start Timer
  1026. _timerProcessAutoUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoUpload target:self selector:@selector(loadAutoUpload) userInfo:nil repeats:YES];
  1027. }
  1028. - (void)startLoadAutoUpload
  1029. {
  1030. if (self.timerProcessAutoUpload.isValid) {
  1031. [self performSelectorOnMainThread:@selector(loadAutoUpload) withObject:nil waitUntilDone:YES];
  1032. }
  1033. }
  1034. #pragma --------------------------------------------------------------------------------------------
  1035. #pragma mark ===== OpenURL =====
  1036. #pragma --------------------------------------------------------------------------------------------
  1037. // Method called from iOS system to send a file from other app.
  1038. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1039. {
  1040. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1041. return YES;
  1042. NSString *scheme = url.scheme;
  1043. dispatch_time_t timer = 0;
  1044. if (self.activeMain == nil) timer = 1;
  1045. if ([scheme isEqualToString:@"nextcloud"]) {
  1046. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1047. NSString *action = url.host;
  1048. if ([action isEqualToString:@"open-file"]) {
  1049. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1050. NSArray *queryItems = urlComponents.queryItems;
  1051. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1052. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1053. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1054. tableAccount *matchedAccount = nil;
  1055. // verify parameter
  1056. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1057. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1058. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1059. [alertController addAction:okAction];
  1060. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1061. } else {
  1062. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1063. if (account) {
  1064. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1065. NSString *activeAccountUser = account.user;
  1066. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1067. matchedAccount = account;
  1068. } else {
  1069. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1070. for (tableAccount *account in accounts) {
  1071. NSURL *accountURL = [NSURL URLWithString:account.url];
  1072. NSString *accountUser = account.user;
  1073. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1074. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1075. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1076. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  1077. }
  1078. }
  1079. }
  1080. if (matchedAccount) {
  1081. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1082. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  1083. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1084. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1085. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1086. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1087. if (splitViewController.isCollapsed) {
  1088. [navigationControllerMaster popToRootViewControllerAnimated:false];
  1089. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1090. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1091. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1092. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1093. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1094. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1095. }
  1096. }
  1097. }
  1098. } else {
  1099. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1100. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1101. }
  1102. }
  1103. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1104. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1105. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1106. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1107. if ([path containsString:@"/"]) {
  1108. // Push
  1109. NSString *fileName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1110. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1111. tableMetadata *metadata = [[NCManageDatabase sharedInstance] createMetadataWithAccount:matchedAccount.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl url:@"" contentType:@""];
  1112. [self.activeMain performSegueDirectoryWithMetadata:metadata blinkFileNamePath:fileNamePath];
  1113. } else {
  1114. // Reload folder
  1115. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1116. self.activeMain.blinkFileNamePath = fileNamePath;
  1117. [self.activeMain readFolder:serverUrl];
  1118. }
  1119. });
  1120. });
  1121. }
  1122. }
  1123. }
  1124. } else {
  1125. NSString *domain = [[NSURL URLWithString:link] host];
  1126. NSString *fileName = [path lastPathComponent];
  1127. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1128. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1129. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1130. [alertController addAction:okAction];
  1131. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1132. }
  1133. }
  1134. }
  1135. }
  1136. });
  1137. return YES;
  1138. }
  1139. NSError *error;
  1140. NSLog(@"[LOG] the path is: %@", url.path);
  1141. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1142. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1143. if (self.activeAccount) {
  1144. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1145. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1146. if (error == nil) {
  1147. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1148. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  1149. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1150. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1151. UIViewController *uploadNavigationViewController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1152. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1153. [navigationControllerMaster presentViewController:uploadNavigationViewController animated:YES completion:nil];
  1154. });
  1155. }
  1156. }
  1157. }
  1158. }
  1159. return YES;
  1160. }
  1161. #pragma --------------------------------------------------------------------------------------------
  1162. #pragma mark ===== Passcode + Delegate =====
  1163. #pragma --------------------------------------------------------------------------------------------
  1164. - (void)passcodeWithAutomaticallyPromptForBiometricValidation:(BOOL)automaticallyPromptForBiometricValidation
  1165. {
  1166. LAContext *laContext = [LAContext new];
  1167. NSError *error;
  1168. BOOL isBiometryAvailable = false;
  1169. if ([[CCUtility getPasscode] length] == 0 || [self.activeAccount length] == 0 || [CCUtility getNotPasscodeAtStart]) return;
  1170. if (self.passcodeViewController == nil) {
  1171. self.passcodeViewController = [[TOPasscodeViewController alloc] initWithStyle:TOPasscodeViewStyleTranslucentLight passcodeType:TOPasscodeTypeSixDigits];
  1172. if (@available(iOS 13.0, *)) {
  1173. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  1174. self.passcodeViewController.style = TOPasscodeViewStyleTranslucentDark;
  1175. }
  1176. }
  1177. self.passcodeViewController.delegate = self;
  1178. self.passcodeViewController.keypadButtonShowLettering = false;
  1179. if ([laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
  1180. if (error == NULL) {
  1181. if (laContext.biometryType == LABiometryTypeFaceID) {
  1182. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID;
  1183. self.passcodeViewController.allowBiometricValidation = true;
  1184. isBiometryAvailable = true;
  1185. } else if (laContext.biometryType == LABiometryTypeTouchID) {
  1186. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeTouchID;
  1187. self.passcodeViewController.allowBiometricValidation = true;
  1188. isBiometryAvailable = true;
  1189. } else {
  1190. isBiometryAvailable = false;
  1191. NSLog(@"No Biometric support");
  1192. }
  1193. }
  1194. }
  1195. [self.window.rootViewController presentViewController:self.passcodeViewController animated:YES completion:nil];
  1196. }
  1197. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1198. if (automaticallyPromptForBiometricValidation && self.passcodeViewController.view.window) {
  1199. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  1200. if (success) {
  1201. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1202. [self.passcodeViewController dismissViewControllerAnimated:YES completion:^{
  1203. self.passcodeViewController = nil;
  1204. }];
  1205. });
  1206. }
  1207. }];
  1208. }
  1209. });
  1210. }
  1211. - (void)didInputCorrectPasscodeInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1212. {
  1213. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  1214. self.passcodeViewController = nil;
  1215. }];
  1216. }
  1217. - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code
  1218. {
  1219. return [code isEqualToString:[CCUtility getPasscode]];
  1220. }
  1221. - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1222. {
  1223. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  1224. if (success) {
  1225. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1226. [passcodeViewController dismissViewControllerAnimated:YES completion:^{
  1227. self.passcodeViewController = nil;
  1228. }];
  1229. });
  1230. }
  1231. }];
  1232. }
  1233. #pragma --------------------------------------------------------------------------------------------
  1234. #pragma mark ===== Maintenance Mode =====
  1235. #pragma --------------------------------------------------------------------------------------------
  1236. - (void)maintenanceMode:(BOOL)mode
  1237. {
  1238. self.maintenanceMode = mode;
  1239. }
  1240. @end