AppDelegate.m 80 KB

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