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