AppDelegate.m 80 KB

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