AppDelegate.m 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  1. //
  2. // AppDelegate.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "AppDelegate.h"
  24. #import "CCNetworking.h"
  25. #import "CCGraphics.h"
  26. #import "CCSynchronize.h"
  27. #import "CCMain.h"
  28. #import "NCBridgeSwift.h"
  29. #import "NCAutoUpload.h"
  30. #import "NCPushNotificationEncryption.h"
  31. #import <QuartzCore/QuartzCore.h>
  32. @import Sentry;
  33. @class NCViewerRichdocument;
  34. @interface AppDelegate() <TOPasscodeViewControllerDelegate>
  35. @end
  36. @implementation AppDelegate
  37. + (void)initialize
  38. {
  39. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  40. }
  41. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  42. {
  43. if (![CCUtility getDisableCrashservice] && NCBrandOptions.sharedInstance.disable_crash_service == false) {
  44. [SentrySDK startWithOptions: @{
  45. @"dsn": @"https://42eaf570ec2646b1a564a4c4bfc8c279@o394108.ingest.sentry.io/5243836",
  46. @"debug": @(YES),
  47. @"enableAutoSessionTracking": @(YES)
  48. /* PRIVACY : https://github.com/getsentry/sentry-cocoa
  49. By default, we don’t apply the user identification provided to the SDK via the API. Instead, we use
  50. the installation ID generated with the first use of the application. The ID doesn’t contain any
  51. private or public data of your users or any public or shared data of their device.
  52. */
  53. }];
  54. }
  55. [CCUtility createDirectoryStandard];
  56. [CCUtility emptyTemporaryDirectory];
  57. // Networking
  58. [[NCCommunicationCommon shared] setupWithDelegate:[NCNetworking sharedInstance]];
  59. [[NCCommunicationCommon shared] setupWithUserAgent:[CCUtility getUserAgent] capabilitiesGroup:[NCBrandOptions sharedInstance].capabilitiesGroups];
  60. // 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.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) 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 sharedInstance] 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 sharedInstance] middlewarePing];
  192. }
  193. // verify task (download/upload) 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 sharedInstance] 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] setupWithUser:activeUser userId:activeUserID password:activePassword url:activeUrl];
  345. [self settingSetupCommunicationCapabilities:activeAccount];
  346. }
  347. - (void)deleteAccount:(NSString *)account wipe:(BOOL)wipe
  348. {
  349. [self unsubscribingNextcloudServerPushNotification:account url:self.activeUrl withSubscribing:false];
  350. [self settingActiveAccount:nil activeUrl:nil activeUser:nil activeUserID:nil activePassword:nil];
  351. /* DELETE ALL FILES LOCAL FS */
  352. NSArray *results = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", account] sorted:@"ocId" ascending:NO];
  353. for (tableLocalFile *result in results) {
  354. [CCUtility removeFileAtPath:[CCUtility getDirectoryProviderStorageOcId:result.ocId]];
  355. }
  356. // Clear database
  357. [[NCManageDatabase sharedInstance] clearDatabaseWithAccount:account removeAccount:true];
  358. [CCUtility clearAllKeysEndToEnd:account];
  359. [CCUtility clearAllKeysPushNotification:account];
  360. [CCUtility setCertificateError:account error:false];
  361. [CCUtility setPassword:account password:nil];
  362. if (wipe) {
  363. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  364. if ([listAccount count] > 0) {
  365. NSString *newAccount = listAccount[0];
  366. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:newAccount];
  367. [self settingActiveAccount:newAccount activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  368. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  369. } else {
  370. [self openLoginView:self.window.rootViewController selector:k_intro_login openLoginWeb:false];
  371. }
  372. }
  373. }
  374. - (void)settingSetupCommunicationCapabilities:(NSString *)account
  375. {
  376. NSInteger serverVersionMajor = [[NCManageDatabase sharedInstance] getCapabilitiesServerIntWithAccount:account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  377. if (serverVersionMajor > 0) {
  378. [[OCNetworking sharedManager].sharedOCCommunication setupNextcloudVersion: serverVersionMajor];
  379. [[NCCommunicationCommon shared] setupWithNextcloudVersion:serverVersionMajor];
  380. }
  381. NSString *webDavRoot = [[NCManageDatabase sharedInstance] getCapabilitiesServerStringWithAccount:account elements:NCElementsJSON.shared.capabilitiesWebDavRoot];
  382. if (webDavRoot != nil) {
  383. [[NCCommunicationCommon shared] setupWithWebDavRoot:webDavRoot];
  384. }
  385. }
  386. #pragma --------------------------------------------------------------------------------------------
  387. #pragma mark ===== Push Notifications =====
  388. #pragma --------------------------------------------------------------------------------------------
  389. - (void)pushNotification
  390. {
  391. // test
  392. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  393. return;
  394. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  395. NSString *token = [CCUtility getPushNotificationToken:result.account];
  396. if (![token isEqualToString:self.pushKitToken]) {
  397. if (token != nil) {
  398. // unsubscribing + subscribing
  399. [self unsubscribingNextcloudServerPushNotification:result.account url:result.url withSubscribing:true];
  400. } else {
  401. [self subscribingNextcloudServerPushNotification:result.account url:result.url];
  402. }
  403. }
  404. }
  405. }
  406. - (void)subscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url
  407. {
  408. // test
  409. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  410. return;
  411. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair:account];
  412. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken];
  413. NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account];
  414. NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding];
  415. [[OCNetworking sharedManager] subscribingPushNotificationWithAccount:account url:url pushToken:self.pushKitToken Hash:pushTokenHash devicePublicKey:pushDevicePublicKey completion:^(NSString *accountCompletion, NSString *deviceIdentifier, NSString *deviceIdentifierSignature, NSString *publicKey, NSString *message, NSInteger errorCode) {
  416. if (errorCode == 0 && [accountCompletion isEqualToString:account]) {
  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:deviceIdentifierSignature];
  421. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  422. } else if (errorCode != 0) {
  423. NSLog(@"[LOG] Subscribed to Push Notification server & proxy error.");
  424. } else {
  425. NSLog(@"[LOG] It has been changed user during networking process, error.");
  426. }
  427. }];
  428. }
  429. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url withSubscribing:(BOOL)subscribing
  430. {
  431. // test
  432. if (self.activeAccount.length == 0 || self.maintenanceMode)
  433. return;
  434. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  435. NSString *deviceIdentifierSignature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  436. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  437. [[OCNetworking sharedManager] unsubscribingPushNotificationWithAccount:account url:url deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  438. if (errorCode == 0) {
  439. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  440. [CCUtility setPushNotificationPublicKey:account data:nil];
  441. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  442. [CCUtility setPushNotificationPrivateKey:account data:nil];
  443. [CCUtility setPushNotificationToken:account token:nil];
  444. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  445. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  446. if (self.pushKitToken != nil && subscribing) {
  447. [self subscribingNextcloudServerPushNotification:account url:url];
  448. }
  449. } else if (errorCode != 0) {
  450. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy error.");
  451. } else {
  452. NSLog(@"[LOG] It has been changed user during networking process, error.");
  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 sharedInstance] deleteMetadata:metadata account:metadata.account user:account.user userID:account.userID password:[CCUtility getPassword:metadata.account] url:account.url completion:^(NSInteger errorCode, NSString *errorDescription) { }];
  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 sharedInstance] 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 sharedInstance] 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:@"tabBarFavorites"] 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:@"tabBarMedia"] 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 = 56;
  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 Download/Upload < k_timerProcess seconds > =====
  918. #pragma --------------------------------------------------------------------------------------------
  919. - (void)loadAutoDownloadUpload
  920. {
  921. if (self.activeAccount.length == 0 || self.maintenanceMode)
  922. return;
  923. tableMetadata *metadataForUpload, *metadataForDownload;
  924. long counterDownload = 0, counterUpload = 0;
  925. NSUInteger sizeDownload = 0, sizeUpload = 0;
  926. NSMutableArray *uploaded = [NSMutableArray new];
  927. NSPredicate *predicate;
  928. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  929. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  930. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  931. // E2EE only 1
  932. for(tableMetadata *metadata in metadatasDownload) {
  933. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:metadata.account]) return;
  934. }
  935. for(tableMetadata *metadata in metadatasUpload) {
  936. if ([CCUtility isFolderEncrypted:metadata.serverUrl e2eEncrypted:metadata.e2eEncrypted account:metadata.account]) return;
  937. }
  938. // Counter
  939. counterDownload = [metadatasDownload count];
  940. counterUpload = [metadatasUpload count];
  941. // Size
  942. for (tableMetadata *metadata in metadatasDownload) {
  943. sizeDownload = sizeDownload + metadata.size;
  944. }
  945. for (tableMetadata *metadata in metadatasUpload) {
  946. sizeUpload = sizeUpload + metadata.size;
  947. }
  948. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  949. // Stop Timer
  950. [_timerProcessAutoDownloadUpload invalidate];
  951. // ------------------------- <selector Download> -------------------------
  952. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  953. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"date" ascending:YES];
  954. if (metadataForDownload) {
  955. if ([CCUtility isFolderEncrypted:metadataForDownload.serverUrl e2eEncrypted:metadataForDownload.e2eEncrypted account:metadataForDownload.account]) {
  956. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  957. maxConcurrentOperationDownloadUpload = 1;
  958. metadataForDownload.status = k_metadataStatusInDownload;
  959. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  960. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  961. break;
  962. } else {
  963. metadataForDownload.status = k_metadataStatusInDownload;
  964. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  965. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  966. counterDownload++;
  967. sizeDownload = sizeDownload + metadata.size;
  968. }
  969. } else {
  970. break;
  971. }
  972. }
  973. // ------------------------- <selector Upload> -------------------------
  974. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  975. if (sizeUpload > k_maxSizeOperationUpload) {
  976. break;
  977. }
  978. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  979. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadFile, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  980. } else {
  981. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload];
  982. }
  983. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"date" ascending:YES];
  984. // Verify modify file
  985. if ([uploaded containsObject:[NSString stringWithFormat:@"%@%@%@", metadataForUpload.account, metadataForUpload.serverUrl, metadataForUpload.fileName]]) {
  986. break;
  987. }
  988. if (metadataForUpload) {
  989. // Verify modify file
  990. BOOL isAleadyInUpload = false;
  991. for (tableMetadata *metadata in metadatasUpload) {
  992. if ([metadataForUpload.account isEqualToString:metadata.account] && [metadataForUpload.serverUrl isEqualToString:metadata.serverUrl] && [metadataForUpload.fileName isEqualToString:metadata.fileName]) {
  993. isAleadyInUpload = true;
  994. }
  995. }
  996. if (isAleadyInUpload == false) {
  997. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  998. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  999. maxConcurrentOperationDownloadUpload = 1;
  1000. metadataForUpload.status = k_metadataStatusInUpload;
  1001. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1002. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1003. break;
  1004. } else {
  1005. metadataForUpload.status = k_metadataStatusInUpload;
  1006. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1007. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1008. counterUpload++;
  1009. sizeUpload = sizeUpload + metadata.size;
  1010. // For verify modify file
  1011. [uploaded addObject:[NSString stringWithFormat:@"%@%@%@", metadata.account, metadata.serverUrl, metadata.fileName]];
  1012. }
  1013. } else {
  1014. break;
  1015. }
  1016. } else {
  1017. break;
  1018. }
  1019. }
  1020. // ------------------------- <selector Auto Upload> -------------------------
  1021. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1022. if (sizeUpload > k_maxSizeOperationUpload) {
  1023. break;
  1024. }
  1025. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1026. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadAutoUpload, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  1027. } else {
  1028. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload];
  1029. }
  1030. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"date" ascending:YES];
  1031. if (metadataForUpload) {
  1032. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1033. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1034. maxConcurrentOperationDownloadUpload = 1;
  1035. metadataForUpload.status = k_metadataStatusInUpload;
  1036. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1037. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1038. break;
  1039. } else {
  1040. metadataForUpload.status = k_metadataStatusInUpload;
  1041. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1042. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1043. counterUpload++;
  1044. sizeUpload = sizeUpload + metadata.size;
  1045. }
  1046. } else {
  1047. break;
  1048. }
  1049. }
  1050. // ------------------------- <selector Auto Upload All> ----------------------
  1051. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1052. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:@"date" ascending:YES];
  1053. NSInteger errorCount = [metadatas count];
  1054. if (errorCount >= k_maxErrorAutoUploadAll) {
  1055. [[NCContentPresenter shared] messageNotification:@"_error_" description:@"_too_errors_automatic_all_" delay:k_dismissAfterSecond type:messageTypeError errorCode:k_CCErrorInternalError];
  1056. } else {
  1057. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1058. if (sizeUpload > k_maxSizeOperationUpload) {
  1059. break;
  1060. }
  1061. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1062. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d AND typeFile != %@", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload, k_metadataTypeFile_video];
  1063. } else {
  1064. predicate = [NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload];
  1065. }
  1066. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:predicate sorted:@"session" ascending:YES];
  1067. if (metadataForUpload) {
  1068. if ([CCUtility isFolderEncrypted:metadataForUpload.serverUrl e2eEncrypted:metadataForUpload.e2eEncrypted account:metadataForUpload.account]) {
  1069. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) { break; }
  1070. maxConcurrentOperationDownloadUpload = 1;
  1071. metadataForUpload.status = k_metadataStatusInUpload;
  1072. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1073. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1074. break;
  1075. } else {
  1076. metadataForUpload.status = k_metadataStatusInUpload;
  1077. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1078. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1079. counterUpload++;
  1080. sizeUpload = sizeUpload + metadata.size;
  1081. }
  1082. } else {
  1083. break;
  1084. }
  1085. }
  1086. }
  1087. // No Download/upload available ? --> remove errors for retry
  1088. //
  1089. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1090. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1091. for (tableMetadata *metadata in metadatas) {
  1092. if (metadata.status == k_metadataStatusDownloadError)
  1093. metadata.status = k_metadataStatusWaitDownload;
  1094. else if (metadata.status == k_metadataStatusUploadError)
  1095. metadata.status = k_metadataStatusWaitUpload;
  1096. [[NCManageDatabase sharedInstance] addMetadata:metadata];
  1097. }
  1098. }
  1099. // Upload in pending
  1100. //
  1101. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1102. for (tableMetadata *metadata in metadatasInUpload) {
  1103. if ([self.sessionPendingStatusInUpload containsObject:metadata.ocId]) {
  1104. metadata.status = k_metadataStatusWaitUpload;
  1105. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1106. } else {
  1107. [self.sessionPendingStatusInUpload addObject:metadata.ocId];
  1108. }
  1109. }
  1110. if (metadatasInUpload.count == 0) {
  1111. [self.sessionPendingStatusInUpload removeAllObjects];
  1112. }
  1113. // Start Timer
  1114. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1115. }
  1116. - (void)startLoadAutoDownloadUpload
  1117. {
  1118. if (self.timerProcessAutoDownloadUpload.isValid) {
  1119. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1120. }
  1121. }
  1122. - (void)verifyTaskLost
  1123. {
  1124. // DOWNLOAD
  1125. //
  1126. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusDownloading] sorted:nil ascending:true];
  1127. for (tableMetadata *metadata in matadatasInDownloading) {
  1128. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1129. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1130. NSURLSessionTask *findTask;
  1131. for (NSURLSessionTask *task in downloadTasks) {
  1132. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1133. findTask = task;
  1134. }
  1135. }
  1136. if (!findTask) {
  1137. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1138. metadata.status = k_metadataStatusWaitDownload;
  1139. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1140. }
  1141. }];
  1142. }
  1143. // UPLOAD
  1144. //
  1145. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1146. for (tableMetadata *metadata in metadatasUploading) {
  1147. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1148. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1149. NSURLSessionTask *findTask;
  1150. for (NSURLSessionTask *task in uploadTasks) {
  1151. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1152. findTask = task;
  1153. }
  1154. }
  1155. if (!findTask) {
  1156. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1157. metadata.status = k_metadataStatusWaitUpload;
  1158. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1159. }
  1160. }];
  1161. }
  1162. }
  1163. #pragma --------------------------------------------------------------------------------------------
  1164. #pragma mark ===== OpenURL =====
  1165. #pragma --------------------------------------------------------------------------------------------
  1166. // Method called from iOS system to send a file from other app.
  1167. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1168. {
  1169. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1170. return YES;
  1171. NSString *scheme = url.scheme;
  1172. dispatch_time_t timer = 0;
  1173. if (self.activeMain == nil) timer = 1;
  1174. if ([scheme isEqualToString:@"nextcloud"]) {
  1175. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1176. NSString *action = url.host;
  1177. if ([action isEqualToString:@"open-file"]) {
  1178. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1179. NSArray *queryItems = urlComponents.queryItems;
  1180. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1181. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1182. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1183. tableAccount *matchedAccount = nil;
  1184. // verify parameter
  1185. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1186. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1187. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1188. [alertController addAction:okAction];
  1189. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1190. } else {
  1191. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1192. if (account) {
  1193. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1194. NSString *activeAccountUser = account.user;
  1195. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1196. matchedAccount = account;
  1197. } else {
  1198. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1199. for (tableAccount *account in accounts) {
  1200. NSURL *accountURL = [NSURL URLWithString:account.url];
  1201. NSString *accountUser = account.user;
  1202. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1203. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1204. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1205. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_initializeMain object:nil userInfo:nil];
  1206. }
  1207. }
  1208. }
  1209. if (matchedAccount) {
  1210. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1211. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  1212. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1213. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1214. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1215. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1216. if (splitViewController.isCollapsed) {
  1217. [navigationControllerMaster popToRootViewControllerAnimated:false];
  1218. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1219. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1220. UITabBarController *tabBarController = (UITabBarController *)navigationControllerMaster.topViewController;
  1221. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1222. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1223. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1224. }
  1225. }
  1226. }
  1227. } else {
  1228. if ([tabBarController isKindOfClass:[UITabBarController class]]) {
  1229. [tabBarController setSelectedIndex: k_tabBarApplicationIndexFile];
  1230. }
  1231. }
  1232. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1233. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1234. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1235. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1236. if ([path containsString:@"/"]) {
  1237. // Push
  1238. NSString *fileName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1239. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1240. tableMetadata *metadata = [[NCManageDatabase sharedInstance] createMetadataWithAccount:matchedAccount.account fileName:fileName ocId:[[NSUUID UUID] UUIDString] serverUrl:serverUrl url:@"" contentType:@""];
  1241. [self.activeMain performSegueDirectoryWithMetadata:metadata blinkFileNamePath:fileNamePath];
  1242. } else {
  1243. // Reload folder
  1244. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1245. self.activeMain.blinkFileNamePath = fileNamePath;
  1246. [self.activeMain readFolder:serverUrl];
  1247. }
  1248. });
  1249. });
  1250. }
  1251. }
  1252. }
  1253. } else {
  1254. NSString *domain = [[NSURL URLWithString:link] host];
  1255. NSString *fileName = [path lastPathComponent];
  1256. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1257. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1258. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1259. [alertController addAction:okAction];
  1260. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1261. }
  1262. }
  1263. }
  1264. }
  1265. });
  1266. return YES;
  1267. }
  1268. NSError *error;
  1269. NSLog(@"[LOG] the path is: %@", url.path);
  1270. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1271. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1272. if (self.activeAccount) {
  1273. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1274. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1275. if (error == nil) {
  1276. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1277. if ([splitViewController isKindOfClass:[UISplitViewController class]]) {
  1278. UINavigationController *navigationControllerMaster = (UINavigationController *)splitViewController.viewControllers.firstObject;
  1279. if ([navigationControllerMaster isKindOfClass:[UINavigationController class]]) {
  1280. UIViewController *uploadNavigationViewController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1281. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1282. [navigationControllerMaster presentViewController:uploadNavigationViewController animated:YES completion:nil];
  1283. });
  1284. }
  1285. }
  1286. }
  1287. }
  1288. return YES;
  1289. }
  1290. #pragma --------------------------------------------------------------------------------------------
  1291. #pragma mark ===== Passcode + Delegate =====
  1292. #pragma --------------------------------------------------------------------------------------------
  1293. - (void)passcodeWithAutomaticallyPromptForBiometricValidation:(BOOL)automaticallyPromptForBiometricValidation
  1294. {
  1295. LAContext *laContext = [LAContext new];
  1296. NSError *error;
  1297. BOOL isBiometryAvailable = false;
  1298. if ([[CCUtility getPasscode] length] == 0 || [self.activeAccount length] == 0 || [CCUtility getNotPasscodeAtStart]) return;
  1299. if (!self.passcodeViewController.view.window) {
  1300. self.passcodeViewController = [[TOPasscodeViewController alloc] initWithStyle:TOPasscodeViewStyleTranslucentLight passcodeType:TOPasscodeTypeSixDigits];
  1301. if (@available(iOS 13.0, *)) {
  1302. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  1303. self.passcodeViewController.style = TOPasscodeViewStyleTranslucentDark;
  1304. }
  1305. }
  1306. self.passcodeViewController.delegate = self;
  1307. self.passcodeViewController.allowCancel = false;
  1308. self.passcodeViewController.keypadButtonShowLettering = false;
  1309. if ([laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
  1310. if (error == NULL) {
  1311. if (laContext.biometryType == LABiometryTypeFaceID) {
  1312. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeFaceID;
  1313. self.passcodeViewController.allowBiometricValidation = true;
  1314. isBiometryAvailable = true;
  1315. } else if (laContext.biometryType == LABiometryTypeTouchID) {
  1316. self.passcodeViewController.biometryType = TOPasscodeBiometryTypeTouchID;
  1317. self.passcodeViewController.allowBiometricValidation = true;
  1318. isBiometryAvailable = true;
  1319. } else {
  1320. isBiometryAvailable = false;
  1321. NSLog(@"No Biometric support");
  1322. }
  1323. }
  1324. }
  1325. [self.window.rootViewController presentViewController:self.passcodeViewController animated:YES completion:nil];
  1326. }
  1327. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1328. if (automaticallyPromptForBiometricValidation && self.passcodeViewController.view.window) {
  1329. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  1330. if (success) {
  1331. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1332. [self.passcodeViewController dismissViewControllerAnimated:YES completion:nil];
  1333. });
  1334. }
  1335. }];
  1336. }
  1337. });
  1338. }
  1339. - (void)didTapCancelInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1340. {
  1341. [passcodeViewController dismissViewControllerAnimated:YES completion:nil];
  1342. }
  1343. - (BOOL)passcodeViewController:(TOPasscodeViewController *)passcodeViewController isCorrectCode:(NSString *)code
  1344. {
  1345. return [code isEqualToString:[CCUtility getPasscode]];
  1346. }
  1347. - (void)didPerformBiometricValidationRequestInPasscodeViewController:(TOPasscodeViewController *)passcodeViewController
  1348. {
  1349. [[LAContext new] evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:[[NCBrandOptions sharedInstance] brand] reply:^(BOOL success, NSError * _Nullable error) {
  1350. if (success) {
  1351. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1352. [passcodeViewController dismissViewControllerAnimated:YES completion:nil];
  1353. });
  1354. }
  1355. }];
  1356. }
  1357. #pragma --------------------------------------------------------------------------------------------
  1358. #pragma mark ===== Maintenance Mode =====
  1359. #pragma --------------------------------------------------------------------------------------------
  1360. - (void)maintenanceMode:(BOOL)mode
  1361. {
  1362. self.maintenanceMode = mode;
  1363. }
  1364. #pragma --------------------------------------------------------------------------------------------
  1365. #pragma mark ===== UPGRADE =====
  1366. #pragma --------------------------------------------------------------------------------------------
  1367. - (BOOL)upgrade
  1368. {
  1369. #ifdef DEBUG
  1370. //self.maintenanceMode = YES;
  1371. #endif
  1372. NSString *actualVersion = [CCUtility getVersion];
  1373. NSString *actualBuild = [CCUtility getBuild];
  1374. /* ---------------------- UPGRADE VERSION ----------------------- */
  1375. // VERSION < 2.17.6
  1376. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1377. // Remove All old Photo Library
  1378. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1379. }
  1380. // VERSION == 2.17.6
  1381. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1382. // Build < 10
  1383. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1384. // Remove All old Photo Library
  1385. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1386. }
  1387. }
  1388. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1389. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1390. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1391. }
  1392. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1393. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1394. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1395. NSString *account = @"";
  1396. NSString *directoryUser = @"";
  1397. NSString *fileName;
  1398. for (tableLocalFile *record in records) {
  1399. if (![account isEqualToString:record.account]) {
  1400. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1401. if (tableAccount) {
  1402. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1403. account = record.account;
  1404. }
  1405. }
  1406. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.ocId];
  1407. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1408. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageOcId:record.ocId fileNameView:record.fileName]];
  1409. }
  1410. }
  1411. });
  1412. }
  1413. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1414. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1415. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1416. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1417. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1418. }
  1419. }
  1420. if (([actualVersion compare:@"2.23.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1421. NSArray *records = [[NCManageDatabase sharedInstance] getAllAccount];
  1422. for (tableAccount *record in records) {
  1423. [CCUtility setPassword:record.account password:record.password];
  1424. [[NCManageDatabase sharedInstance] removePasswordAccount:record.account];
  1425. }
  1426. }
  1427. return YES;
  1428. }
  1429. @end