AppDelegate.m 90 KB

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