AppDelegate.m 79 KB

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