AppDelegate.m 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  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 ===== PushNotification & PushKit Delegate =====
  318. #pragma --------------------------------------------------------------------------------------------
  319. - (void)pushNotification
  320. {
  321. // test
  322. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  323. return;
  324. NSString *token = [CCUtility getPushNotificationToken:self.activeAccount];
  325. if (![token isEqualToString:self.pushKitToken]) {
  326. if (token != nil) {
  327. // unsubscribing + subscribing
  328. [self unsubscribingNextcloudServerPushNotification:self.activeAccount url:self.activeUrl withSubscribing:true];
  329. } else {
  330. [self subscribingNextcloudServerPushNotification:self.activeAccount url:self.activeUrl];
  331. }
  332. }
  333. }
  334. - (void)subscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url
  335. {
  336. // test
  337. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  338. return;
  339. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair:account];
  340. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken];
  341. NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account];
  342. NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding];
  343. [[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) {
  344. if (errorCode == 0 && [accountCompletion isEqualToString:account]) {
  345. NSLog(@"[LOG] Subscribed to Push Notification server & proxy successfully.");
  346. [CCUtility setPushNotificationToken:account token:self.pushKitToken];
  347. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier];
  348. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:deviceIdentifierSignature];
  349. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  350. } else if (errorCode != 0) {
  351. NSLog(@"[LOG] Subscribed to Push Notification server & proxy error.");
  352. } else {
  353. NSLog(@"[LOG] It has been changed user during networking process, error.");
  354. }
  355. }];
  356. }
  357. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url withSubscribing:(BOOL)subscribing
  358. {
  359. // test
  360. if (self.activeAccount.length == 0 || self.maintenanceMode)
  361. return;
  362. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  363. NSString *deviceIdentifierSignature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  364. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  365. [[OCNetworking sharedManager] unsubscribingPushNotificationWithAccount:account url:url deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  366. if (errorCode == 0) {
  367. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  368. [CCUtility setPushNotificationPublicKey:account data:nil];
  369. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  370. [CCUtility setPushNotificationPrivateKey:account data:nil];
  371. [CCUtility setPushNotificationToken:account token:nil];
  372. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  373. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  374. if (self.pushKitToken != nil && subscribing) {
  375. [self subscribingNextcloudServerPushNotification:account url:url];
  376. }
  377. } else if (errorCode != 0) {
  378. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy error.");
  379. } else {
  380. NSLog(@"[LOG] It has been changed user during networking process, error.");
  381. }
  382. }];
  383. }
  384. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  385. {
  386. //Called when a notification is delivered to a foreground app.
  387. completionHandler(UNNotificationPresentationOptionAlert);
  388. }
  389. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  390. {
  391. completionHandler();
  392. }
  393. /*
  394. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  395. {
  396. NSLog(@"Push notification: %@", userInfo);
  397. NSUInteger fetchResult = UIBackgroundFetchResultNoData;
  398. NSString *message = [userInfo objectForKey:@"subject"];
  399. if (message) {
  400. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  401. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  402. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey: [CCUtility getPushNotificationPrivateKey:result.account]];
  403. if (decryptedMessage) {
  404. UNMutableNotificationContent *content = [UNMutableNotificationContent new];
  405. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  406. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  407. NSString *app = [json objectForKey:@"app"];
  408. NSString *subject = [json objectForKey:@"subject"];
  409. NSInteger notificationId = [[json objectForKey:@"nid"] integerValue];
  410. if ([app isEqualToString:@"spreed"]) {
  411. content.title = @"Nextcloud Talk";
  412. } else {
  413. content.title = app.capitalizedString;
  414. }
  415. content.title = [NSString stringWithFormat:@"%@ (%@)", content.title, result.account];
  416. if (subject) {
  417. content.body = subject;
  418. } else {
  419. content.body = @"Nextcloud notification";
  420. }
  421. [[OCNetworking sharedManager] getServerNotification:result.url notificationId:notificationId completion:^(NSDictionary *json, NSString *message, NSInteger errorCode) {
  422. //
  423. }];
  424. content.sound = [UNNotificationSound defaultSound];
  425. NSString *identifier = [NSString stringWithFormat:@"Notification-%@", [NSDate new]];
  426. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
  427. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
  428. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
  429. fetchResult = UIBackgroundFetchResultNewData;
  430. break;
  431. }
  432. }
  433. }
  434. }
  435. completionHandler(fetchResult);
  436. }
  437. - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken
  438. {
  439. // test
  440. if (self.activeAccount.length == 0 || self.maintenanceMode)
  441. return;
  442. NSLog(@"FCM registration token: %@", fcmToken);
  443. NSString *token = [CCUtility getPushNotificationToken:self.activeAccount];
  444. if (![token isEqualToString:fcmToken]) {
  445. if (token != nil) {
  446. // unsubscribing + subscribing
  447. [self unsubscribingNextcloudServerPushNotification:self.activeAccount url:self.activeUrl token:fcmToken];
  448. } else {
  449. [self subscribingNextcloudServerPushNotification:self.activeAccount url:self.activeUrl token:fcmToken];
  450. }
  451. }
  452. }
  453. */
  454. - (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type
  455. {
  456. // test
  457. if (self.activeAccount.length == 0 || self.maintenanceMode)
  458. return;
  459. self.pushKitToken = [self stringWithDeviceToken:credentials.token];
  460. [self pushNotification];
  461. }
  462. - (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type
  463. {
  464. NSString *message = [payload.dictionaryPayload objectForKey:@"subject"];
  465. if (message) {
  466. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  467. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  468. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey: [CCUtility getPushNotificationPrivateKey:result.account]];
  469. if (decryptedMessage) {
  470. UNMutableNotificationContent *content = [UNMutableNotificationContent new];
  471. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  472. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  473. NSString *app = [json objectForKey:@"app"];
  474. NSString *subject = [json objectForKey:@"subject"];
  475. NSInteger notificationId = [[json objectForKey:@"nid"] integerValue];
  476. NSURL *url = [NSURL URLWithString:result.url];
  477. NSString *domain = [url host];
  478. if ([app isEqualToString:@"spreed"]) {
  479. content.title = @"Nextcloud Talk";
  480. } else {
  481. content.title = app.capitalizedString;
  482. }
  483. content.title = [NSString stringWithFormat:@"%@ - %@ (%@)", content.title, result.displayName, domain];
  484. if (subject) {
  485. content.body = subject;
  486. } else {
  487. content.body = @"Nextcloud notification";
  488. }
  489. content.sound = [UNNotificationSound defaultSound];
  490. [[OCNetworking sharedManager] getServerNotification:result.url notificationId:notificationId completion:^(NSDictionary *json, NSString *message, NSInteger errorCode) {
  491. //
  492. }];
  493. NSString *identifier = [NSString stringWithFormat:@"Notification-%@", [NSDate new]];
  494. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
  495. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
  496. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
  497. break;
  498. }
  499. }
  500. }
  501. }
  502. }
  503. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  504. {
  505. const char *data = [deviceToken bytes];
  506. NSMutableString *token = [NSMutableString string];
  507. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  508. [token appendFormat:@"%02.2hhX", data[i]];
  509. }
  510. return [token copy];
  511. }
  512. #pragma --------------------------------------------------------------------------------------------
  513. #pragma mark ===== Quick Actions - ShotcutItem =====
  514. #pragma --------------------------------------------------------------------------------------------
  515. - (void)configDynamicShortcutItems
  516. {
  517. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  518. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  519. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  520. // add the array to our app
  521. if (shortcutMedia)
  522. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  523. }
  524. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  525. {
  526. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  527. completionHandler(handledShortCutItem);
  528. }
  529. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  530. {
  531. BOOL handled = NO;
  532. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  533. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  534. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  535. dispatch_async(dispatch_get_main_queue(), ^{
  536. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  537. if (splitViewController.isCollapsed) {
  538. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  539. for (UINavigationController *nvc in tbc.viewControllers) {
  540. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  541. [nvc popToRootViewControllerAnimated:NO];
  542. }
  543. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  544. } else {
  545. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  546. [nvcDetail popToRootViewControllerAnimated:NO];
  547. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  548. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  549. }
  550. });
  551. handled = YES;
  552. }
  553. return handled;
  554. }
  555. #pragma --------------------------------------------------------------------------------------------
  556. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  557. #pragma --------------------------------------------------------------------------------------------
  558. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  559. {
  560. static NSInteger errorCodePrev = 0;
  561. dispatch_async(dispatch_get_main_queue(), ^{
  562. if (visible) {
  563. switch (errorcode) {
  564. // JDStatusBarNotification
  565. case kCFURLErrorNotConnectedToInternet :
  566. if (errorCodePrev != errorcode)
  567. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  568. errorCodePrev = errorcode;
  569. break;
  570. // TWMessageBarManager
  571. default:
  572. if (description.length > 0) {
  573. [TWMessageBarManager sharedInstance].styleSheet = self;
  574. [[TWMessageBarManager sharedInstance] showMessageWithTitle:[NSString stringWithFormat:@"%@\n", NSLocalizedString(title, nil)] description:NSLocalizedString(description, nil) type:type duration:delay];
  575. }
  576. break;
  577. }
  578. } else {
  579. [[TWMessageBarManager sharedInstance] hideAllAnimated:YES];
  580. }
  581. });
  582. }
  583. - (UIColor *)backgroundColorForMessageType:(TWMessageBarMessageType)type
  584. {
  585. UIColor *backgroundColor = nil;
  586. switch (type)
  587. {
  588. case TWMessageBarMessageTypeError:
  589. backgroundColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.90];
  590. break;
  591. case TWMessageBarMessageTypeSuccess:
  592. backgroundColor = [UIColor colorWithRed:0.588 green:0.797 blue:0.000 alpha:0.90];
  593. break;
  594. case TWMessageBarMessageTypeInfo:
  595. backgroundColor = [NCBrandColor sharedInstance].brand;
  596. break;
  597. default:
  598. break;
  599. }
  600. return backgroundColor;
  601. }
  602. - (UIColor *)strokeColorForMessageType:(TWMessageBarMessageType)type
  603. {
  604. UIColor *strokeColor = nil;
  605. switch (type)
  606. {
  607. case TWMessageBarMessageTypeError:
  608. strokeColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];
  609. break;
  610. case TWMessageBarMessageTypeSuccess:
  611. strokeColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0];
  612. break;
  613. case TWMessageBarMessageTypeInfo:
  614. strokeColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0];
  615. break;
  616. default:
  617. break;
  618. }
  619. return strokeColor;
  620. }
  621. - (UIImage *)iconImageForMessageType:(TWMessageBarMessageType)type
  622. {
  623. UIImage *iconImage = nil;
  624. switch (type)
  625. {
  626. case TWMessageBarMessageTypeError:
  627. iconImage = [UIImage imageNamed:@"icon-error.png"];
  628. break;
  629. case TWMessageBarMessageTypeSuccess:
  630. iconImage = [UIImage imageNamed:@"icon-success.png"];
  631. break;
  632. case TWMessageBarMessageTypeInfo:
  633. iconImage = [UIImage imageNamed:@"icon-info.png"];
  634. break;
  635. default:
  636. break;
  637. }
  638. return iconImage;
  639. }
  640. - (void)updateApplicationIconBadgeNumber
  641. {
  642. if (self.activeAccount.length == 0 || self.maintenanceMode)
  643. return;
  644. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  645. 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];
  646. 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];
  647. NSInteger total = counterDownload + counterUpload;
  648. dispatch_async(dispatch_get_main_queue(), ^{
  649. [UIApplication sharedApplication].applicationIconBadgeNumber = total;
  650. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  651. if ([[splitViewController.viewControllers firstObject] isKindOfClass:[UITabBarController class]]) {
  652. UITabBarController *tbc = [splitViewController.viewControllers firstObject];
  653. UITabBarItem *tbItem = [tbc.tabBar.items objectAtIndex:0];
  654. if (total > 0) {
  655. [tbItem setBadgeValue:[NSString stringWithFormat:@"%li", (unsigned long)total]];
  656. } else {
  657. [tbItem setBadgeValue:nil];
  658. }
  659. }
  660. });
  661. });
  662. }
  663. #pragma --------------------------------------------------------------------------------------------
  664. #pragma mark ===== TabBarController =====
  665. #pragma --------------------------------------------------------------------------------------------
  666. - (void)createTabBarController:(UITabBarController *)tabBarController
  667. {
  668. UITabBarItem *item;
  669. NSLayoutConstraint *constraint;
  670. CGFloat multiplier = 0;
  671. CGFloat safeAreaBottom = 0;
  672. if (@available(iOS 11, *)) {
  673. UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
  674. if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
  675. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.right/2;
  676. if (safeAreaBottom > 0) safeAreaBottom -= 5;
  677. } else {
  678. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom/2;
  679. }
  680. }
  681. [self aspectTabBar:tabBarController.tabBar hidden:NO];
  682. // File
  683. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFile];
  684. [item setTitle:NSLocalizedString(@"_home_", nil)];
  685. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  686. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  687. // Favorites
  688. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexFavorite];
  689. [item setTitle:NSLocalizedString(@"_favorites_", nil)];
  690. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  691. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarFavorites"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  692. // (PLUS)
  693. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexPlusHide];
  694. item.title = @"";
  695. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[UIColor clearColor]];
  696. item.enabled = false;
  697. // Media
  698. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMedia];
  699. [item setTitle:NSLocalizedString(@"_media_", nil)];
  700. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  701. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMedia"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  702. // More
  703. item = [tabBarController.tabBar.items objectAtIndex: k_tabBarApplicationIndexMore];
  704. [item setTitle:NSLocalizedString(@"_more_", nil)];
  705. item.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  706. item.selectedImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarMore"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  707. // Plus Button
  708. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  709. UIButton *buttonPlus = [UIButton buttonWithType:UIButtonTypeCustom];
  710. buttonPlus.tag = 99;
  711. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  712. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  713. [buttonPlus addTarget:self action:@selector(handleTouchTabbarCenter:) forControlEvents:UIControlEventTouchUpInside];
  714. [buttonPlus setTranslatesAutoresizingMaskIntoConstraints:NO];
  715. [tabBarController.tabBar addSubview:buttonPlus];
  716. multiplier = 1.0;
  717. // X
  718. constraint =[NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterX multiplier:multiplier constant:0];
  719. [tabBarController.view addConstraint:constraint];
  720. // Y
  721. if (safeAreaBottom == 0) {
  722. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:multiplier constant:0];
  723. } else {
  724. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:5];
  725. }
  726. [tabBarController.view addConstraint:constraint];
  727. multiplier = 0.8 * (tabBarController.tabBar.frame.size.height - safeAreaBottom) / tabBarController.tabBar.frame.size.height;
  728. // Width
  729. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  730. [tabBarController.view addConstraint:constraint];
  731. // Height
  732. constraint = [NSLayoutConstraint constraintWithItem:buttonPlus attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:tabBarController.tabBar attribute:NSLayoutAttributeHeight multiplier:multiplier constant:0];
  733. [tabBarController.view addConstraint:constraint];
  734. }
  735. - (void)aspectNavigationControllerBar:(UINavigationBar *)nav online:(BOOL)online hidden:(BOOL)hidden
  736. {
  737. nav.translucent = NO;
  738. nav.barTintColor = [NCBrandColor sharedInstance].brand;
  739. nav.tintColor = [NCBrandColor sharedInstance].brandText;
  740. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].brandText}];
  741. // Change bar bottom line shadow
  742. nav.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  743. if (!online)
  744. [nav setTitleTextAttributes:@{NSForegroundColorAttributeName : [NCBrandColor sharedInstance].connectionNo}];
  745. nav.hidden = hidden;
  746. [nav setAlpha:1];
  747. }
  748. - (void)aspectTabBar:(UITabBar *)tab hidden:(BOOL)hidden
  749. {
  750. tab.translucent = NO;
  751. tab.barTintColor = [NCBrandColor sharedInstance].tabBar;
  752. tab.tintColor = [NCBrandColor sharedInstance].brandElement;
  753. tab.hidden = hidden;
  754. [tab setAlpha:1];
  755. }
  756. - (void)plusButtonVisibile:(BOOL)visible
  757. {
  758. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  759. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  760. UIButton *buttonPlus = [tabBarController.view viewWithTag:99];
  761. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  762. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateNormal];
  763. [buttonPlus setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  764. if (buttonPlus) {
  765. if (visible) {
  766. buttonPlus.hidden = false;
  767. } else {
  768. buttonPlus.hidden = true;
  769. }
  770. }
  771. }
  772. - (void)handleTouchTabbarCenter:(id)sender
  773. {
  774. // Test Maintenance
  775. if (self.maintenanceMode)
  776. return;
  777. UIView *view = [(UIButton *)sender superview];
  778. NCCreateMenuAdd *menuAdd = [[NCCreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brandElement];
  779. [menuAdd createMenuWithViewController:self.window.rootViewController view:view];
  780. }
  781. - (void)selectedTabBarController:(NSInteger)index
  782. {
  783. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  784. if (splitViewController.isCollapsed) {
  785. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  786. for (UINavigationController *nvc in tbc.viewControllers) {
  787. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  788. [nvc popToRootViewControllerAnimated:NO];
  789. }
  790. [tbc setSelectedIndex: index];
  791. } else {
  792. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  793. [nvcDetail popToRootViewControllerAnimated:NO];
  794. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  795. [tbc setSelectedIndex: index];
  796. }
  797. }
  798. - (NSString *)getTabBarControllerActiveServerUrl
  799. {
  800. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  801. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  802. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  803. NSInteger index = tabBarController.selectedIndex;
  804. // select active serverUrl
  805. if (index == k_tabBarApplicationIndexFile) {
  806. serverUrl = self.activeMain.serverUrl;
  807. } else if (index == k_tabBarApplicationIndexFavorite) {
  808. if (self.activeFavorites.serverUrl)
  809. serverUrl = self.activeFavorites.serverUrl;
  810. } else if (index == k_tabBarApplicationIndexMedia) {
  811. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  812. }
  813. return serverUrl;
  814. }
  815. #pragma --------------------------------------------------------------------------------------------
  816. #pragma mark ===== Theming Color =====
  817. #pragma --------------------------------------------------------------------------------------------
  818. - (void)settingThemingColorBrand
  819. {
  820. if (self.activeAccount.length == 0 || self.maintenanceMode)
  821. return;
  822. if ([NCBrandOptions sharedInstance].use_themingColor) {
  823. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  824. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  825. } else {
  826. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  827. [NCBrandColor sharedInstance].brandElement = [NCBrandColor sharedInstance].customer;
  828. [NCBrandColor sharedInstance].brandText = [NCBrandColor sharedInstance].customerText;
  829. }
  830. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  831. }
  832. - (void)changeTheming:(UIViewController *)vc
  833. {
  834. // Change Navigation & TabBar color
  835. vc.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  836. vc.tabBarController.tabBar.tintColor = [NCBrandColor sharedInstance].brandElement;
  837. // Change bar bottom line shadow
  838. vc.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  839. // Change button Plus
  840. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  841. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  842. UIButton *button = [tabBarController.view viewWithTag:99];
  843. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  844. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  845. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  846. // Tint Color GLOBAL WINDOW
  847. [self.window setTintColor:[NCBrandColor sharedInstance].textView];
  848. }
  849. #pragma --------------------------------------------------------------------------------------------
  850. #pragma mark ===== Manager Passcode =====
  851. #pragma --------------------------------------------------------------------------------------------
  852. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  853. {
  854. // ServerUrl active
  855. NSString *serverUrl = self.activeMain.serverUrl;
  856. BOOL isBlockZone = false;
  857. // fermiamo la data della sessione
  858. self.sessionePasscodeLock = nil;
  859. // se il block code è a zero esci con NON attivare la richiesta password
  860. if ([[CCUtility getBlockCode] length] == 0) return NO;
  861. // se non c'è attivo un account esci con NON attivare la richiesta password
  862. if ([self.activeAccount length] == 0) return NO;
  863. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  864. if (serverUrl && _activeUrl) {
  865. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  866. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  867. if (directory.lock) {
  868. isBlockZone = true;
  869. break;
  870. } else {
  871. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  872. if (serverUrl == self.activeUrl)
  873. break;
  874. }
  875. }
  876. }
  877. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  878. return YES;
  879. }
  880. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  881. {
  882. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  883. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  884. viewController.delegate = self;
  885. viewController.title = [NCBrandOptions sharedInstance].brand;
  886. viewController.fromType = CCBKPasscodeFromLockScreen;
  887. viewController.inputViewTitlePassword = YES;
  888. if ([CCUtility getSimplyBlockCode]) {
  889. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  890. viewController.passcodeInputView.maximumLength = 6;
  891. } else {
  892. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  893. viewController.passcodeInputView.maximumLength = 64;
  894. }
  895. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  896. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  897. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  898. return navigationController;
  899. }
  900. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  901. {
  902. [aViewController dismissViewControllerAnimated:YES completion:nil];
  903. // is a lock screen
  904. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  905. [aViewController dismissViewControllerAnimated:YES completion:nil];
  906. // start session Passcode Lock
  907. BOOL isBlockZone = false;
  908. NSString *serverUrl = self.activeMain.serverUrl;
  909. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  910. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  911. if (directory.lock) {
  912. isBlockZone = true;
  913. break;
  914. } else {
  915. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  916. if (serverUrl == self.activeUrl)
  917. break;
  918. }
  919. }
  920. if (isBlockZone)
  921. self.sessionePasscodeLock = [NSDate date];
  922. }
  923. }
  924. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  925. {
  926. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  927. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  928. //self.lockUntilDate = nil;
  929. //self.failedAttempts = 0;
  930. aResultHandler(YES);
  931. } else aResultHandler(NO);
  932. } else aResultHandler(YES);
  933. }
  934. #pragma --------------------------------------------------------------------------------------------
  935. #pragma mark ===== reachabilityChanged =====
  936. #pragma --------------------------------------------------------------------------------------------
  937. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  938. {
  939. if ([self.reachability isReachable]) {
  940. if (self.lastReachability == NO) {
  941. NSLog(@"[LOG] Request Service Server Nextcloud");
  942. [[NCService sharedInstance] startRequestServicesServer];
  943. }
  944. NSLog(@"[LOG] Reachability Changed: Reachable");
  945. self.lastReachability = YES;
  946. } else {
  947. if (self.lastReachability == YES) {
  948. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  949. }
  950. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  951. self.lastReachability = NO;
  952. }
  953. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  954. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  955. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  956. }
  957. #pragma --------------------------------------------------------------------------------------------
  958. #pragma mark ===== Fetch =====
  959. #pragma --------------------------------------------------------------------------------------------
  960. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  961. {
  962. // Test Maintenance
  963. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  964. completionHandler(UIBackgroundFetchResultNoData);
  965. return;
  966. }
  967. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  968. // Verify new photo
  969. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  970. // after 20 sec
  971. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  972. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  973. if ([records count] > 0) {
  974. completionHandler(UIBackgroundFetchResultNewData);
  975. } else {
  976. completionHandler(UIBackgroundFetchResultNoData);
  977. }
  978. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  979. });
  980. }
  981. #pragma --------------------------------------------------------------------------------------------
  982. #pragma mark ===== Operation Networking & Session =====
  983. #pragma --------------------------------------------------------------------------------------------
  984. //
  985. // Method called by the system when all the background task has end
  986. //
  987. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  988. {
  989. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  990. // after 20 sec
  991. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  992. self.backgroundSessionCompletionHandler = completionHandler;
  993. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  994. self.backgroundSessionCompletionHandler = nil;
  995. completionHandler();
  996. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  997. });
  998. }
  999. #pragma --------------------------------------------------------------------------------------------
  1000. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  1001. #pragma --------------------------------------------------------------------------------------------
  1002. - (void)loadAutoDownloadUpload
  1003. {
  1004. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1005. return;
  1006. tableMetadata *metadataForUpload, *metadataForDownload;
  1007. long counterDownload = 0, counterUpload = 0;
  1008. NSUInteger sizeDownload = 0, sizeUpload = 0;
  1009. BOOL isE2EE = false;
  1010. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  1011. // Detect E2EE
  1012. NSString *saveserverUrl = @"";
  1013. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status != %d", k_metadataStatusNormal] sorted:@"serverUrl" ascending:NO];
  1014. for (tableMetadata *metadata in metadatasForE2EE) {
  1015. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  1016. saveserverUrl = metadata.serverUrl;
  1017. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  1018. isE2EE = true;
  1019. break;
  1020. }
  1021. }
  1022. }
  1023. // E2EE : not in background
  1024. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  1025. return;
  1026. }
  1027. // E2EE : only 1 operation
  1028. if (isE2EE) {
  1029. maxConcurrentOperationDownloadUpload = 1;
  1030. }
  1031. // Stop Timer
  1032. [_timerProcessAutoDownloadUpload invalidate];
  1033. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  1034. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  1035. // Counter
  1036. counterDownload = [metadatasDownload count];
  1037. counterUpload = [metadatasUpload count];
  1038. // Size
  1039. for (tableMetadata *metadata in metadatasDownload) {
  1040. sizeDownload = sizeDownload + metadata.size;
  1041. }
  1042. for (tableMetadata *metadata in metadatasUpload) {
  1043. sizeUpload = sizeUpload + metadata.size;
  1044. }
  1045. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] -PROCESS-AUTO-UPLOAD- | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  1046. // ------------------------- <selector Download> -------------------------
  1047. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  1048. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"session" ascending:YES];
  1049. if (metadataForDownload) {
  1050. metadataForDownload.status = k_metadataStatusInDownload;
  1051. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  1052. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  1053. counterDownload++;
  1054. sizeDownload = sizeDownload + metadata.size;
  1055. } else {
  1056. break;
  1057. }
  1058. }
  1059. // ------------------------- <selector Upload> -------------------------
  1060. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1061. if (sizeUpload > k_maxSizeOperationUpload) {
  1062. break;
  1063. }
  1064. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1065. if (metadataForUpload) {
  1066. if ([metadataForUpload.session isEqualToString:k_upload_session_extension]) {
  1067. metadataForUpload.session = k_upload_session;
  1068. }
  1069. metadataForUpload.status = k_metadataStatusInUpload;
  1070. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1071. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1072. counterUpload++;
  1073. sizeUpload = sizeUpload + metadata.size;
  1074. } else {
  1075. break;
  1076. }
  1077. }
  1078. // ------------------------- <selector Auto Upload> -------------------------
  1079. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1080. if (sizeUpload > k_maxSizeOperationUpload) {
  1081. break;
  1082. }
  1083. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1084. if (metadataForUpload) {
  1085. metadataForUpload.status = k_metadataStatusInUpload;
  1086. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1087. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1088. counterUpload++;
  1089. sizeUpload = sizeUpload + metadata.size;
  1090. } else {
  1091. break;
  1092. }
  1093. }
  1094. // ------------------------- <selector Auto Upload All> ----------------------
  1095. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1096. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1097. NSInteger errorCount = [metadatas count];
  1098. if (errorCount >= k_maxErrorAutoUploadAll) {
  1099. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1100. } else {
  1101. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1102. if (sizeUpload > k_maxSizeOperationUpload) {
  1103. break;
  1104. }
  1105. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1106. if (metadataForUpload) {
  1107. metadataForUpload.status = k_metadataStatusInUpload;
  1108. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1109. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1110. counterUpload++;
  1111. sizeUpload = sizeUpload + metadata.size;
  1112. } else {
  1113. break;
  1114. }
  1115. }
  1116. }
  1117. // No Download/upload available ? --> remove errors for retry
  1118. //
  1119. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1120. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1121. for (tableMetadata *metadata in metadatas) {
  1122. if (metadata.status == k_metadataStatusDownloadError)
  1123. metadata.status = k_metadataStatusWaitDownload;
  1124. else if (metadata.status == k_metadataStatusUploadError)
  1125. metadata.status = k_metadataStatusWaitUpload;
  1126. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1127. }
  1128. }
  1129. // Verify internal error download (lost task)
  1130. //
  1131. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_download_session_extension, k_metadataStatusDownloading] sorted:nil ascending:true];
  1132. for (tableMetadata *metadata in matadatasInDownloading) {
  1133. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1134. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1135. NSURLSessionTask *findTask;
  1136. for (NSURLSessionTask *task in downloadTasks) {
  1137. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1138. findTask = task;
  1139. }
  1140. }
  1141. if (!findTask) {
  1142. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1143. metadata.status = k_metadataStatusWaitDownload;
  1144. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1145. }
  1146. }];
  1147. }
  1148. // Verify internal error upload (lost task)
  1149. //
  1150. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1151. for (tableMetadata *metadata in metadatasUploading) {
  1152. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1153. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1154. NSURLSessionTask *findTask;
  1155. for (NSURLSessionTask *task in uploadTasks) {
  1156. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1157. findTask = task;
  1158. }
  1159. }
  1160. if (!findTask) {
  1161. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1162. metadata.status = k_metadataStatusWaitUpload;
  1163. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1164. }
  1165. }];
  1166. }
  1167. // Upload in pending
  1168. //
  1169. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1170. for (tableMetadata *metadata in metadatasInUpload) {
  1171. if ([self.sessionPendingStatusInUpload containsObject:metadata.fileID]) {
  1172. metadata.status = k_metadataStatusWaitUpload;
  1173. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1174. } else {
  1175. [self.sessionPendingStatusInUpload addObject:metadata.fileID];
  1176. }
  1177. }
  1178. if (metadatasInUpload.count == 0) {
  1179. [self.sessionPendingStatusInUpload removeAllObjects];
  1180. }
  1181. // Start Timer
  1182. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1183. }
  1184. - (void)startLoadAutoDownloadUpload
  1185. {
  1186. if (self.timerProcessAutoDownloadUpload.isValid) {
  1187. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1188. }
  1189. }
  1190. #pragma --------------------------------------------------------------------------------------------
  1191. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1192. #pragma --------------------------------------------------------------------------------------------
  1193. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1194. {
  1195. return YES;
  1196. }
  1197. // Method called from iOS system to send a file from other app.
  1198. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1199. {
  1200. NSError *error;
  1201. NSLog(@"[LOG] the path is: %@", url.path);
  1202. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1203. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1204. if (self.activeAccount) {
  1205. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1206. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1207. if (error == nil) {
  1208. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1209. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1210. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1211. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1212. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1213. });
  1214. }
  1215. }
  1216. return YES;
  1217. }
  1218. #pragma --------------------------------------------------------------------------------------------
  1219. #pragma mark ===== Maintenance Mode =====
  1220. #pragma --------------------------------------------------------------------------------------------
  1221. - (void)maintenanceMode:(BOOL)mode
  1222. {
  1223. self.maintenanceMode = mode;
  1224. }
  1225. #pragma --------------------------------------------------------------------------------------------
  1226. #pragma mark ===== UPGRADE =====
  1227. #pragma --------------------------------------------------------------------------------------------
  1228. - (BOOL)upgrade
  1229. {
  1230. #ifdef DEBUG
  1231. //self.maintenanceMode = YES;
  1232. #endif
  1233. NSString *actualVersion = [CCUtility getVersion];
  1234. NSString *actualBuild = [CCUtility getBuild];
  1235. /* ---------------------- UPGRADE VERSION ----------------------- */
  1236. // VERSION < 2.17.6
  1237. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1238. // Remove All old Photo Library
  1239. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1240. }
  1241. // VERSION == 2.17.6
  1242. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1243. // Build < 10
  1244. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1245. // Remove All old Photo Library
  1246. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1247. }
  1248. }
  1249. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1250. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1251. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1252. }
  1253. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1254. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1255. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1256. NSString *account = @"";
  1257. NSString *directoryUser = @"";
  1258. NSString *fileName;
  1259. for (tableLocalFile *record in records) {
  1260. if (![account isEqualToString:record.account]) {
  1261. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1262. if (tableAccount) {
  1263. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1264. account = record.account;
  1265. }
  1266. }
  1267. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.fileID];
  1268. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1269. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageFileID:record.fileID fileNameView:record.fileName]];
  1270. }
  1271. }
  1272. });
  1273. }
  1274. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1275. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1276. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1277. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1278. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1279. }
  1280. }
  1281. return YES;
  1282. }
  1283. @end