AppDelegate.m 81 KB

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