AppDelegate.m 79 KB

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