AppDelegate.m 80 KB

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