AppDelegate.m 81 KB

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