AppDelegate.m 87 KB

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