AppDelegate.m 80 KB

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