AppDelegate.m 84 KB

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