AppDelegate.m 84 KB

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