AppDelegate.m 82 KB

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