ShareViewController.m 19 KB

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