AppDelegate.m 78 KB

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