AppDelegate.m 77 KB

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