ShareViewController.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. //
  2. // ShareViewController.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 26/01/16.
  6. // Copyright (c) 2016 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 () <NCSelectDestinationDelegate>
  27. {
  28. NSURL *dirGroup;
  29. NSUInteger totalSize;
  30. NSExtensionItem *inputItem;
  31. UIColor *barTintColor;
  32. UIColor *tintColor;
  33. NSString *fileNameOriginal;
  34. UIBarButtonItem *rightButtonUpload, *leftButtonCancel;
  35. }
  36. @end
  37. @implementation ShareViewController
  38. #pragma --------------------------------------------------------------------------------------------
  39. #pragma mark ===== View =====
  40. #pragma --------------------------------------------------------------------------------------------
  41. -(void)viewDidLoad
  42. {
  43. tableAccount *tableAccount = [[NCManageDatabase shared] getAccountActive];
  44. if (tableAccount == nil) {
  45. // close now
  46. [self performSelector:@selector(closeShareViewController) withObject:nil afterDelay:0.1];
  47. return;
  48. } else {
  49. NSInteger serverVersionMajor = [[NCManageDatabase shared] getCapabilitiesServerIntWithAccount:tableAccount.account elements:NCElementsJSON.shared.capabilitiesVersionMajor];
  50. NSString *webDav = [[NCUtilityFileSystem shared] getWebDAVWithAccount:tableAccount.account];
  51. // LOG
  52. NSInteger levelLog = [CCUtility getLogLevel];
  53. [[NCCommunicationCommon shared] setLevelLog:levelLog];
  54. NSString *pathDirectoryGroup = [[CCUtility getDirectoryGroup] path];
  55. [[NCCommunicationCommon shared] setPathLog: pathDirectoryGroup];
  56. [[NCCommunicationCommon shared] setCopyLogToDocumentDirectory: true];
  57. NSString *versionNextcloudiOS = [NSString stringWithFormat:[NCBrandOptions shared].textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp];
  58. [[NCCommunicationCommon shared] writeLog:[NSString stringWithFormat:@"Start session with level %lu %@", (unsigned long)levelLog, versionNextcloudiOS]];
  59. // Networking
  60. [[NCCommunicationCommon shared] setupWithAccount:tableAccount.account user:tableAccount.user userId:tableAccount.userID password:[CCUtility getPassword:tableAccount.account] urlBase:tableAccount.urlBase userAgent:[CCUtility getUserAgent] webDav:webDav dav:nil nextcloudVersion:serverVersionMajor delegate:[NCNetworking shared]];
  61. _account = tableAccount.account;
  62. _urlBase = tableAccount.urlBase;
  63. if ([_account isEqualToString:[CCUtility getAccountExt]]) {
  64. // load
  65. _serverUrl = [CCUtility getServerUrlExt];
  66. _destinyFolderButton.title = [NSString stringWithFormat:NSLocalizedString(@"_destiny_folder_", nil), [CCUtility getTitleServerUrlExt]];
  67. } else {
  68. // Default settings
  69. [CCUtility setAccountExt:self.account];
  70. _serverUrl = [[NCUtilityFileSystem shared] getHomeServerWithUrlBase:tableAccount.urlBase account:tableAccount.account];
  71. [CCUtility setServerUrlExt:_serverUrl];
  72. _destinyFolderButton.title = [NSString stringWithFormat:NSLocalizedString(@"_destiny_folder_", nil), NSLocalizedString(@"_home_", nil)];
  73. [CCUtility setTitleServerUrlExt:NSLocalizedString(@"_home_", nil)];
  74. }
  75. }
  76. self.filesName = [[NSMutableArray alloc] init];
  77. self.hud = [[CCHud alloc] initWithView:self.navigationController.view];
  78. [self.shareTable registerNib:[UINib nibWithNibName:@"CCCellShareExt" bundle:nil] forCellReuseIdentifier:@"ShareExtCell"];
  79. [self navigationBarToolBar];
  80. [self loadDataSwift];
  81. }
  82. - (void)viewWillAppear:(BOOL)animated
  83. {
  84. [super viewWillAppear:animated];
  85. self.view.backgroundColor = NCBrandColor.shared.backgroundView;
  86. self.shareTable.backgroundColor = NCBrandColor.shared.backgroundView;
  87. }
  88. - (void)closeShareViewController
  89. {
  90. [self.extensionContext completeRequestReturningItems:self.extensionContext.inputItems completionHandler:nil];
  91. }
  92. - (void)applicationWillTerminate:(UIApplication *)application
  93. {
  94. NSLog(@"[LOG] bye bye, Nextcloud Share Extension!");
  95. }
  96. #pragma --------------------------------------------------------------------------------------------
  97. #pragma mark == TextField Delegate ==
  98. #pragma --------------------------------------------------------------------------------------------
  99. - (void)textFieldDidBeginEditing:(UITextField *)textField
  100. {
  101. rightButtonUpload.enabled = false;
  102. fileNameOriginal = textField.text;
  103. }
  104. - (void)textFieldDidEndEditing:(UITextField *)textField
  105. {
  106. rightButtonUpload.enabled = true;
  107. NSInteger index = [self.filesName indexOfObject:fileNameOriginal];
  108. if (index != NSNotFound) {
  109. self.filesName[index] = textField.text;
  110. }
  111. }
  112. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
  113. {
  114. NSError *error;
  115. if ([string isEqualToString:@"\n"]) {
  116. //NSString *fileName = [textField.text stringByDeletingPathExtension];
  117. NSString *ext = [textField.text pathExtension];
  118. if (![ext isEqualToString:@""]) {
  119. NSString *fileNameAtPath = [NSTemporaryDirectory() stringByAppendingString:fileNameOriginal];
  120. NSString *fileNameToPath = [NSTemporaryDirectory() stringByAppendingString:textField.text];
  121. [[NSFileManager defaultManager] moveItemAtPath:fileNameAtPath toPath:fileNameToPath error:&error];
  122. if (error != nil) {
  123. textField.text = fileNameOriginal;
  124. }
  125. } else {
  126. textField.text = fileNameOriginal;
  127. }
  128. [textField endEditing:true];
  129. return false;
  130. }
  131. return true;
  132. }
  133. #pragma --------------------------------------------------------------------------------------------
  134. #pragma mark == Action ==
  135. #pragma --------------------------------------------------------------------------------------------
  136. - (void)navigationBarToolBar
  137. {
  138. // Theming
  139. if ([NCBrandOptions shared].use_themingColor) {
  140. NSString *themingColor = [[NCManageDatabase shared] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColor];
  141. NSString *themingColorElement = [[NCManageDatabase shared] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColorElement];
  142. NSString *themingColorText = [[NCManageDatabase shared] getCapabilitiesServerStringWithAccount:self.account elements:NCElementsJSON.shared.capabilitiesThemingColorText];
  143. [NCBrandColor.shared settingBrandColor:themingColor themingColorElement:themingColorElement themingColorText:themingColorText];
  144. }
  145. self.navigationController.navigationBar.barTintColor = NCBrandColor.shared.brand;
  146. self.navigationController.navigationBar.tintColor = NCBrandColor.shared.brandText;
  147. self.toolBar.barTintColor = NCBrandColor.shared.tabBar;
  148. self.toolBar.tintColor = [UIColor grayColor];
  149. // Upload
  150. rightButtonUpload = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_save_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(selectPost)];
  151. // Cancel
  152. leftButtonCancel = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelPost)];
  153. // Title
  154. [self.navigationController.navigationBar setTitleTextAttributes: @{NSForegroundColorAttributeName:self.navigationController.navigationBar.tintColor}];
  155. self.navigationItem.title = [NCBrandOptions shared].brand;
  156. self.navigationItem.leftBarButtonItem = leftButtonCancel;
  157. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:rightButtonUpload, nil];
  158. self.navigationItem.hidesBackButton = YES;
  159. }
  160. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title type:(NSString *)type
  161. {
  162. // DENIED e2e
  163. if ([CCUtility isFolderEncrypted:serverUrlTo e2eEncrypted:false account:self.account urlBase:self.urlBase]) {
  164. return;
  165. }
  166. if (serverUrlTo)
  167. _serverUrl = serverUrlTo;
  168. if (title) {
  169. self.destinyFolderButton.title = [NSString stringWithFormat:NSLocalizedString(@"_destiny_folder_", nil), title];
  170. [CCUtility setTitleServerUrlExt:title];
  171. } else {
  172. self.destinyFolderButton.title = [NSString stringWithFormat:NSLocalizedString(@"_destiny_folder_", nil), NSLocalizedString(@"_home_", nil)];
  173. [CCUtility setTitleServerUrlExt:NSLocalizedString(@"_home_", nil)];
  174. }
  175. [CCUtility setAccountExt:self.account];
  176. [CCUtility setServerUrlExt:_serverUrl];
  177. }
  178. - (IBAction)destinyFolderButtonTapped:(UIBarButtonItem *)sender
  179. {
  180. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCSelectDestination" bundle:nil] instantiateInitialViewController];
  181. NCSelectDestination *viewController = (NCSelectDestination *)navigationController.topViewController;
  182. viewController.delegate = self;
  183. viewController.move.title = NSLocalizedString(@"_select_", nil);
  184. viewController.tintColor = tintColor;
  185. viewController.barTintColor = barTintColor;
  186. viewController.tintColorTitle = tintColor;
  187. // E2EE
  188. viewController.includeDirectoryE2EEncryption = NO;
  189. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  190. [self presentViewController:navigationController animated:YES completion:nil];
  191. }
  192. - (void)selectPost
  193. {
  194. if ([self.filesName count] > 0) {
  195. [self.hud visibleHudTitle:NSLocalizedString(@"_uploading_", nil) mode:MBProgressHUDModeDeterminate color:NCBrandColor.shared.brandElement];
  196. NSString *fileName = [self.filesName objectAtIndex:0];
  197. NSString *fileNameLocal = [NSTemporaryDirectory() stringByAppendingString:fileName];
  198. // CONVERSION -->
  199. if ([fileName.pathExtension.uppercaseString isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
  200. UIImage *image = [UIImage imageWithContentsOfFile:fileNameLocal];
  201. if (image != nil) {
  202. fileName = fileName.stringByDeletingPathExtension;
  203. fileName = [NSString stringWithFormat:@"%@.jpg", fileName];
  204. [self.filesName replaceObjectAtIndex:0 withObject:fileName];
  205. fileNameLocal = [NSTemporaryDirectory() stringByAppendingString:fileName];
  206. [UIImageJPEGRepresentation(image, 1.0) writeToFile:fileNameLocal atomically:YES];
  207. [self.shareTable reloadData];
  208. }
  209. }
  210. // <--
  211. NSString *fileNameForUpload = [[NCUtilityFileSystem shared] createFileName:fileName serverUrl:self.serverUrl account:self.account];
  212. NSString *fileNameServer = [NSString stringWithFormat:@"%@/%@", self.serverUrl, fileNameForUpload];
  213. [[NCCommunication shared] uploadWithServerUrlFileName:fileNameServer fileNameLocalPath:fileNameLocal dateCreationFile:nil dateModificationFile:nil customUserAgent:nil addCustomHeaders:nil taskHandler:^(NSURLSessionTask *task) {
  214. } progressHandler:^(NSProgress *progress) {
  215. [self.hud progress:progress.fractionCompleted];
  216. } completionHandler:^(NSString *account, NSString *ocId, NSString *etag, NSDate *date, int64_t size, NSDictionary *allHeaderFields, NSInteger errorCode, NSString *errorDescription) {
  217. [self.hud hideHud];
  218. [self.filesName removeObject:fileName];
  219. if (errorCode == 0) {
  220. [CCUtility copyFileAtPath:fileNameLocal toPath:[CCUtility getDirectoryProviderStorageOcId:ocId fileNameView:fileNameForUpload]];
  221. tableMetadata *metadata = [[NCManageDatabase shared] createMetadataWithAccount:self.account fileName:fileNameForUpload ocId:ocId serverUrl:self.serverUrl urlBase:self.urlBase url:@"" contentType:@"" livePhoto:false];
  222. metadata.date = date;
  223. metadata.etag = etag;
  224. metadata.serverUrl = self.serverUrl;
  225. metadata.size = size;
  226. [[NCManageDatabase shared] addMetadata:metadata];
  227. [[NCManageDatabase shared] addLocalFileWithMetadata:metadata];
  228. [self.shareTable performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
  229. [self performSelector:@selector(selectPost) withObject:nil];
  230. } else {
  231. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message: errorDescription preferredStyle:UIAlertControllerStyleAlert];
  232. UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
  233. handler:^(UIAlertAction * action) {
  234. [alert dismissViewControllerAnimated:YES completion:nil];
  235. [self closeShareViewController];
  236. }];
  237. [alert addAction:ok];
  238. [self presentViewController:alert animated:YES completion:nil];
  239. }
  240. }];
  241. } else {
  242. [self closeShareViewController];
  243. }
  244. }
  245. - (void)cancelPost
  246. {
  247. // rimuoviamo i file+ico
  248. for (NSString *fileName in self.filesName) {
  249. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] error:nil];
  250. }
  251. [self closeShareViewController];
  252. }
  253. #pragma --------------------------------------------------------------------------------------------
  254. #pragma mark ===== Swipe Table DELETE -> menu =====
  255. #pragma--------------------------------------------------------------------------------------------
  256. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  257. {
  258. [self setEditing:NO animated:YES];
  259. NSString *fileName = [self.filesName objectAtIndex:indexPath.row];
  260. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] error:nil];
  261. [self.filesName removeObjectAtIndex:indexPath.row];
  262. if ([self.filesName count] == 0) [self closeShareViewController];
  263. else [self.shareTable performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
  264. }
  265. #pragma --------------------------------------------------------------------------------------------
  266. #pragma mark == Table ==
  267. #pragma --------------------------------------------------------------------------------------------
  268. - (void)loadDataSwift
  269. {
  270. CCloadItemData *loadItem = [[CCloadItemData alloc] init];
  271. [loadItem loadFiles:NSTemporaryDirectory() extensionContext:self.extensionContext vc:self];
  272. }
  273. - (void)reloadData:(NSArray *)files
  274. {
  275. totalSize = 0;
  276. for (NSString *file in files) {
  277. NSUInteger fileSize = (NSInteger)[[[NSFileManager defaultManager] attributesOfItemAtPath:[NSTemporaryDirectory() stringByAppendingString:file] error:nil] fileSize];
  278. totalSize += fileSize;
  279. }
  280. if (totalSize > 0) {
  281. self.filesName = [[NSMutableArray alloc] initWithArray:files];
  282. [self.shareTable reloadData];
  283. } else {
  284. [self closeShareViewController];
  285. }
  286. }
  287. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  288. {
  289. return 80;
  290. }
  291. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  292. {
  293. return 1;
  294. }
  295. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  296. {
  297. return [self.filesName count];
  298. }
  299. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  300. {
  301. NSString *fileName = [self.filesName objectAtIndex:indexPath.row];
  302. UIImage *image = nil;
  303. CCCellShareExt *cell = (CCCellShareExt *)[tableView dequeueReusableCellWithIdentifier:@"ShareExtCell" forIndexPath:indexPath];
  304. CFStringRef fileExtension = (__bridge CFStringRef)[fileName pathExtension];
  305. CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
  306. if (UTTypeConformsTo(fileUTI, kUTTypeZipArchive) && [(__bridge NSString *)fileUTI containsString:@"org.openxmlformats"] == NO) image = [UIImage imageNamed:@"file_compress"];
  307. else if (UTTypeConformsTo(fileUTI, kUTTypeAudio)) image = [UIImage imageNamed:@"file_audio"];
  308. else if (UTTypeConformsTo(fileUTI, kUTTypeMovie)) image = [UIImage imageNamed:@"file_movie"];
  309. else if (UTTypeConformsTo(fileUTI, kUTTypeImage)) {
  310. image = [UIImage imageWithContentsOfFile:[NSTemporaryDirectory() stringByAppendingString:fileName]];
  311. if (image) {
  312. image = [image resizeImageWithSize:CGSizeMake(100, 100) isAspectRation:true];
  313. } else {
  314. image = [UIImage imageNamed:@"file_photo"];
  315. }
  316. }
  317. else if (UTTypeConformsTo(fileUTI, kUTTypeContent)) {
  318. image = [UIImage imageNamed:@"document"];
  319. NSString *typeFile = (__bridge NSString *)fileUTI;
  320. if ([typeFile isEqualToString:@"com.adobe.pdf"]) image = [UIImage imageNamed:@"file_pdf"];
  321. if ([typeFile isEqualToString:@"org.openxmlformats.spreadsheetml.sheet"]) image = [UIImage imageNamed:@"file_xls"];
  322. if ([typeFile isEqualToString:@"public.plain-text"]) image = [UIImage imageNamed:@"file_txt"];
  323. }
  324. else image = [UIImage imageNamed:@"file"];
  325. NSUInteger fileSize = (NSInteger)[[[NSFileManager defaultManager] attributesOfItemAtPath:[NSTemporaryDirectory() stringByAppendingString:fileName] error:nil] fileSize];
  326. cell.fileImageView.image = image;
  327. cell.fileName.text = fileName;
  328. cell.fileName.textColor = NCBrandColor.shared.textView;
  329. cell.fileName.delegate = self;
  330. cell.info.text = [CCUtility transformedSize:fileSize];
  331. cell.info.textColor = NCBrandColor.shared.textView;
  332. return cell;
  333. }
  334. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  335. {
  336. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  337. }
  338. @end