AppDelegate.m 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  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. UIView *view = [(UIButton *)sender superview];
  721. NCCreateMenuAdd *menuAdd = [[NCCreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brandElement];
  722. [menuAdd createMenuWithViewController:self.window.rootViewController view:view];
  723. }
  724. - (void)selectedTabBarController:(NSInteger)index
  725. {
  726. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  727. if (splitViewController.isCollapsed) {
  728. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  729. for (UINavigationController *nvc in tbc.viewControllers) {
  730. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  731. [nvc popToRootViewControllerAnimated:NO];
  732. }
  733. [tbc setSelectedIndex: index];
  734. } else {
  735. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  736. [nvcDetail popToRootViewControllerAnimated:NO];
  737. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  738. [tbc setSelectedIndex: index];
  739. }
  740. }
  741. - (NSString *)getTabBarControllerActiveServerUrl
  742. {
  743. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  744. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  745. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  746. NSInteger index = tabBarController.selectedIndex;
  747. // select active serverUrl
  748. if (index == k_tabBarApplicationIndexFile) {
  749. serverUrl = self.activeMain.serverUrl;
  750. } else if (index == k_tabBarApplicationIndexFavorite) {
  751. if (self.activeFavorites.serverUrl)
  752. serverUrl = self.activeFavorites.serverUrl;
  753. } else if (index == k_tabBarApplicationIndexMedia) {
  754. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  755. }
  756. return serverUrl;
  757. }
  758. #pragma --------------------------------------------------------------------------------------------
  759. #pragma mark ===== Theming Color =====
  760. #pragma --------------------------------------------------------------------------------------------
  761. - (void)settingThemingColorBrand
  762. {
  763. if (self.activeAccount.length == 0 || self.maintenanceMode)
  764. return;
  765. if ([NCBrandOptions sharedInstance].use_themingColor) {
  766. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  767. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  768. } else {
  769. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  770. [NCBrandColor sharedInstance].brandElement = [NCBrandColor sharedInstance].customer;
  771. [NCBrandColor sharedInstance].brandText = [NCBrandColor sharedInstance].customerText;
  772. }
  773. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  774. }
  775. - (void)changeTheming:(UIViewController *)vc
  776. {
  777. // Change Navigation & TabBar color
  778. vc.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  779. vc.tabBarController.tabBar.tintColor = [NCBrandColor sharedInstance].brandElement;
  780. // Change bar bottom line shadow
  781. vc.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  782. // Change button Plus
  783. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  784. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  785. UIButton *button = [tabBarController.view viewWithTag:99];
  786. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  787. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  788. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  789. // Tint Color GLOBAL WINDOW
  790. [self.window setTintColor:[NCBrandColor sharedInstance].textView];
  791. }
  792. #pragma --------------------------------------------------------------------------------------------
  793. #pragma mark ===== Manager Passcode =====
  794. #pragma --------------------------------------------------------------------------------------------
  795. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  796. {
  797. // ServerUrl active
  798. NSString *serverUrl = self.activeMain.serverUrl;
  799. BOOL isBlockZone = false;
  800. // fermiamo la data della sessione
  801. self.sessionePasscodeLock = nil;
  802. // se il block code è a zero esci con NON attivare la richiesta password
  803. if ([[CCUtility getBlockCode] length] == 0) return NO;
  804. // se non c'è attivo un account esci con NON attivare la richiesta password
  805. if ([self.activeAccount length] == 0) return NO;
  806. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  807. if (serverUrl && _activeUrl) {
  808. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  809. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  810. if (directory.lock) {
  811. isBlockZone = true;
  812. break;
  813. } else {
  814. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  815. if (serverUrl == self.activeUrl)
  816. break;
  817. }
  818. }
  819. }
  820. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  821. return YES;
  822. }
  823. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  824. {
  825. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  826. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  827. viewController.delegate = self;
  828. viewController.title = [NCBrandOptions sharedInstance].brand;
  829. viewController.fromType = CCBKPasscodeFromLockScreen;
  830. viewController.inputViewTitlePassword = YES;
  831. if ([CCUtility getSimplyBlockCode]) {
  832. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  833. viewController.passcodeInputView.maximumLength = 6;
  834. } else {
  835. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  836. viewController.passcodeInputView.maximumLength = 64;
  837. }
  838. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  839. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  840. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  841. return navigationController;
  842. }
  843. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  844. {
  845. [aViewController dismissViewControllerAnimated:YES completion:nil];
  846. // is a lock screen
  847. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  848. [aViewController dismissViewControllerAnimated:YES completion:nil];
  849. // start session Passcode Lock
  850. BOOL isBlockZone = false;
  851. NSString *serverUrl = self.activeMain.serverUrl;
  852. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  853. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  854. if (directory.lock) {
  855. isBlockZone = true;
  856. break;
  857. } else {
  858. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  859. if (serverUrl == self.activeUrl)
  860. break;
  861. }
  862. }
  863. if (isBlockZone)
  864. self.sessionePasscodeLock = [NSDate date];
  865. }
  866. }
  867. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  868. {
  869. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  870. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  871. //self.lockUntilDate = nil;
  872. //self.failedAttempts = 0;
  873. aResultHandler(YES);
  874. } else aResultHandler(NO);
  875. } else aResultHandler(YES);
  876. }
  877. #pragma --------------------------------------------------------------------------------------------
  878. #pragma mark ===== reachabilityChanged =====
  879. #pragma --------------------------------------------------------------------------------------------
  880. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  881. {
  882. if ([self.reachability isReachable]) {
  883. if (self.lastReachability == NO) {
  884. NSLog(@"[LOG] Request Service Server Nextcloud");
  885. [[NCService sharedInstance] startRequestServicesServer];
  886. }
  887. NSLog(@"[LOG] Reachability Changed: Reachable");
  888. self.lastReachability = YES;
  889. } else {
  890. if (self.lastReachability == YES) {
  891. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  892. }
  893. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  894. self.lastReachability = NO;
  895. }
  896. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  897. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  898. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  899. }
  900. #pragma --------------------------------------------------------------------------------------------
  901. #pragma mark ===== Fetch =====
  902. #pragma --------------------------------------------------------------------------------------------
  903. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  904. {
  905. // Test Maintenance
  906. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  907. completionHandler(UIBackgroundFetchResultNoData);
  908. return;
  909. }
  910. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  911. // Verify new photo
  912. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  913. // after 20 sec
  914. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  915. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  916. if ([records count] > 0) {
  917. completionHandler(UIBackgroundFetchResultNewData);
  918. } else {
  919. completionHandler(UIBackgroundFetchResultNoData);
  920. }
  921. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  922. });
  923. }
  924. #pragma --------------------------------------------------------------------------------------------
  925. #pragma mark ===== Operation Networking & Session =====
  926. #pragma --------------------------------------------------------------------------------------------
  927. //
  928. // Method called by the system when all the background task has end
  929. //
  930. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  931. {
  932. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  933. // after 20 sec
  934. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  935. self.backgroundSessionCompletionHandler = completionHandler;
  936. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  937. self.backgroundSessionCompletionHandler = nil;
  938. completionHandler();
  939. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  940. });
  941. }
  942. #pragma --------------------------------------------------------------------------------------------
  943. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  944. #pragma --------------------------------------------------------------------------------------------
  945. - (void)loadAutoDownloadUpload
  946. {
  947. if (self.activeAccount.length == 0 || self.maintenanceMode)
  948. return;
  949. tableMetadata *metadataForUpload, *metadataForDownload;
  950. long counterDownload = 0, counterUpload = 0;
  951. NSUInteger sizeDownload = 0, sizeUpload = 0;
  952. BOOL isE2EE = false;
  953. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  954. // Detect E2EE
  955. NSString *saveserverUrl = @"";
  956. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status != %d", k_metadataStatusNormal] sorted:@"serverUrl" ascending:NO];
  957. for (tableMetadata *metadata in metadatasForE2EE) {
  958. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  959. saveserverUrl = metadata.serverUrl;
  960. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  961. isE2EE = true;
  962. break;
  963. }
  964. }
  965. }
  966. // E2EE : not in background
  967. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  968. return;
  969. }
  970. // E2EE : only 1 operation
  971. if (isE2EE) {
  972. maxConcurrentOperationDownloadUpload = 1;
  973. }
  974. // Stop Timer
  975. [_timerProcessAutoDownloadUpload invalidate];
  976. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  977. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  978. // Counter
  979. counterDownload = [metadatasDownload count];
  980. counterUpload = [metadatasUpload count];
  981. // Size
  982. for (tableMetadata *metadata in metadatasDownload) {
  983. sizeDownload = sizeDownload + metadata.size;
  984. }
  985. for (tableMetadata *metadata in metadatasUpload) {
  986. sizeUpload = sizeUpload + metadata.size;
  987. }
  988. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  989. // ------------------------- <selector Download> -------------------------
  990. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  991. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"session" ascending:YES];
  992. if (metadataForDownload) {
  993. metadataForDownload.status = k_metadataStatusInDownload;
  994. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  995. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  996. counterDownload++;
  997. sizeDownload = sizeDownload + metadata.size;
  998. } else {
  999. break;
  1000. }
  1001. }
  1002. // ------------------------- <selector Upload> -------------------------
  1003. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1004. if (sizeUpload > k_maxSizeOperationUpload) {
  1005. break;
  1006. }
  1007. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1008. if (metadataForUpload) {
  1009. metadataForUpload.status = k_metadataStatusInUpload;
  1010. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1011. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1012. counterUpload++;
  1013. sizeUpload = sizeUpload + metadata.size;
  1014. } else {
  1015. break;
  1016. }
  1017. }
  1018. // ------------------------- <selector Auto Upload> -------------------------
  1019. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1020. if (sizeUpload > k_maxSizeOperationUpload) {
  1021. break;
  1022. }
  1023. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1024. if (metadataForUpload) {
  1025. metadataForUpload.status = k_metadataStatusInUpload;
  1026. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1027. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1028. counterUpload++;
  1029. sizeUpload = sizeUpload + metadata.size;
  1030. } else {
  1031. break;
  1032. }
  1033. }
  1034. // ------------------------- <selector Auto Upload All> ----------------------
  1035. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1036. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1037. NSInteger errorCount = [metadatas count];
  1038. if (errorCount >= k_maxErrorAutoUploadAll) {
  1039. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1040. } else {
  1041. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1042. if (sizeUpload > k_maxSizeOperationUpload) {
  1043. break;
  1044. }
  1045. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1046. if (metadataForUpload) {
  1047. metadataForUpload.status = k_metadataStatusInUpload;
  1048. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1049. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1050. counterUpload++;
  1051. sizeUpload = sizeUpload + metadata.size;
  1052. } else {
  1053. break;
  1054. }
  1055. }
  1056. }
  1057. // No Download/upload available ? --> remove errors for retry
  1058. //
  1059. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1060. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1061. for (tableMetadata *metadata in metadatas) {
  1062. if (metadata.status == k_metadataStatusDownloadError)
  1063. metadata.status = k_metadataStatusWaitDownload;
  1064. else if (metadata.status == k_metadataStatusUploadError)
  1065. metadata.status = k_metadataStatusWaitUpload;
  1066. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1067. }
  1068. }
  1069. // Verify internal error download (lost task)
  1070. //
  1071. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_download_session_extension, k_metadataStatusDownloading] sorted:nil ascending:true];
  1072. for (tableMetadata *metadata in matadatasInDownloading) {
  1073. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1074. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1075. NSURLSessionTask *findTask;
  1076. for (NSURLSessionTask *task in downloadTasks) {
  1077. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1078. findTask = task;
  1079. }
  1080. }
  1081. if (!findTask) {
  1082. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1083. metadata.status = k_metadataStatusWaitDownload;
  1084. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1085. }
  1086. }];
  1087. }
  1088. // Verify internal error upload (lost task)
  1089. //
  1090. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1091. for (tableMetadata *metadata in metadatasUploading) {
  1092. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1093. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1094. NSURLSessionTask *findTask;
  1095. for (NSURLSessionTask *task in uploadTasks) {
  1096. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1097. findTask = task;
  1098. }
  1099. }
  1100. if (!findTask) {
  1101. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1102. metadata.status = k_metadataStatusWaitUpload;
  1103. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1104. }
  1105. }];
  1106. }
  1107. // Upload in pending
  1108. //
  1109. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1110. for (tableMetadata *metadata in metadatasInUpload) {
  1111. if ([self.sessionPendingStatusInUpload containsObject:metadata.ocId]) {
  1112. metadata.status = k_metadataStatusWaitUpload;
  1113. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1114. } else {
  1115. [self.sessionPendingStatusInUpload addObject:metadata.ocId];
  1116. }
  1117. }
  1118. if (metadatasInUpload.count == 0) {
  1119. [self.sessionPendingStatusInUpload removeAllObjects];
  1120. }
  1121. // Start Timer
  1122. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1123. }
  1124. - (void)startLoadAutoDownloadUpload
  1125. {
  1126. if (self.timerProcessAutoDownloadUpload.isValid) {
  1127. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1128. }
  1129. }
  1130. #pragma --------------------------------------------------------------------------------------------
  1131. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1132. #pragma --------------------------------------------------------------------------------------------
  1133. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1134. {
  1135. return YES;
  1136. }
  1137. // Method called from iOS system to send a file from other app.
  1138. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1139. {
  1140. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1141. return YES;
  1142. NSString *scheme = url.scheme;
  1143. dispatch_time_t timer = 0;
  1144. if (self.activeMain == nil) timer = 1;
  1145. if ([scheme isEqualToString:@"nextcloud"]) {
  1146. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1147. NSString *action = url.host;
  1148. if ([action isEqualToString:@"open-file"]) {
  1149. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1150. NSArray *queryItems = urlComponents.queryItems;
  1151. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1152. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1153. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1154. tableAccount *matchedAccount = nil;
  1155. // verify parameter
  1156. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1157. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1158. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1159. [alertController addAction:okAction];
  1160. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1161. } else {
  1162. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1163. if (account) {
  1164. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1165. NSString *activeAccountUser = account.user;
  1166. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1167. matchedAccount = account;
  1168. } else {
  1169. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1170. for (tableAccount *account in accounts) {
  1171. NSURL *accountURL = [NSURL URLWithString:account.url];
  1172. NSString *accountUser = account.user;
  1173. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1174. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1175. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1176. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1177. }
  1178. }
  1179. }
  1180. if (matchedAccount) {
  1181. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1182. UITabBarController *tbc;
  1183. if (splitViewController.isCollapsed) {
  1184. tbc = splitViewController.viewControllers.firstObject;
  1185. for (UINavigationController *nvc in tbc.viewControllers) {
  1186. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  1187. [nvc popToRootViewControllerAnimated:NO];
  1188. }
  1189. } else {
  1190. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  1191. [nvcDetail popToRootViewControllerAnimated:NO];
  1192. tbc = splitViewController.viewControllers.firstObject;
  1193. }
  1194. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1195. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  1196. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1197. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1198. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1199. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1200. if ([path containsString:@"/"]) {
  1201. // Push
  1202. NSString *directoryName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1203. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1204. 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:@""];
  1205. [self.activeMain performSegueDirectoryWithControlPasscode:true metadata:metadata blinkFileNamePath:fileNamePath];
  1206. } else {
  1207. // Reload folder
  1208. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1209. self.activeMain.blinkFileNamePath = fileNamePath;
  1210. [self.activeMain readFolder:serverUrl];
  1211. }
  1212. });
  1213. });
  1214. });
  1215. } else {
  1216. NSString *domain = [[NSURL URLWithString:link] host];
  1217. NSString *fileName = [path lastPathComponent];
  1218. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1219. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1220. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1221. [alertController addAction:okAction];
  1222. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1223. }
  1224. }
  1225. }
  1226. }
  1227. });
  1228. return YES;
  1229. }
  1230. NSError *error;
  1231. NSLog(@"[LOG] the path is: %@", url.path);
  1232. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1233. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1234. if (self.activeAccount) {
  1235. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1236. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1237. if (error == nil) {
  1238. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1239. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1240. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1241. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1242. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1243. });
  1244. }
  1245. }
  1246. return YES;
  1247. }
  1248. #pragma --------------------------------------------------------------------------------------------
  1249. #pragma mark ===== Maintenance Mode =====
  1250. #pragma --------------------------------------------------------------------------------------------
  1251. - (void)maintenanceMode:(BOOL)mode
  1252. {
  1253. self.maintenanceMode = mode;
  1254. }
  1255. #pragma --------------------------------------------------------------------------------------------
  1256. #pragma mark ===== UPGRADE =====
  1257. #pragma --------------------------------------------------------------------------------------------
  1258. - (BOOL)upgrade
  1259. {
  1260. #ifdef DEBUG
  1261. //self.maintenanceMode = YES;
  1262. #endif
  1263. NSString *actualVersion = [CCUtility getVersion];
  1264. NSString *actualBuild = [CCUtility getBuild];
  1265. /* ---------------------- UPGRADE VERSION ----------------------- */
  1266. // VERSION < 2.17.6
  1267. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1268. // Remove All old Photo Library
  1269. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1270. }
  1271. // VERSION == 2.17.6
  1272. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1273. // Build < 10
  1274. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1275. // Remove All old Photo Library
  1276. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1277. }
  1278. }
  1279. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1280. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1281. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1282. }
  1283. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1284. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1285. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1286. NSString *account = @"";
  1287. NSString *directoryUser = @"";
  1288. NSString *fileName;
  1289. for (tableLocalFile *record in records) {
  1290. if (![account isEqualToString:record.account]) {
  1291. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1292. if (tableAccount) {
  1293. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1294. account = record.account;
  1295. }
  1296. }
  1297. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.ocId];
  1298. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1299. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageOcId:record.ocId fileNameView:record.fileName]];
  1300. }
  1301. }
  1302. });
  1303. }
  1304. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1305. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1306. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1307. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1308. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1309. }
  1310. }
  1311. if (([actualVersion compare:@"2.23.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1312. NSArray *records = [[NCManageDatabase sharedInstance] getAllAccount];
  1313. for (tableAccount *record in records) {
  1314. [CCUtility setPassword:record.account password:record.password];
  1315. [[NCManageDatabase sharedInstance] removePasswordAccount:record.account];
  1316. }
  1317. }
  1318. return YES;
  1319. }
  1320. @end