AppDelegate.m 78 KB

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