AppDelegate.m 79 KB

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