AppDelegate.m 82 KB

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