AppDelegate.m 79 KB

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