AppDelegate.m 80 KB

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