AppDelegate.m 72 KB

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