AppDelegate.m 70 KB

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