AppDelegate.m 81 KB

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