AppDelegate.m 81 KB

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