AppDelegate.m 87 KB

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