AppDelegate.m 81 KB

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