AppDelegate.m 80 KB

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