AppDelegate.m 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  1. //
  2. // AppDelegate.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "AppDelegate.h"
  24. #import <JDStatusBarNotification/JDStatusBarNotification.h>
  25. #import "CCNetworking.h"
  26. #import "CCGraphics.h"
  27. #import "CCSynchronize.h"
  28. #import "CCMain.h"
  29. #import "CCDetail.h"
  30. #import <Fabric/Fabric.h>
  31. #import <Crashlytics/Crashlytics.h>
  32. #import "NCBridgeSwift.h"
  33. #import "NCAutoUpload.h"
  34. #import "NCPushNotificationEncryption.h"
  35. @interface AppDelegate () <UNUserNotificationCenterDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  36. {
  37. PKPushRegistry *pushRegistry;
  38. }
  39. @end
  40. @implementation AppDelegate
  41. + (void)initialize
  42. {
  43. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": [CCUtility getUserAgent]}];
  44. }
  45. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  46. {
  47. NSString *path;
  48. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  49. NSLog(@"[LOG] Start program group -----------------");
  50. NSLog(@"%@", [dirGroup path]);
  51. NSLog(@"[LOG] Start program application -----------");
  52. NSLog(@"%@", [[CCUtility getDirectoryDocuments] stringByDeletingLastPathComponent]);
  53. NSLog(@"[LOG] -------------------------------------");
  54. // create Directory Documents
  55. path = [CCUtility getDirectoryDocuments];
  56. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  57. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  58. // create Directory audio => Library, Application Support, audio
  59. path = [CCUtility getDirectoryAudio];
  60. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  61. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  62. // create Directory database Nextcloud
  63. path = [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path];
  64. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  65. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  66. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:path error:nil];
  67. // create Directory User Data
  68. path = [[dirGroup URLByAppendingPathComponent:k_appUserData] path];
  69. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  70. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  71. // create Directory Provider Storage
  72. path = [CCUtility getDirectoryProviderStorage];
  73. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  74. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  75. // create Directory Scan
  76. path = [[dirGroup URLByAppendingPathComponent:k_appScan] path];
  77. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  78. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  79. // Directory Excluded From Backup
  80. [CCUtility addSkipBackupAttributeToItemAtURL:[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]];
  81. [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_DirectoryProviderStorage]];
  82. [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_appUserData]];
  83. // Verify upgrade
  84. if ([self upgrade]) {
  85. // Set account, if no exists clear all
  86. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  87. if (tableAccount == nil) {
  88. // remove all the keys Chain
  89. [CCUtility deleteAllChainStore];
  90. // remove all the App group key
  91. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];
  92. } else {
  93. [self settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:[CCUtility getPassword:tableAccount.account]];
  94. }
  95. }
  96. #ifdef DEBUG
  97. NSLog(@"[LOG] Copy DB on Documents directory");
  98. NSString *atPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path]];
  99. NSString *toPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [CCUtility getDirectoryDocuments]];
  100. [[NSFileManager defaultManager] removeItemAtPath:toPathDB error:nil];
  101. [[NSFileManager defaultManager] copyItemAtPath:atPathDB toPath:toPathDB error:nil];
  102. #endif
  103. // UserDefaults
  104. self.ncUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:[NCBrandOptions sharedInstance].capabilitiesGroups];
  105. // Initialization Share
  106. self.sharesID = [NSMutableDictionary new];
  107. self.sharesLink = [NSMutableDictionary new];
  108. self.sharesUserAndGroup = [NSMutableDictionary new];
  109. // Filter fileID
  110. self.filterFileID = [NSMutableArray new];
  111. // Upload Pending In Upload (crash)
  112. self.sessionPendingStatusInUpload = [NSMutableArray new];
  113. // Initialization Notification
  114. self.listOfNotifications = [NSMutableArray new];
  115. // Background Fetch
  116. [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  117. // Initialization List
  118. self.listProgressMetadata = [[NSMutableDictionary alloc] init];
  119. self.listMainVC = [[NSMutableDictionary alloc] init];
  120. // Push Notification
  121. pushRegistry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
  122. pushRegistry.delegate = self;
  123. pushRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
  124. [application registerForRemoteNotifications];
  125. // Display notification (sent via APNS)
  126. [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  127. UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
  128. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
  129. }];
  130. // setting Reachable in back
  131. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  132. self.reachability = [Reachability reachabilityForInternetConnection];
  133. self.lastReachability = [self.reachability isReachable];
  134. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
  135. [self.reachability startNotifier];
  136. });
  137. //AV Session
  138. [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
  139. // [[AVAudioSession sharedInstance] setActive:YES error:nil];
  140. [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  141. // APPEARANCE: How to hide UINavigationBar 1px bottom line < iOS 11
  142. [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
  143. [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
  144. [UINavigationBar appearance].translucent = NO;
  145. // passcode
  146. [[BKPasscodeLockScreenManager sharedManager] setDelegate:self];
  147. dispatch_async(dispatch_get_main_queue(), ^{
  148. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:NO];
  149. });
  150. // Quick Actions
  151. if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]) {
  152. [self configDynamicShortcutItems];
  153. UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];
  154. if (shortcutItem)
  155. [self handleShortCutItem:shortcutItem];
  156. }
  157. // Start Timer
  158. self.timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  159. self.timerUpdateApplicationIconBadgeNumber = [NSTimer scheduledTimerWithTimeInterval:k_timerUpdateApplicationIconBadgeNumber target:self selector:@selector(updateApplicationIconBadgeNumber) userInfo:nil repeats:YES];
  160. [self startTimerServerUnauthorized];
  161. // Fabric
  162. if (![CCUtility getDisableCrashservice]) {
  163. [Fabric with:@[[Crashlytics class]]];
  164. }
  165. // Store review
  166. if ([[NCUtility sharedInstance] isSimulatorOrTestFlight] == false) {
  167. NCStoreReview *review = [NCStoreReview new];
  168. [review incrementAppRuns];
  169. [review showStoreReview];
  170. }
  171. return YES;
  172. }
  173. //
  174. // L' applicazione si dimetterà dallo stato di attivo
  175. //
  176. - (void)applicationWillResignActive:(UIApplication *)application
  177. {
  178. // Test Maintenance
  179. if (self.activeAccount.length == 0 || self.maintenanceMode)
  180. return;
  181. [_activeMain closeAllMenu];
  182. [self updateApplicationIconBadgeNumber];
  183. }
  184. //
  185. // L' applicazione entrerà in primo piano (attivo solo dopo il background)
  186. //
  187. - (void)applicationWillEnterForeground:(UIApplication *)application
  188. {
  189. // Test Maintenance
  190. if (self.activeAccount.length == 0 || self.maintenanceMode)
  191. return;
  192. NSLog(@"[LOG] Request Service Server Nextcloud");
  193. [[NCService sharedInstance] startRequestServicesServer];
  194. NSLog(@"[LOG] Initialize Auto upload");
  195. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  196. NSLog(@"[LOG] Read active directory");
  197. [self.activeMain readFileReloadFolder];
  198. NSLog(@"[LOG] Required unsubscribing / subscribing");
  199. [self pushNotification];
  200. }
  201. //
  202. // L' applicazione entrerà in primo piano (attivo sempre)
  203. //
  204. - (void)applicationDidBecomeActive:(UIApplication *)application
  205. {
  206. // Test Maintenance
  207. if (self.activeAccount.length == 0 || self.maintenanceMode)
  208. return;
  209. // middelware ping
  210. if ([[NCBrandOptions sharedInstance] use_middlewarePing]) {
  211. NSLog(@"[LOG] Middleware Ping");
  212. [[NCService sharedInstance] middlewarePing];
  213. }
  214. // Brand
  215. #if defined(HC)
  216. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  217. if (account.hcIsTrial == true || account.hcTrialExpired == true || account.hcNextGroupExpirationGroupExpired == true) {
  218. HCTrial *vc = [[UIStoryboard storyboardWithName:@"HCTrial" bundle:nil] instantiateInitialViewController];
  219. vc.account = account;
  220. [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
  221. }
  222. #endif
  223. }
  224. //
  225. // L' applicazione è entrata nello sfondo
  226. //
  227. - (void)applicationDidEnterBackground:(UIApplication *)application
  228. {
  229. NSLog(@"[LOG] Enter in Background");
  230. [[BKPasscodeLockScreenManager sharedManager] showLockScreen:YES];
  231. if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
  232. __block UIBackgroundTaskIdentifier background_task;
  233. background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
  234. //Clean up code. Tell the system that we are done.
  235. [application endBackgroundTask: background_task];
  236. background_task = UIBackgroundTaskInvalid;
  237. }];
  238. }
  239. }
  240. //
  241. // L'applicazione terminerà
  242. //
  243. - (void)applicationWillTerminate:(UIApplication *)application
  244. {
  245. NSLog(@"[LOG] bye bye, Nextcloud !");
  246. }
  247. #pragma --------------------------------------------------------------------------------------------
  248. #pragma mark ===== Login / checkPassword: ServerUnauthorized =====
  249. #pragma --------------------------------------------------------------------------------------------
  250. - (void)checkPassword
  251. {
  252. // test
  253. if (self.activeAccount.length == 0 || self.maintenanceMode)
  254. return;
  255. if ([CCUtility getPassword:self.activeAccount].length == 0) {
  256. [self openLoginView:self.window.rootViewController delegate:self loginType:k_login_Modify_Password selector:k_intro_login];
  257. }
  258. }
  259. - (void)openLoginView:(UIViewController *)viewController delegate:(id)delegate loginType:(NSInteger)loginType selector:(NSInteger)selector
  260. {
  261. BOOL loginWebFlow = NO;
  262. @synchronized (self) {
  263. // only for personalized LoginWeb [customer]
  264. if ([NCBrandOptions sharedInstance].use_login_web_personalized) {
  265. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  266. _activeLoginWeb = [CCLoginWeb new];
  267. _activeLoginWeb.delegate = delegate;
  268. _activeLoginWeb.loginType = loginType;
  269. _activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  270. dispatch_async(dispatch_get_main_queue(), ^ {
  271. [_activeLoginWeb open:viewController];
  272. });
  273. }
  274. return;
  275. }
  276. // ------------------- Nextcloud -------------------------
  277. //
  278. // Login flow : LoginWeb
  279. if (loginType == k_login_Modify_Password) {
  280. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  281. if (account.loginFlow)
  282. loginWebFlow = YES;
  283. }
  284. if (loginWebFlow || selector == k_intro_signup) {
  285. if (!(_activeLoginWeb.isViewLoaded && _activeLoginWeb.view.window)) {
  286. _activeLoginWeb = [CCLoginWeb new];
  287. _activeLoginWeb.delegate = delegate;
  288. _activeLoginWeb.loginType = loginType;
  289. if (selector == k_intro_signup) {
  290. _activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] linkloginPreferredProviders];
  291. } else {
  292. _activeLoginWeb.urlBase = self.activeUrl;
  293. }
  294. dispatch_async(dispatch_get_main_queue(), ^ {
  295. [_activeLoginWeb open:viewController];
  296. });
  297. }
  298. } else if ([NCBrandOptions sharedInstance].disable_intro && [NCBrandOptions sharedInstance].disable_request_login_url) {
  299. _activeLoginWeb = [CCLoginWeb new];
  300. _activeLoginWeb.delegate = delegate;
  301. _activeLoginWeb.loginType = loginType;
  302. _activeLoginWeb.urlBase = [[NCBrandOptions sharedInstance] loginBaseUrl];
  303. dispatch_async(dispatch_get_main_queue(), ^ {
  304. [_activeLoginWeb open:viewController];
  305. });
  306. } else {
  307. if (!(_activeLogin.isViewLoaded && _activeLogin.view.window)) {
  308. _activeLogin = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  309. _activeLogin.delegate = delegate;
  310. _activeLogin.loginType = loginType;
  311. dispatch_async(dispatch_get_main_queue(), ^ {
  312. [viewController presentViewController:_activeLogin animated:YES completion:nil];
  313. });
  314. }
  315. }
  316. }
  317. }
  318. - (void)loginSuccess:(NSInteger)loginType
  319. {
  320. //
  321. }
  322. - (void)webDismiss
  323. {
  324. [self startTimerServerUnauthorized];
  325. }
  326. - (void)loginDismiss
  327. {
  328. [self startTimerServerUnauthorized];
  329. }
  330. - (void)startTimerServerUnauthorized
  331. {
  332. self.timerServerUnauthorized = [NSTimer scheduledTimerWithTimeInterval:k_timerServerUnauthorized target:self selector:@selector(checkPassword) userInfo:nil repeats:YES];
  333. }
  334. #pragma --------------------------------------------------------------------------------------------
  335. #pragma mark ===== Setting Active Account for all APP =====
  336. #pragma --------------------------------------------------------------------------------------------
  337. - (void)settingActiveAccount:(NSString *)activeAccount activeUrl:(NSString *)activeUrl activeUser:(NSString *)activeUser activeUserID:(NSString *)activeUserID activePassword:(NSString *)activePassword
  338. {
  339. self.activeAccount = activeAccount;
  340. self.activeUrl = activeUrl;
  341. self.activeUser = activeUser;
  342. self.activeUserID = activeUserID;
  343. self.activePassword = activePassword;
  344. // Setting Account to CCNetworking
  345. [CCNetworking sharedNetworking].delegate = [NCNetworkingMain sharedInstance];
  346. }
  347. #pragma --------------------------------------------------------------------------------------------
  348. #pragma mark ===== PushNotification & PushKit Delegate =====
  349. #pragma --------------------------------------------------------------------------------------------
  350. - (void)pushNotification
  351. {
  352. // test
  353. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  354. return;
  355. for (tableAccount *result in [[NCManageDatabase sharedInstance] getAllAccount]) {
  356. NSString *token = [CCUtility getPushNotificationToken:result.account];
  357. if (![token isEqualToString:self.pushKitToken]) {
  358. if (token != nil) {
  359. // unsubscribing + subscribing
  360. [self unsubscribingNextcloudServerPushNotification:result.account url:result.url withSubscribing:true];
  361. } else {
  362. [self subscribingNextcloudServerPushNotification:result.account url:result.url];
  363. }
  364. }
  365. }
  366. }
  367. - (void)subscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url
  368. {
  369. // test
  370. if (self.activeAccount.length == 0 || self.maintenanceMode || self.pushKitToken.length == 0)
  371. return;
  372. [[NCPushNotificationEncryption sharedInstance] generatePushNotificationsKeyPair:account];
  373. NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:self.pushKitToken];
  374. NSData *pushPublicKey = [CCUtility getPushNotificationPublicKey:account];
  375. NSString *pushDevicePublicKey = [[NSString alloc] initWithData:pushPublicKey encoding:NSUTF8StringEncoding];
  376. [[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) {
  377. if (errorCode == 0 && [accountCompletion isEqualToString:account]) {
  378. NSLog(@"[LOG] Subscribed to Push Notification server & proxy successfully.");
  379. [CCUtility setPushNotificationToken:account token:self.pushKitToken];
  380. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:deviceIdentifier];
  381. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:deviceIdentifierSignature];
  382. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:publicKey];
  383. } else if (errorCode != 0) {
  384. NSLog(@"[LOG] Subscribed to Push Notification server & proxy error.");
  385. } else {
  386. NSLog(@"[LOG] It has been changed user during networking process, error.");
  387. }
  388. }];
  389. }
  390. - (void)unsubscribingNextcloudServerPushNotification:(NSString *)account url:(NSString *)url withSubscribing:(BOOL)subscribing
  391. {
  392. // test
  393. if (self.activeAccount.length == 0 || self.maintenanceMode)
  394. return;
  395. NSString *deviceIdentifier = [CCUtility getPushNotificationDeviceIdentifier:account];
  396. NSString *deviceIdentifierSignature = [CCUtility getPushNotificationDeviceIdentifierSignature:account];
  397. NSString *publicKey = [CCUtility getPushNotificationSubscribingPublicKey:account];
  398. [[OCNetworking sharedManager] unsubscribingPushNotificationWithAccount:account url:url deviceIdentifier:deviceIdentifier deviceIdentifierSignature:deviceIdentifierSignature publicKey:publicKey completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  399. if (errorCode == 0) {
  400. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy successfully.");
  401. [CCUtility setPushNotificationPublicKey:account data:nil];
  402. [CCUtility setPushNotificationSubscribingPublicKey:account publicKey:nil];
  403. [CCUtility setPushNotificationPrivateKey:account data:nil];
  404. [CCUtility setPushNotificationToken:account token:nil];
  405. [CCUtility setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  406. [CCUtility setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  407. if (self.pushKitToken != nil && subscribing) {
  408. [self subscribingNextcloudServerPushNotification:account url:url];
  409. }
  410. } else if (errorCode != 0) {
  411. NSLog(@"[LOG] Unsubscribed to Push Notification server & proxy error.");
  412. } else {
  413. NSLog(@"[LOG] It has been changed user during networking process, error.");
  414. }
  415. }];
  416. }
  417. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  418. {
  419. //Called when a notification is delivered to a foreground app.
  420. completionHandler(UNNotificationPresentationOptionAlert);
  421. }
  422. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
  423. {
  424. completionHandler();
  425. }
  426. - (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type
  427. {
  428. self.pushKitToken = [self stringWithDeviceToken:credentials.token];
  429. [self pushNotification];
  430. }
  431. - (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type
  432. {
  433. NSString *message = [payload.dictionaryPayload objectForKey:@"subject"];
  434. if (message) {
  435. NSArray *results = [[NCManageDatabase sharedInstance] getAllAccount];
  436. for (tableAccount *result in results) {
  437. if ([CCUtility getPushNotificationPrivateKey:result.account]) {
  438. NSString *decryptedMessage = [[NCPushNotificationEncryption sharedInstance] decryptPushNotification:message withDevicePrivateKey: [CCUtility getPushNotificationPrivateKey:result.account]];
  439. if (decryptedMessage) {
  440. UNMutableNotificationContent *content = [UNMutableNotificationContent new];
  441. NSData *data = [decryptedMessage dataUsingEncoding:NSUTF8StringEncoding];
  442. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  443. NSString *app = [json objectForKey:@"app"];
  444. NSString *subject = [json objectForKey:@"subject"];
  445. //NSInteger notificationId = [[json objectForKey:@"nid"] integerValue];
  446. NSURL *url = [NSURL URLWithString:result.url];
  447. NSString *domain = [url host];
  448. if ([app isEqualToString:@"spreed"]) {
  449. content.title = @"Nextcloud Talk";
  450. } else {
  451. content.title = NSLocalizedString(app.capitalizedString, nil);
  452. }
  453. if (results.count == 1) {
  454. content.title = content.title;
  455. } else {
  456. content.title = content.title;
  457. content.subtitle = [NSString stringWithFormat:@"%@ (%@)", result.displayName, domain];
  458. }
  459. if (subject) {
  460. content.body = subject;
  461. } else {
  462. content.body = @"Nextcloud notification";
  463. }
  464. content.sound = [UNNotificationSound defaultSound];
  465. /*
  466. [[OCNetworking sharedManager] getServerNotification:result.url notificationId:notificationId completion:^(NSDictionary *json, NSString *message, NSInteger errorCode) {
  467. //
  468. }];
  469. */
  470. NSString *identifier = [NSString stringWithFormat:@"Notification-%@", [NSDate new]];
  471. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
  472. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
  473. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
  474. break;
  475. }
  476. }
  477. }
  478. }
  479. }
  480. - (NSString *)stringWithDeviceToken:(NSData *)deviceToken
  481. {
  482. const char *data = [deviceToken bytes];
  483. NSMutableString *token = [NSMutableString string];
  484. for (NSUInteger i = 0; i < [deviceToken length]; i++) {
  485. [token appendFormat:@"%02.2hhX", data[i]];
  486. }
  487. return [token copy];
  488. }
  489. #pragma --------------------------------------------------------------------------------------------
  490. #pragma mark ===== Quick Actions - ShotcutItem =====
  491. #pragma --------------------------------------------------------------------------------------------
  492. - (void)configDynamicShortcutItems
  493. {
  494. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  495. UIApplicationShortcutIcon *shortcutMediaIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"media"];
  496. UIApplicationShortcutItem *shortcutMedia = [[UIApplicationShortcutItem alloc] initWithType:[NSString stringWithFormat:@"%@.media", bundleId] localizedTitle:NSLocalizedString(@"_media_", nil) localizedSubtitle:nil icon:shortcutMediaIcon userInfo:nil];
  497. // add the array to our app
  498. if (shortcutMedia)
  499. [UIApplication sharedApplication].shortcutItems = @[shortcutMedia];
  500. }
  501. - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
  502. {
  503. BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];
  504. completionHandler(handledShortCutItem);
  505. }
  506. - (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem
  507. {
  508. BOOL handled = NO;
  509. NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;
  510. NSString *shortcutMedia = [NSString stringWithFormat:@"%@.media", bundleId];
  511. if ([shortcutItem.type isEqualToString:shortcutMedia] && self.activeAccount) {
  512. dispatch_async(dispatch_get_main_queue(), ^{
  513. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  514. if (splitViewController.isCollapsed) {
  515. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  516. for (UINavigationController *nvc in tbc.viewControllers) {
  517. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  518. [nvc popToRootViewControllerAnimated:NO];
  519. }
  520. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  521. } else {
  522. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  523. [nvcDetail popToRootViewControllerAnimated:NO];
  524. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  525. [tbc setSelectedIndex: k_tabBarApplicationIndexMedia];
  526. }
  527. });
  528. handled = YES;
  529. }
  530. return handled;
  531. }
  532. #pragma --------------------------------------------------------------------------------------------
  533. #pragma mark ===== StatusBar & ApplicationIconBadgeNumber =====
  534. #pragma --------------------------------------------------------------------------------------------
  535. - (void)messageNotification:(NSString *)title description:(NSString *)description visible:(BOOL)visible delay:(NSTimeInterval)delay type:(TWMessageBarMessageType)type errorCode:(NSInteger)errorcode
  536. {
  537. static NSInteger errorCodePrev = 0;
  538. dispatch_async(dispatch_get_main_queue(), ^{
  539. if (visible) {
  540. switch (errorcode) {
  541. // JDStatusBarNotification
  542. case kCFURLErrorNotConnectedToInternet :
  543. if (errorCodePrev != errorcode)
  544. [JDStatusBarNotification showWithStatus:NSLocalizedString(title, nil) dismissAfter:delay styleName:JDStatusBarStyleDefault];
  545. errorCodePrev = errorcode;
  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. UIView *view = [(UIButton *)sender superview];
  755. NCCreateMenuAdd *menuAdd = [[NCCreateMenuAdd alloc] initWithThemingColor:[NCBrandColor sharedInstance].brandElement];
  756. [menuAdd createMenuWithViewController:self.window.rootViewController view:view];
  757. }
  758. - (void)selectedTabBarController:(NSInteger)index
  759. {
  760. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  761. if (splitViewController.isCollapsed) {
  762. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  763. for (UINavigationController *nvc in tbc.viewControllers) {
  764. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  765. [nvc popToRootViewControllerAnimated:NO];
  766. }
  767. [tbc setSelectedIndex: index];
  768. } else {
  769. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  770. [nvcDetail popToRootViewControllerAnimated:NO];
  771. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  772. [tbc setSelectedIndex: index];
  773. }
  774. }
  775. - (NSString *)getTabBarControllerActiveServerUrl
  776. {
  777. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  778. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  779. NSString *serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  780. NSInteger index = tabBarController.selectedIndex;
  781. // select active serverUrl
  782. if (index == k_tabBarApplicationIndexFile) {
  783. serverUrl = self.activeMain.serverUrl;
  784. } else if (index == k_tabBarApplicationIndexFavorite) {
  785. if (self.activeFavorites.serverUrl)
  786. serverUrl = self.activeFavorites.serverUrl;
  787. } else if (index == k_tabBarApplicationIndexMedia) {
  788. serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:self.activeUrl];
  789. }
  790. return serverUrl;
  791. }
  792. #pragma --------------------------------------------------------------------------------------------
  793. #pragma mark ===== Theming Color =====
  794. #pragma --------------------------------------------------------------------------------------------
  795. - (void)settingThemingColorBrand
  796. {
  797. if (self.activeAccount.length == 0 || self.maintenanceMode)
  798. return;
  799. if ([NCBrandOptions sharedInstance].use_themingColor) {
  800. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  801. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  802. } else {
  803. [NCBrandColor sharedInstance].brand = [NCBrandColor sharedInstance].customer;
  804. [NCBrandColor sharedInstance].brandElement = [NCBrandColor sharedInstance].customer;
  805. [NCBrandColor sharedInstance].brandText = [NCBrandColor sharedInstance].customerText;
  806. }
  807. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeTheming" object:nil];
  808. }
  809. - (void)changeTheming:(UIViewController *)vc
  810. {
  811. // Change Navigation & TabBar color
  812. vc.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  813. vc.tabBarController.tabBar.tintColor = [NCBrandColor sharedInstance].brandElement;
  814. // Change bar bottom line shadow
  815. vc.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  816. // Change button Plus
  817. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  818. UITabBarController *tabBarController = [splitViewController.viewControllers firstObject];
  819. UIButton *button = [tabBarController.view viewWithTag:99];
  820. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"tabBarPlus"] multiplier:3 color:[NCBrandColor sharedInstance].brandElement];
  821. [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
  822. [button setBackgroundImage:buttonImage forState:UIControlStateHighlighted];
  823. // Tint Color GLOBAL WINDOW
  824. [self.window setTintColor:[NCBrandColor sharedInstance].textView];
  825. }
  826. #pragma --------------------------------------------------------------------------------------------
  827. #pragma mark ===== Manager Passcode =====
  828. #pragma --------------------------------------------------------------------------------------------
  829. - (BOOL)lockScreenManagerShouldShowLockScreen:(BKPasscodeLockScreenManager *)aManager
  830. {
  831. // ServerUrl active
  832. NSString *serverUrl = self.activeMain.serverUrl;
  833. BOOL isBlockZone = false;
  834. // fermiamo la data della sessione
  835. self.sessionePasscodeLock = nil;
  836. // se il block code è a zero esci con NON attivare la richiesta password
  837. if ([[CCUtility getBlockCode] length] == 0) return NO;
  838. // se non c'è attivo un account esci con NON attivare la richiesta password
  839. if ([self.activeAccount length] == 0) return NO;
  840. // se non è attivo il OnlyLockDir esci con NON attivare la richiesta password
  841. if (serverUrl && _activeUrl) {
  842. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  843. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  844. if (directory.lock) {
  845. isBlockZone = true;
  846. break;
  847. } else {
  848. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  849. if (serverUrl == self.activeUrl)
  850. break;
  851. }
  852. }
  853. }
  854. if ([CCUtility getOnlyLockDir] && !isBlockZone) return NO;
  855. return YES;
  856. }
  857. - (UIViewController *)lockScreenManagerPasscodeViewController:(BKPasscodeLockScreenManager *)aManager
  858. {
  859. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  860. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  861. viewController.delegate = self;
  862. viewController.title = [NCBrandOptions sharedInstance].brand;
  863. viewController.fromType = CCBKPasscodeFromLockScreen;
  864. viewController.inputViewTitlePassword = YES;
  865. if ([CCUtility getSimplyBlockCode]) {
  866. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  867. viewController.passcodeInputView.maximumLength = 6;
  868. } else {
  869. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  870. viewController.passcodeInputView.maximumLength = 64;
  871. }
  872. viewController.touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName: k_serviceShareKeyChain];
  873. viewController.touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  874. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  875. return navigationController;
  876. }
  877. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  878. {
  879. [aViewController dismissViewControllerAnimated:YES completion:nil];
  880. // is a lock screen
  881. if (aViewController.fromType == CCBKPasscodeFromLockScreen) {
  882. [aViewController dismissViewControllerAnimated:YES completion:nil];
  883. // start session Passcode Lock
  884. BOOL isBlockZone = false;
  885. NSString *serverUrl = self.activeMain.serverUrl;
  886. while (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:_activeUrl]]) {
  887. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", self.activeAccount, serverUrl]];
  888. if (directory.lock) {
  889. isBlockZone = true;
  890. break;
  891. } else {
  892. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  893. if (serverUrl == self.activeUrl)
  894. break;
  895. }
  896. }
  897. if (isBlockZone)
  898. self.sessionePasscodeLock = [NSDate date];
  899. }
  900. }
  901. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  902. {
  903. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromInit) {
  904. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  905. //self.lockUntilDate = nil;
  906. //self.failedAttempts = 0;
  907. aResultHandler(YES);
  908. } else aResultHandler(NO);
  909. } else aResultHandler(YES);
  910. }
  911. #pragma --------------------------------------------------------------------------------------------
  912. #pragma mark ===== reachabilityChanged =====
  913. #pragma --------------------------------------------------------------------------------------------
  914. -(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
  915. {
  916. if ([self.reachability isReachable]) {
  917. if (self.lastReachability == NO) {
  918. NSLog(@"[LOG] Request Service Server Nextcloud");
  919. [[NCService sharedInstance] startRequestServicesServer];
  920. }
  921. NSLog(@"[LOG] Reachability Changed: Reachable");
  922. self.lastReachability = YES;
  923. } else {
  924. if (self.lastReachability == YES) {
  925. [self messageNotification:@"_network_not_available_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:kCFURLErrorNotConnectedToInternet];
  926. }
  927. NSLog(@"[LOG] Reachability Changed: NOT Reachable");
  928. self.lastReachability = NO;
  929. }
  930. if ([self.reachability isReachableViaWiFi]) NSLog(@"[LOG] Reachability Changed: WiFi");
  931. if ([self.reachability isReachableViaWWAN]) NSLog(@"[LOG] Reachability Changed: WWAn");
  932. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"setTitleMain" object:nil];
  933. }
  934. #pragma --------------------------------------------------------------------------------------------
  935. #pragma mark ===== Fetch =====
  936. #pragma --------------------------------------------------------------------------------------------
  937. - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  938. {
  939. // Test Maintenance
  940. if (self.activeAccount.length == 0 || self.maintenanceMode) {
  941. completionHandler(UIBackgroundFetchResultNoData);
  942. return;
  943. }
  944. NSLog(@"[LOG] Start perform Fetch With Completion Handler");
  945. // Verify new photo
  946. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  947. // after 20 sec
  948. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  949. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != ''"] sorted:nil ascending:NO];
  950. if ([records count] > 0) {
  951. completionHandler(UIBackgroundFetchResultNewData);
  952. } else {
  953. completionHandler(UIBackgroundFetchResultNoData);
  954. }
  955. NSLog(@"[LOG] End 20 sec. perform Fetch With Completion Handler");
  956. });
  957. }
  958. #pragma --------------------------------------------------------------------------------------------
  959. #pragma mark ===== Operation Networking & Session =====
  960. #pragma --------------------------------------------------------------------------------------------
  961. //
  962. // Method called by the system when all the background task has end
  963. //
  964. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler
  965. {
  966. NSLog(@"[LOG] Start handle Events For Background URLSession: %@", identifier);
  967. // after 20 sec
  968. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  969. self.backgroundSessionCompletionHandler = completionHandler;
  970. void (^completionHandler)() = self.backgroundSessionCompletionHandler;
  971. self.backgroundSessionCompletionHandler = nil;
  972. completionHandler();
  973. NSLog(@"[LOG] End 20 sec. Start handle Events For Background URLSession: %@", identifier);
  974. });
  975. }
  976. #pragma --------------------------------------------------------------------------------------------
  977. #pragma mark ===== Process Load Download/Upload < k_timerProcess seconds > =====
  978. #pragma --------------------------------------------------------------------------------------------
  979. - (void)loadAutoDownloadUpload
  980. {
  981. if (self.activeAccount.length == 0 || self.maintenanceMode)
  982. return;
  983. tableMetadata *metadataForUpload, *metadataForDownload;
  984. long counterDownload = 0, counterUpload = 0;
  985. NSUInteger sizeDownload = 0, sizeUpload = 0;
  986. BOOL isE2EE = false;
  987. long maxConcurrentOperationDownloadUpload = k_maxConcurrentOperation;
  988. // Detect E2EE
  989. NSString *saveserverUrl = @"";
  990. NSArray *metadatasForE2EE = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status != %d", k_metadataStatusNormal] sorted:@"serverUrl" ascending:NO];
  991. for (tableMetadata *metadata in metadatasForE2EE) {
  992. if (![saveserverUrl isEqualToString:metadata.serverUrl]) {
  993. saveserverUrl = metadata.serverUrl;
  994. if ([[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND e2eEncrypted == 1", metadata.account, metadata.serverUrl]] != nil) {
  995. isE2EE = true;
  996. break;
  997. }
  998. }
  999. }
  1000. // E2EE : not in background
  1001. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground && isE2EE) {
  1002. return;
  1003. }
  1004. // E2EE : only 1 operation
  1005. if (isE2EE) {
  1006. maxConcurrentOperationDownloadUpload = 1;
  1007. }
  1008. // Stop Timer
  1009. [_timerProcessAutoDownloadUpload invalidate];
  1010. NSArray *metadatasDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInDownload, k_metadataStatusDownloading] sorted:nil ascending:true];
  1011. NSArray *metadatasUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusInUpload, k_metadataStatusUploading] sorted:nil ascending:true];
  1012. // Counter
  1013. counterDownload = [metadatasDownload count];
  1014. counterUpload = [metadatasUpload count];
  1015. // Size
  1016. for (tableMetadata *metadata in metadatasDownload) {
  1017. sizeDownload = sizeDownload + metadata.size;
  1018. }
  1019. for (tableMetadata *metadata in metadatasUpload) {
  1020. sizeUpload = sizeUpload + metadata.size;
  1021. }
  1022. NSLog(@"%@", [NSString stringWithFormat:@"[LOG] PROCESS-AUTO-UPLOAD | Download %ld - %@ | Upload %ld - %@", counterDownload, [CCUtility transformedSize:sizeDownload], counterUpload, [CCUtility transformedSize:sizeUpload]]);
  1023. // ------------------------- <selector Download> -------------------------
  1024. while (counterDownload < maxConcurrentOperationDownloadUpload) {
  1025. metadataForDownload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"status == %d", k_metadataStatusWaitDownload] sorted:@"session" ascending:YES];
  1026. if (metadataForDownload) {
  1027. metadataForDownload.status = k_metadataStatusInDownload;
  1028. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  1029. [[CCNetworking sharedNetworking] downloadFile:metadata taskStatus:k_taskStatusResume];
  1030. counterDownload++;
  1031. sizeDownload = sizeDownload + metadata.size;
  1032. } else {
  1033. break;
  1034. }
  1035. }
  1036. // ------------------------- <selector Upload> -------------------------
  1037. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1038. if (sizeUpload > k_maxSizeOperationUpload) {
  1039. break;
  1040. }
  1041. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadFile, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1042. if (metadataForUpload) {
  1043. if ([metadataForUpload.session isEqualToString:k_upload_session_extension]) {
  1044. metadataForUpload.session = k_upload_session;
  1045. }
  1046. metadataForUpload.status = k_metadataStatusInUpload;
  1047. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1048. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1049. counterUpload++;
  1050. sizeUpload = sizeUpload + metadata.size;
  1051. } else {
  1052. break;
  1053. }
  1054. }
  1055. // ------------------------- <selector Auto Upload> -------------------------
  1056. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1057. if (sizeUpload > k_maxSizeOperationUpload) {
  1058. break;
  1059. }
  1060. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUpload, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1061. if (metadataForUpload) {
  1062. metadataForUpload.status = k_metadataStatusInUpload;
  1063. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1064. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1065. counterUpload++;
  1066. sizeUpload = sizeUpload + metadata.size;
  1067. } else {
  1068. break;
  1069. }
  1070. }
  1071. // ------------------------- <selector Auto Upload All> ----------------------
  1072. // Verify num error k_maxErrorAutoUploadAll after STOP (100)
  1073. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %i", selectorUploadAutoUploadAll, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1074. NSInteger errorCount = [metadatas count];
  1075. if (errorCount >= k_maxErrorAutoUploadAll) {
  1076. [self messageNotification:@"_error_" description:@"_too_errors_automatic_all_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1077. } else {
  1078. while (counterUpload < maxConcurrentOperationDownloadUpload) {
  1079. if (sizeUpload > k_maxSizeOperationUpload) {
  1080. break;
  1081. }
  1082. metadataForUpload = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"sessionSelector == %@ AND status == %d", selectorUploadAutoUploadAll, k_metadataStatusWaitUpload] sorted:@"session" ascending:YES];
  1083. if (metadataForUpload) {
  1084. metadataForUpload.status = k_metadataStatusInUpload;
  1085. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  1086. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  1087. counterUpload++;
  1088. sizeUpload = sizeUpload + metadata.size;
  1089. } else {
  1090. break;
  1091. }
  1092. }
  1093. }
  1094. // No Download/upload available ? --> remove errors for retry
  1095. //
  1096. if (counterDownload+counterUpload < maxConcurrentOperationDownloadUpload+1) {
  1097. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"status == %d OR status == %d", k_metadataStatusDownloadError, k_metadataStatusUploadError] sorted:nil ascending:NO];
  1098. for (tableMetadata *metadata in metadatas) {
  1099. if (metadata.status == k_metadataStatusDownloadError)
  1100. metadata.status = k_metadataStatusWaitDownload;
  1101. else if (metadata.status == k_metadataStatusUploadError)
  1102. metadata.status = k_metadataStatusWaitUpload;
  1103. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1104. }
  1105. }
  1106. // Verify internal error download (lost task)
  1107. //
  1108. NSArray *matadatasInDownloading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_download_session_extension, k_metadataStatusDownloading] sorted:nil ascending:true];
  1109. for (tableMetadata *metadata in matadatasInDownloading) {
  1110. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1111. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1112. NSURLSessionTask *findTask;
  1113. for (NSURLSessionTask *task in downloadTasks) {
  1114. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1115. findTask = task;
  1116. }
  1117. }
  1118. if (!findTask) {
  1119. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1120. metadata.status = k_metadataStatusWaitDownload;
  1121. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1122. }
  1123. }];
  1124. }
  1125. // Verify internal error upload (lost task)
  1126. //
  1127. NSArray *metadatasUploading = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d", k_upload_session_extension, k_metadataStatusUploading] sorted:nil ascending:true];
  1128. for (tableMetadata *metadata in metadatasUploading) {
  1129. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1130. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1131. NSURLSessionTask *findTask;
  1132. for (NSURLSessionTask *task in uploadTasks) {
  1133. if (task.taskIdentifier == metadata.sessionTaskIdentifier) {
  1134. findTask = task;
  1135. }
  1136. }
  1137. if (!findTask) {
  1138. metadata.sessionTaskIdentifier = k_taskIdentifierDone;
  1139. metadata.status = k_metadataStatusWaitUpload;
  1140. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1141. }
  1142. }];
  1143. }
  1144. // Upload in pending
  1145. //
  1146. NSArray *metadatasInUpload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"session != %@ AND status == %d AND sessionTaskIdentifier == 0", k_upload_session_extension, k_metadataStatusInUpload] sorted:nil ascending:true];
  1147. for (tableMetadata *metadata in metadatasInUpload) {
  1148. if ([self.sessionPendingStatusInUpload containsObject:metadata.fileID]) {
  1149. metadata.status = k_metadataStatusWaitUpload;
  1150. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1151. } else {
  1152. [self.sessionPendingStatusInUpload addObject:metadata.fileID];
  1153. }
  1154. }
  1155. if (metadatasInUpload.count == 0) {
  1156. [self.sessionPendingStatusInUpload removeAllObjects];
  1157. }
  1158. // Start Timer
  1159. _timerProcessAutoDownloadUpload = [NSTimer scheduledTimerWithTimeInterval:k_timerProcessAutoDownloadUpload target:self selector:@selector(loadAutoDownloadUpload) userInfo:nil repeats:YES];
  1160. }
  1161. - (void)startLoadAutoDownloadUpload
  1162. {
  1163. if (self.timerProcessAutoDownloadUpload.isValid) {
  1164. [self performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1165. }
  1166. }
  1167. #pragma --------------------------------------------------------------------------------------------
  1168. #pragma mark ===== Open CCUploadFromOtherUpp =====
  1169. #pragma --------------------------------------------------------------------------------------------
  1170. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
  1171. {
  1172. return YES;
  1173. }
  1174. // Method called from iOS system to send a file from other app.
  1175. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
  1176. {
  1177. if (self.activeAccount.length == 0 || self.maintenanceMode)
  1178. return YES;
  1179. NSString *scheme = url.scheme;
  1180. dispatch_time_t timer = 0;
  1181. if (self.activeMain == nil) timer = 1;
  1182. if ([scheme isEqualToString:@"nextcloud"]) {
  1183. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1184. NSString *action = url.host;
  1185. if ([action isEqualToString:@"open-file"]) {
  1186. NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
  1187. NSArray *queryItems = urlComponents.queryItems;
  1188. NSString *user = [CCUtility valueForKey:@"user" fromQueryItems:queryItems];
  1189. NSString *path = [CCUtility valueForKey:@"path" fromQueryItems:queryItems];
  1190. NSString *link = [CCUtility valueForKey:@"link" fromQueryItems:queryItems];
  1191. tableAccount *matchedAccount = nil;
  1192. // verify parameter
  1193. if (user.length == 0 || path.length == 0 || [[NSURL URLWithString:link] host].length == 0) {
  1194. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_parameter_schema_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1195. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1196. [alertController addAction:okAction];
  1197. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1198. } else {
  1199. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  1200. if (account) {
  1201. NSURL *activeAccountURL = [NSURL URLWithString:account.url];
  1202. NSString *activeAccountUser = account.user;
  1203. if ([link containsString:activeAccountURL.host] && [user isEqualToString:activeAccountUser]) {
  1204. matchedAccount = account;
  1205. } else {
  1206. NSArray *accounts = [[NCManageDatabase sharedInstance] getAllAccount];
  1207. for (tableAccount *account in accounts) {
  1208. NSURL *accountURL = [NSURL URLWithString:account.url];
  1209. NSString *accountUser = account.user;
  1210. if ([link containsString:accountURL.host] && [user isEqualToString:accountUser]) {
  1211. matchedAccount = [[NCManageDatabase sharedInstance] setAccountActive:account.account];
  1212. [self settingActiveAccount:matchedAccount.account activeUrl:matchedAccount.url activeUser:matchedAccount.user activeUserID:matchedAccount.userID activePassword:[CCUtility getPassword:matchedAccount.account]];
  1213. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1214. }
  1215. }
  1216. }
  1217. if (matchedAccount) {
  1218. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1219. if (splitViewController.isCollapsed) {
  1220. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  1221. for (UINavigationController *nvc in tbc.viewControllers) {
  1222. if ([nvc.topViewController isKindOfClass:[CCDetail class]])
  1223. [nvc popToRootViewControllerAnimated:NO];
  1224. }
  1225. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  1226. } else {
  1227. UINavigationController *nvcDetail = splitViewController.viewControllers.lastObject;
  1228. [nvcDetail popToRootViewControllerAnimated:NO];
  1229. UITabBarController *tbc = splitViewController.viewControllers.firstObject;
  1230. [tbc setSelectedIndex: k_tabBarApplicationIndexFile];
  1231. }
  1232. [CATransaction begin];
  1233. [CATransaction setCompletionBlock:^{
  1234. NSString *fileNamePath = [NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, path];
  1235. if ([path containsString:@"/"]) {
  1236. // Push
  1237. NSString *directoryName = [[path stringByDeletingLastPathComponent] lastPathComponent];
  1238. NSString *serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:[NSString stringWithFormat:@"%@%@/%@", matchedAccount.url, k_webDAV, [path stringByDeletingLastPathComponent]]];
  1239. tableMetadata *metadata = [CCUtility createMetadataWithAccount:matchedAccount.account date:[NSDate date] directory:NO fileID:[[NSUUID UUID] UUIDString] serverUrl:serverUrl fileName:directoryName etag:@"" size:0 status:k_metadataStatusNormal url:@""];
  1240. [self.activeMain performSegueDirectoryWithControlPasscode:true metadata:metadata scrollToFileNamePath:fileNamePath];
  1241. } else {
  1242. // Reload folder
  1243. NSString *serverUrl = [NSString stringWithFormat:@"%@%@", matchedAccount.url, k_webDAV];
  1244. self.activeMain.scrollToFileNamePath = fileNamePath;
  1245. [self.activeMain readFolder:serverUrl];
  1246. }
  1247. }];
  1248. [self.activeMain.navigationController popToRootViewControllerAnimated:NO];
  1249. [CATransaction commit];
  1250. } else {
  1251. NSString *domain = [[NSURL URLWithString:link] host];
  1252. NSString *fileName = [path lastPathComponent];
  1253. NSString *message = [NSString stringWithFormat:NSLocalizedString(@"_account_not_available_", nil), user, domain, fileName];
  1254. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_info_", nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1255. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1256. [alertController addAction:okAction];
  1257. [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
  1258. }
  1259. }
  1260. }
  1261. }
  1262. });
  1263. return YES;
  1264. }
  1265. NSError *error;
  1266. NSLog(@"[LOG] the path is: %@", url.path);
  1267. NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"];
  1268. self.fileNameUpload = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]];
  1269. if (self.activeAccount) {
  1270. [[NSFileManager defaultManager]removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:nil];
  1271. [[NSFileManager defaultManager]moveItemAtPath:url.path toPath:[NSTemporaryDirectory() stringByAppendingString:self.fileNameUpload] error:&error];
  1272. if (error == nil) {
  1273. UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
  1274. UINavigationController *splitNavigationController = [splitViewController.viewControllers firstObject];
  1275. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"CCUploadFromOtherUpp" bundle:nil] instantiateViewControllerWithIdentifier:@"CCUploadNavigationViewController"];
  1276. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1277. [splitNavigationController presentViewController:navigationController animated:YES completion:nil];
  1278. });
  1279. }
  1280. }
  1281. return YES;
  1282. }
  1283. #pragma --------------------------------------------------------------------------------------------
  1284. #pragma mark ===== Maintenance Mode =====
  1285. #pragma --------------------------------------------------------------------------------------------
  1286. - (void)maintenanceMode:(BOOL)mode
  1287. {
  1288. self.maintenanceMode = mode;
  1289. }
  1290. #pragma --------------------------------------------------------------------------------------------
  1291. #pragma mark ===== UPGRADE =====
  1292. #pragma --------------------------------------------------------------------------------------------
  1293. - (BOOL)upgrade
  1294. {
  1295. #ifdef DEBUG
  1296. //self.maintenanceMode = YES;
  1297. #endif
  1298. NSString *actualVersion = [CCUtility getVersion];
  1299. NSString *actualBuild = [CCUtility getBuild];
  1300. /* ---------------------- UPGRADE VERSION ----------------------- */
  1301. // VERSION < 2.17.6
  1302. if (([actualVersion compare:@"2.17.6" options:NSNumericSearch] == NSOrderedAscending)) {
  1303. // Remove All old Photo Library
  1304. [[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1305. }
  1306. // VERSION == 2.17.6
  1307. if ([actualVersion isEqualToString:@"2.17.6"]) {
  1308. // Build < 10
  1309. if (([actualBuild compare:@"10" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1310. // Remove All old Photo Library
  1311. //[[NCManageDatabase sharedInstance] clearTable:[tablePhotoLibrary class] account:nil];
  1312. }
  1313. }
  1314. if (([actualVersion compare:@"2.19.1" options:NSNumericSearch] == NSOrderedAscending)) {
  1315. [[NCManageDatabase sharedInstance] clearTable:[tableMetadata class] account:nil];
  1316. [[NCManageDatabase sharedInstance] setClearAllDateReadDirectory];
  1317. }
  1318. if (([actualVersion compare:@"2.22.0" options:NSNumericSearch] == NSOrderedAscending)) {
  1319. NSArray *records = [[NCManageDatabase sharedInstance] getTableLocalFilesWithPredicate:[NSPredicate predicateWithFormat:@"#size > 0"] sorted:@"account" ascending:NO];
  1320. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1321. NSString *account = @"";
  1322. NSString *directoryUser = @"";
  1323. NSString *fileName;
  1324. for (tableLocalFile *record in records) {
  1325. if (![account isEqualToString:record.account]) {
  1326. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", record.account]];
  1327. if (tableAccount) {
  1328. directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  1329. account = record.account;
  1330. }
  1331. }
  1332. fileName = [NSString stringWithFormat:@"%@/%@", directoryUser, record.fileID];
  1333. if (![directoryUser isEqualToString:@""] && [[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
  1334. [CCUtility moveFileAtPath:fileName toPath:[CCUtility getDirectoryProviderStorageFileID:record.fileID fileNameView:record.fileName]];
  1335. }
  1336. }
  1337. });
  1338. }
  1339. if ([actualVersion isEqualToString:@"2.22.9"]) {
  1340. if (([actualBuild compare:@"8" options:NSNumericSearch] == NSOrderedAscending) || actualBuild == nil) {
  1341. [[NCManageDatabase sharedInstance] clearTable:[tableActivity class] account:nil];
  1342. [[NCManageDatabase sharedInstance] clearTable:[tableActivitySubjectRich class] account:nil];
  1343. [[NCManageDatabase sharedInstance] clearTable:[tableActivityPreview class] account:nil];
  1344. }
  1345. }
  1346. if (([actualVersion compare:@"2.23.4" options:NSNumericSearch] == NSOrderedAscending)) {
  1347. NSArray *records = [[NCManageDatabase sharedInstance] getAllAccount];
  1348. for (tableAccount *record in records) {
  1349. [CCUtility setPassword:record.account password:record.password];
  1350. [[NCManageDatabase sharedInstance] removePasswordAccount:record.account];
  1351. }
  1352. }
  1353. return YES;
  1354. }
  1355. @end