AppDelegate.m 71 KB

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