AppDelegate.m 73 KB

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