AppDelegate.m 81 KB

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