ShareViewController.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. //
  2. // ShareViewController.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 26/01/16.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "ShareViewController.h"
  24. #import "NCBridgeSwift.h"
  25. @import MobileCoreServices;
  26. @interface ShareViewController ()
  27. {
  28. NSURL *dirGroup;
  29. NSUInteger totalSize;
  30. NSExtensionItem *inputItem;
  31. UIColor *barTintColor;
  32. UIColor *tintColor;
  33. }
  34. @end
  35. @implementation ShareViewController
  36. #pragma --------------------------------------------------------------------------------------------
  37. #pragma mark ===== View =====
  38. #pragma --------------------------------------------------------------------------------------------
  39. -(void)viewDidLoad
  40. {
  41. tableAccount *recordAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  42. if (recordAccount == nil) {
  43. // close now
  44. [self performSelector:@selector(closeShareViewController) withObject:nil afterDelay:0.1];
  45. return;
  46. } else {
  47. _activeAccount = recordAccount.account;
  48. _activePassword = recordAccount.password;
  49. _activeUrl = recordAccount.url;
  50. _activeUser = recordAccount.user;
  51. _activeUserID = recordAccount.userID;
  52. if ([_activeAccount isEqualToString:[CCUtility getActiveAccountExt]]) {
  53. // load
  54. _serverUrl = [CCUtility getServerUrlExt];
  55. _destinyFolderButton.title = [NSString stringWithFormat:NSLocalizedString(@"_destiny_folder_", nil), [CCUtility getTitleServerUrlExt]];
  56. } else {
  57. // Default settings
  58. [CCUtility setActiveAccountExt:self.activeAccount];
  59. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:self.activeUrl];
  60. [CCUtility setServerUrlExt:_serverUrl];
  61. _destinyFolderButton.title = [NSString stringWithFormat:NSLocalizedString(@"_destiny_folder_", nil), NSLocalizedString(@"_home_", nil)];
  62. [CCUtility setTitleServerUrlExt:NSLocalizedString(@"_home_", nil)];
  63. }
  64. }
  65. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  66. _filesName = [[NSMutableArray alloc] init];
  67. _hud = [[CCHud alloc] initWithView:self.navigationController.view];
  68. _networkingOperationQueue = [NSOperationQueue new];
  69. _networkingOperationQueue.name = k_queue;
  70. _networkingOperationQueue.maxConcurrentOperationCount = 1;
  71. [CCNetworking sharedNetworking].delegate = self;
  72. [self.shareTable registerNib:[UINib nibWithNibName:@"CCCellShareExt" bundle:nil] forCellReuseIdentifier:@"ShareExtCell"];
  73. [self navigationBarToolBar];
  74. [self loadDataSwift];
  75. }
  76. // Apparirà
  77. - (void)viewWillAppear:(BOOL)animated
  78. {
  79. [super viewWillAppear:animated];
  80. // BUGFIX 2.17 - Change user Nextcloud App
  81. [[CCNetworking sharedNetworking] settingAccount];
  82. if ([[CCUtility getBlockCode] length] > 0 && [CCUtility getOnlyLockDir] == NO)
  83. [self openBKPasscode];
  84. }
  85. - (void)didReceiveMemoryWarning
  86. {
  87. [super didReceiveMemoryWarning];
  88. // Dispose of any resources that can be recreated.
  89. }
  90. - (void)closeShareViewController
  91. {
  92. [self.extensionContext completeRequestReturningItems:self.extensionContext.inputItems completionHandler:nil];
  93. }
  94. //
  95. // L'applicazione terminerà
  96. //
  97. - (void)applicationWillTerminate:(UIApplication *)application
  98. {
  99. NSLog(@"[LOG] bye bye, Nextcloud Share Extension!");
  100. }
  101. #pragma --------------------------------------------------------------------------------------------
  102. #pragma mark == Action ==
  103. #pragma --------------------------------------------------------------------------------------------
  104. - (void)navigationBarToolBar
  105. {
  106. UIBarButtonItem *rightButtonUpload, *leftButtonCancel;
  107. // Theming
  108. if ([NCBrandOptions sharedInstance].use_themingColor) {
  109. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilitesWithAccount:self.activeAccount];
  110. [CCGraphics settingThemingColor:capabilities.themingColor themingColorElement:capabilities.themingColorElement themingColorText:capabilities.themingColorText];
  111. }
  112. self.navigationController.navigationBar.barTintColor = [NCBrandColor sharedInstance].brand;
  113. self.navigationController.navigationBar.tintColor = [NCBrandColor sharedInstance].brandText;
  114. self.toolBar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  115. self.toolBar.tintColor = [NCBrandColor sharedInstance].brandElement;
  116. // Upload
  117. rightButtonUpload = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_save_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(selectPost)];
  118. // Cancel
  119. leftButtonCancel = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelPost)];
  120. // Title
  121. [self.navigationController.navigationBar setTitleTextAttributes: @{NSForegroundColorAttributeName:self.navigationController.navigationBar.tintColor}];
  122. self.navigationItem.title = [NCBrandOptions sharedInstance].brand;
  123. self.navigationItem.leftBarButtonItem = leftButtonCancel;
  124. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:rightButtonUpload, nil];
  125. self.navigationItem.hidesBackButton = YES;
  126. }
  127. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title type:(NSString *)type
  128. {
  129. // DENIED e2e
  130. if ([CCUtility isFolderEncrypted:serverUrlTo account:self.activeAccount]) {
  131. return;
  132. }
  133. if (serverUrlTo)
  134. _serverUrl = serverUrlTo;
  135. if (title) {
  136. self.destinyFolderButton.title = [NSString stringWithFormat:NSLocalizedString(@"_destiny_folder_", nil), title];
  137. [CCUtility setTitleServerUrlExt:title];
  138. } else {
  139. self.destinyFolderButton.title = [NSString stringWithFormat:NSLocalizedString(@"_destiny_folder_", nil), NSLocalizedString(@"_home_", nil)];
  140. [CCUtility setTitleServerUrlExt:NSLocalizedString(@"_home_", nil)];
  141. }
  142. [CCUtility setActiveAccountExt:self.activeAccount];
  143. [CCUtility setServerUrlExt:_serverUrl];
  144. }
  145. - (IBAction)destinyFolderButtonTapped:(UIBarButtonItem *)sender
  146. {
  147. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  148. CCMove *viewController = (CCMove *)navigationController.topViewController;
  149. viewController.delegate = self;
  150. viewController.move.title = NSLocalizedString(@"_select_", nil);
  151. viewController.tintColor = tintColor;
  152. viewController.barTintColor = barTintColor;
  153. viewController.tintColorTitle = tintColor;
  154. viewController.networkingOperationQueue = _networkingOperationQueue;
  155. // E2EE
  156. viewController.includeDirectoryE2EEncryption = NO;
  157. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  158. [self presentViewController:navigationController animated:YES completion:nil];
  159. }
  160. - (void)selectPost
  161. {
  162. if ([self.filesName count] > 0) {
  163. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:self.serverUrl account:self.activeAccount];
  164. NSString *fileName = [[NCUtility sharedInstance] createFileName:[self.filesName objectAtIndex:0] serverUrl:self.serverUrl account:self.activeAccount];
  165. tableMetadata *metadataForUpload = [tableMetadata new];
  166. metadataForUpload.account = self.activeAccount;
  167. metadataForUpload.date = [NSDate new];
  168. metadataForUpload.directoryID = directoryID;
  169. metadataForUpload.fileID = [directoryID stringByAppendingString:fileName];
  170. metadataForUpload.fileName = fileName;
  171. metadataForUpload.fileNameView = fileName;
  172. metadataForUpload.serverUrl = self.serverUrl;
  173. metadataForUpload.session = k_upload_session_foreground;
  174. metadataForUpload.sessionSelector = selectorUploadFile;
  175. metadataForUpload.status = k_metadataStatusWaitUpload;
  176. // Prepare file and directory
  177. [CCUtility copyFileAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] toPath:[CCUtility getDirectoryProviderStorageFileID:metadataForUpload.fileID fileNameView:fileName]];
  178. // Add Medtadata for upload
  179. tableMetadata *metadata = [[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  180. [[CCNetworking sharedNetworking] uploadFile:metadata taskStatus:k_taskStatusResume];
  181. [self.hud visibleHudTitle:NSLocalizedString(@"_uploading_", nil) mode:MBProgressHUDModeDeterminate color:[NCBrandColor sharedInstance].brandElement];
  182. }
  183. else
  184. [self closeShareViewController];
  185. }
  186. - (void)cancelPost
  187. {
  188. // rimuoviamo i file+ico
  189. for (NSString *fileName in self.filesName) {
  190. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] error:nil];
  191. }
  192. [self closeShareViewController];
  193. }
  194. #pragma --------------------------------------------------------------------------------------------
  195. #pragma mark ======================= NetWorking ==================================
  196. #pragma --------------------------------------------------------------------------------------------
  197. - (void)triggerProgressTask:(NSNotification *)notification
  198. {
  199. NSDictionary *dict = notification.userInfo;
  200. float progress = [[dict valueForKey:@"progress"] floatValue];
  201. [self.hud progress:progress];
  202. }
  203. - (void)uploadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID assetLocalIdentifier:(NSString *)assetLocalIdentifier serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  204. {
  205. [self.hud hideHud];
  206. if (errorCode == 0) {
  207. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  208. [self.filesName removeObject:metadata.fileName];
  209. [self.shareTable performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
  210. [self performSelector:@selector(selectPost) withObject:nil afterDelay:0.1];
  211. } else {
  212. // remove file
  213. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  214. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:fileID] error:nil];
  215. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:fileID] error:nil];
  216. // message error
  217. if (errorCode != kCFURLErrorCancelled) {
  218. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:errorMessage preferredStyle:UIAlertControllerStyleAlert];
  219. UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
  220. handler:^(UIAlertAction * action) {
  221. [alert dismissViewControllerAnimated:YES completion:nil];
  222. [self closeShareViewController];
  223. }];
  224. [alert addAction:ok];
  225. [self presentViewController:alert animated:YES completion:nil];
  226. }
  227. else
  228. [self closeShareViewController];
  229. }
  230. }
  231. - (void)addNetworkingQueue:(CCMetadataNet *)metadataNet
  232. {
  233. id operation;
  234. operation = [[OCnetworking alloc] initWithDelegate:self metadataNet:metadataNet withUser:_activeUser withUserID:_activeUserID withPassword:_activePassword withUrl:_activeUrl];
  235. [operation setQueuePriority:metadataNet.priority];
  236. [_networkingOperationQueue addOperation:operation];
  237. }
  238. #pragma --------------------------------------------------------------------------------------------
  239. #pragma mark ===== Lock Password =====
  240. #pragma --------------------------------------------------------------------------------------------
  241. - (void)openBKPasscode
  242. {
  243. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  244. viewController.delegate = self;
  245. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  246. viewController.inputViewTitlePassword = YES;
  247. if ([CCUtility getSimplyBlockCode]) {
  248. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  249. viewController.passcodeInputView.maximumLength = 6;
  250. } else {
  251. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  252. viewController.passcodeInputView.maximumLength = 64;
  253. }
  254. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  255. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  256. viewController.touchIDManager = touchIDManager;
  257. viewController.title = [NCBrandOptions sharedInstance].brand;
  258. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  259. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  260. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  261. [self presentViewController:navController animated:YES completion:nil];
  262. }
  263. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  264. {
  265. return self.failedAttempts;
  266. }
  267. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  268. {
  269. return self.lockUntilDate;
  270. }
  271. - (void)passcodeViewCloseButtonPressed:(id)sender
  272. {
  273. [self dismissViewControllerAnimated:YES completion:^{
  274. [self performSelector:@selector(closeShareViewController) withObject:nil];
  275. }];
  276. }
  277. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  278. {
  279. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  280. self.lockUntilDate = nil;
  281. self.failedAttempts = 0;
  282. aResultHandler(YES);
  283. } else aResultHandler(NO);
  284. }
  285. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  286. {
  287. [aViewController dismissViewControllerAnimated:YES completion:nil];
  288. }
  289. #pragma --------------------------------------------------------------------------------------------
  290. #pragma mark ===== Swipe Table DELETE -> menu =====
  291. #pragma--------------------------------------------------------------------------------------------
  292. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  293. {
  294. [self setEditing:NO animated:YES];
  295. NSString *fileName = [self.filesName objectAtIndex:indexPath.row];
  296. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] error:nil];
  297. [self.filesName removeObjectAtIndex:indexPath.row];
  298. if ([self.filesName count] == 0) [self closeShareViewController];
  299. else [self.shareTable performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
  300. }
  301. #pragma --------------------------------------------------------------------------------------------
  302. #pragma mark == Table ==
  303. #pragma --------------------------------------------------------------------------------------------
  304. - (void)loadDataSwift
  305. {
  306. CCloadItemData *loadItem = [[CCloadItemData alloc] init];
  307. [loadItem loadFiles:NSTemporaryDirectory() extensionContext:self.extensionContext vc:self];
  308. }
  309. - (void)reloadData:(NSArray *)files
  310. {
  311. totalSize = 0;
  312. for (NSString *file in files) {
  313. NSUInteger fileSize = (NSInteger)[[[NSFileManager defaultManager] attributesOfItemAtPath:[NSTemporaryDirectory() stringByAppendingString:file] error:nil] fileSize];
  314. totalSize += fileSize;
  315. }
  316. if (totalSize > 0) {
  317. self.filesName = [[NSMutableArray alloc] initWithArray:files];
  318. [self.shareTable reloadData];
  319. } else {
  320. [self closeShareViewController];
  321. }
  322. }
  323. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  324. {
  325. return 80;
  326. }
  327. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  328. {
  329. return 1;
  330. }
  331. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  332. {
  333. return [self.filesName count];
  334. }
  335. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  336. {
  337. NSString *fileName = [self.filesName objectAtIndex:indexPath.row];
  338. UIImage *image = nil;
  339. CCCellShareExt *cell = (CCCellShareExt *)[tableView dequeueReusableCellWithIdentifier:@"ShareExtCell" forIndexPath:indexPath];
  340. CFStringRef fileExtension = (__bridge CFStringRef)[fileName pathExtension];
  341. CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
  342. if (UTTypeConformsTo(fileUTI, kUTTypeZipArchive) && [(__bridge NSString *)fileUTI containsString:@"org.openxmlformats"] == NO) image = [UIImage imageNamed:@"file_compress"];
  343. else if (UTTypeConformsTo(fileUTI, kUTTypeAudio)) image = [UIImage imageNamed:@"file_audio"];
  344. else if (UTTypeConformsTo(fileUTI, kUTTypeMovie)) image = [UIImage imageNamed:@"file_movie"];
  345. else if (UTTypeConformsTo(fileUTI, kUTTypeImage)) {
  346. image = [UIImage imageWithContentsOfFile:[NSTemporaryDirectory() stringByAppendingString:fileName]];
  347. if (image) {
  348. image = [NCUtility.sharedInstance resizeImageWithImage:image newWidth:cell.frame.size.width];
  349. } else {
  350. image = [UIImage imageNamed:@"file_photo"];
  351. }
  352. }
  353. else if (UTTypeConformsTo(fileUTI, kUTTypeContent)) {
  354. image = [UIImage imageNamed:@"document"];
  355. NSString *typeFile = (__bridge NSString *)fileUTI;
  356. if ([typeFile isEqualToString:@"com.adobe.pdf"]) image = [UIImage imageNamed:@"file_pdf"];
  357. if ([typeFile isEqualToString:@"org.openxmlformats.spreadsheetml.sheet"]) image = [UIImage imageNamed:@"file_xls"];
  358. if ([typeFile isEqualToString:@"public.plain-text"]) image = [UIImage imageNamed:@"file_txt"];
  359. }
  360. else image = [UIImage imageNamed:@"file"];
  361. NSUInteger fileSize = (NSInteger)[[[NSFileManager defaultManager] attributesOfItemAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] error:nil] fileSize];
  362. cell.labelInformazioni.text = [NSString stringWithFormat:@"%@\r\r%@", fileName, [CCUtility transformedSize:fileSize]];
  363. cell.labelInformazioni.textColor = [UIColor blackColor];
  364. cell.fileImageView.image = image;
  365. return cell;
  366. }
  367. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  368. {
  369. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  370. }
  371. @end