AppDelegate.m 81 KB

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