AppDelegate.m 83 KB

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