AppDelegate.m 71 KB

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