AppDelegate.m 70 KB

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