CCDetail.m 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. //
  2. // CCDetail.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 16/01/15.
  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 "CCDetail.h"
  24. #import "AppDelegate.h"
  25. #import "CCMain.h"
  26. #import "NCUchardet.h"
  27. #import "NCBridgeSwift.h"
  28. #import <KTVHTTPCache/KTVHTTPCache.h>
  29. #import "NCBridgeSwift.h"
  30. #define TOOLBAR_HEIGHT 49.0f
  31. #define alertRequestPasswordPDF 1
  32. @interface CCDetail () <NCTextDelegate, UIDocumentInteractionControllerDelegate>
  33. {
  34. AppDelegate *appDelegate;
  35. UIDocumentInteractionController *docController;
  36. UIBarButtonItem *buttonModifyTxt;
  37. UIBarButtonItem *buttonShare;
  38. UIBarButtonItem *buttonDelete;
  39. NSInteger indexNowVisible;
  40. NSString *fileIDNowVisible;
  41. NSMutableOrderedSet *dataSourceDirectoryID;
  42. NSString *fileNameExtension;
  43. }
  44. @end
  45. @implementation CCDetail
  46. #pragma --------------------------------------------------------------------------------------------
  47. #pragma mark ===== init =====
  48. #pragma --------------------------------------------------------------------------------------------
  49. - (id)initWithCoder:(NSCoder *)aDecoder
  50. {
  51. if (self = [super initWithCoder:aDecoder]) {
  52. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  53. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  54. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  55. self.metadataDetail = [[tableMetadata alloc] init];
  56. self.photos = [[NSMutableArray alloc] init];
  57. self.photoDataSource = [NSMutableArray new];
  58. dataSourceDirectoryID = [[NSMutableOrderedSet alloc] init];
  59. indexNowVisible = -1;
  60. fileIDNowVisible = nil;
  61. appDelegate.activeDetail = self;
  62. }
  63. return self;
  64. }
  65. #pragma --------------------------------------------------------------------------------------------
  66. #pragma mark ===== View =====
  67. #pragma --------------------------------------------------------------------------------------------
  68. - (void)viewDidLoad
  69. {
  70. [super viewDidLoad];
  71. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertGeocoderLocation:) name:@"insertGeocoderLocation" object:nil];
  72. self.imageBackground.image = [UIImage imageNamed:@"backgroundDetail"];
  73. // Change bar bottom line shadow and remove title back button <"title"
  74. self.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  75. self.navigationController.navigationBar.topItem.title = @"";
  76. // Color Navigation Controller
  77. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  78. // TabBar
  79. self.tabBarController.tabBar.hidden = YES;
  80. self.tabBarController.tabBar.translucent = YES;
  81. // Open View
  82. if ([self.metadataDetail.fileNameView length] > 0 || [self.metadataDetail.directoryID length] > 0 || [self.metadataDetail.fileID length] > 0) {
  83. // open view
  84. [self viewFile];
  85. }
  86. }
  87. - (void)viewWillAppear:(BOOL)animated
  88. {
  89. [super viewWillAppear:animated];
  90. self.tabBarController.tabBar.hidden = YES;
  91. self.tabBarController.tabBar.translucent = YES;
  92. }
  93. - (void)viewDidDisappear:(BOOL)animated
  94. {
  95. [super viewDidDisappear:animated];
  96. // If AVPlayer in play -> Stop
  97. if (appDelegate.player != nil && appDelegate.player.rate != 0) {
  98. [appDelegate.player pause];
  99. }
  100. // remove Observer AVPlayer
  101. if (self.isMediaObserver) {
  102. self.isMediaObserver = NO;
  103. @try{
  104. [[NCViewerMedia sharedInstance] removeObserver];
  105. }@catch(id anException) { }
  106. }
  107. }
  108. - (void)changeTheming
  109. {
  110. [appDelegate changeTheming:self];
  111. if (self.toolbar) {
  112. self.toolbar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  113. self.toolbar.tintColor = [NCBrandColor sharedInstance].brandElement;
  114. }
  115. }
  116. - (void)changeToDisplayMode
  117. {
  118. if (_readerPDFViewController)
  119. [self.readerPDFViewController updateContentViews];
  120. }
  121. #pragma --------------------------------------------------------------------------------------------
  122. #pragma mark ===== View File =====
  123. #pragma --------------------------------------------------------------------------------------------
  124. - (void)viewFile
  125. {
  126. // Title
  127. self.navigationController.navigationBar.topItem.title = _metadataDetail.fileNameView;
  128. // verifico se esiste l'icona e se la posso creare
  129. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView]] == NO) {
  130. [CCGraphics createNewImageFrom:self.metadataDetail.fileNameView fileID:self.metadataDetail.fileID extension:[self.metadataDetail.fileNameView pathExtension] filterGrayScale:NO typeFile:self.metadataDetail.typeFile writeImage:YES];
  131. }
  132. // remove Observer AVPlayer
  133. if (self.isMediaObserver) {
  134. self.isMediaObserver = NO;
  135. [[NCViewerMedia sharedInstance] removeObserver];
  136. }
  137. // IMAGE
  138. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_image]) {
  139. self.edgesForExtendedLayout = UIRectEdgeAll;
  140. [self viewImage];
  141. }
  142. // AUDIO VIDEO
  143. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_audio]) {
  144. self.edgesForExtendedLayout = UIRectEdgeAll;
  145. [self createToolbar];
  146. [self viewMedia];
  147. }
  148. // DOCUMENT
  149. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_document]) {
  150. BOOL openWithRichDocument = false;
  151. fileNameExtension = [[self.metadataDetail.fileNameView pathExtension] uppercaseString];
  152. if ([fileNameExtension isEqualToString:@"PDF"]) {
  153. self.edgesForExtendedLayout = UIRectEdgeBottom;
  154. [self createToolbar];
  155. [self viewPDF:@""];
  156. return;
  157. }
  158. // Very if mimeType is compatible with Rich Document viewer
  159. NSString *mimeType = [CCUtility getMimeType:self.metadataDetail.fileNameView];
  160. NSArray *richdocumentsMimetypes = [[NCManageDatabase sharedInstance] getRichdocumentsMimetypes];
  161. if (richdocumentsMimetypes.count > 0 & mimeType != nil && [mimeType componentsSeparatedByString:@"."].count > 2) {
  162. NSArray *mimeTypeArray = [mimeType componentsSeparatedByString:@"."];
  163. NSString *mimeType = [NSString stringWithFormat:@"%@.%@",mimeTypeArray[mimeTypeArray.count-2], mimeTypeArray[mimeTypeArray.count-1]];
  164. for (NSString *richdocumentMimetype in richdocumentsMimetypes) {
  165. if ([richdocumentMimetype containsString:mimeType]) {
  166. openWithRichDocument = true;
  167. }
  168. }
  169. }
  170. if (openWithRichDocument) {
  171. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  172. [ocNetworking createLinkRichdocumentsWithFileID:self.metadataDetail.fileID success:^(NSString *link) {
  173. [[NCViewerRichdocument sharedInstance] viewRichDocumentAt:link viewDetail:self];
  174. } failure:^(NSString *message, NSInteger errorCode) {
  175. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  176. [self.navigationController popViewControllerAnimated:YES];
  177. }];
  178. return;
  179. }
  180. self.edgesForExtendedLayout = UIRectEdgeBottom;
  181. [self createToolbar];
  182. [self viewDocument];
  183. }
  184. }
  185. #pragma --------------------------------------------------------------------------------------------
  186. #pragma mark ===== Toolbar =====
  187. #pragma --------------------------------------------------------------------------------------------
  188. - (void)createToolbar
  189. {
  190. CGFloat safeAreaBottom = 0;
  191. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadataDetail.directoryID];
  192. if (!serverUrl)
  193. return;
  194. if (@available(iOS 11, *)) {
  195. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  196. }
  197. self.toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom, self.view.bounds.size.width, TOOLBAR_HEIGHT)];
  198. UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
  199. UIBarButtonItem *fixedSpaceMini = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  200. fixedSpaceMini.width = 25;
  201. buttonModifyTxt = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"actionSheetModify"] style:UIBarButtonItemStylePlain target:self action:@selector(modifyTxtButtonPressed:)];
  202. if (![NCBrandOptions sharedInstance].disable_openin_file) {
  203. self.buttonAction = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"openFile"] style:UIBarButtonItemStylePlain target:self action:@selector(actionButtonPressed:)];
  204. }
  205. buttonShare = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share"] style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonPressed:)];
  206. buttonDelete = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteButtonPressed:)];
  207. if ([CCUtility isDocumentModifiableExtension:fileNameExtension]) {
  208. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) // E2EE
  209. [self.toolbar setItems:[NSArray arrayWithObjects: buttonModifyTxt, flexible, buttonDelete, fixedSpaceMini, self.buttonAction, nil]];
  210. else
  211. [self.toolbar setItems:[NSArray arrayWithObjects: buttonModifyTxt, flexible, buttonDelete, fixedSpaceMini, buttonShare, fixedSpaceMini, self.buttonAction, nil]];
  212. } else {
  213. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) // E2EE
  214. [self.toolbar setItems:[NSArray arrayWithObjects: flexible, buttonDelete, fixedSpaceMini, self.buttonAction, nil]];
  215. else
  216. [self.toolbar setItems:[NSArray arrayWithObjects: flexible, buttonDelete, fixedSpaceMini, buttonShare, fixedSpaceMini, self.buttonAction, nil]];
  217. }
  218. [self.toolbar setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  219. self.toolbar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  220. self.toolbar.tintColor = [NCBrandColor sharedInstance].brandElement;
  221. [self.view addSubview:self.toolbar];
  222. }
  223. #pragma --------------------------------------------------------------------------------------------
  224. #pragma mark ===== View Document =====
  225. #pragma --------------------------------------------------------------------------------------------
  226. - (void)viewDocument
  227. {
  228. CGFloat safeAreaBottom = 0;
  229. if (@available(iOS 11, *)) {
  230. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  231. }
  232. if ([CCUtility fileProviderStorageExists:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView] == NO) {
  233. [self.navigationController popViewControllerAnimated:YES];
  234. return;
  235. }
  236. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNameView];
  237. [[NSFileManager defaultManager] removeItemAtPath:fileNamePath error:nil];
  238. [[NSFileManager defaultManager] linkItemAtPath:[CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView] toPath:fileNamePath error:nil];
  239. NSURL *url = [NSURL fileURLWithPath:fileNamePath];
  240. WKPreferences *wkPreferences = [[WKPreferences alloc] init];
  241. wkPreferences.javaScriptEnabled = true;
  242. WKWebViewConfiguration *wkConfig = [[WKWebViewConfiguration alloc] init];
  243. wkConfig.preferences = wkPreferences;
  244. self.webView = [[WKWebView alloc] initWithFrame:(CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom)) configuration:wkConfig];
  245. self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  246. [self.webView setBackgroundColor:[NCBrandColor sharedInstance].backgroundView];
  247. [self.webView setOpaque:NO];
  248. if ( [fileNameExtension isEqualToString:@"CSS"] || [fileNameExtension isEqualToString:@"PY"] || [fileNameExtension isEqualToString:@"XML"] || [fileNameExtension isEqualToString:@"JS"] ) {
  249. NSString *dataFile = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:url] encoding:NSASCIIStringEncoding];
  250. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  251. [self.webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-size:%@;font-family:%@;'><pre>%@",@"40",@"Sans-Serif",dataFile] baseURL:nil];
  252. }else{
  253. [self.webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-size:%@;font-family:%@;'><pre>%@",@"20",@"Sans-Serif",dataFile] baseURL:nil];
  254. }
  255. } else if ([CCUtility isDocumentModifiableExtension:fileNameExtension]) {
  256. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  257. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
  258. NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
  259. [headRequest setHTTPMethod:@"HEAD"];
  260. NSURLSessionDataTask *task = [session dataTaskWithRequest:headRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  261. dispatch_async(dispatch_get_main_queue(), ^{
  262. NSString *encodingName = [[NCUchardet sharedNUCharDet] encodingStringDetectWithData:data];
  263. [self.webView loadData:[NSData dataWithContentsOfURL: url] MIMEType:response.MIMEType characterEncodingName:encodingName baseURL:url];
  264. });
  265. }];
  266. [task resume];
  267. } else {
  268. [self.webView loadRequest:[NSMutableURLRequest requestWithURL:url]];
  269. }
  270. [self.view addSubview:self.webView];
  271. }
  272. #pragma --------------------------------------------------------------------------------------------
  273. #pragma mark ===== View Media =====
  274. #pragma --------------------------------------------------------------------------------------------
  275. - (void)viewMedia
  276. {
  277. CGFloat safeAreaBottom = 0;
  278. if (@available(iOS 11, *)) {
  279. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  280. }
  281. [[NCViewerMedia sharedInstance] viewMedia:self.metadataDetail viewDetail:self width:self.view.bounds.size.width height:self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom];
  282. }
  283. #pragma --------------------------------------------------------------------------------------------
  284. #pragma mark ===== View Image =====
  285. #pragma --------------------------------------------------------------------------------------------
  286. - (void)viewImage
  287. {
  288. self.photoBrowser = [[MWPhotoBrowser alloc] initWithDelegate:self];
  289. indexNowVisible = -1;
  290. fileIDNowVisible = nil;
  291. [self.photos removeAllObjects];
  292. [dataSourceDirectoryID removeAllObjects];
  293. // if not images, exit
  294. if ([self.photoDataSource count] == 0)
  295. return;
  296. // test
  297. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadataDetail.directoryID];
  298. if (!serverUrl)
  299. return;
  300. NSUInteger index = 0;
  301. for (tableMetadata *metadata in self.photoDataSource) {
  302. // start from here ?
  303. if (self.metadataDetail.fileID && [metadata.fileID isEqualToString:self.metadataDetail.fileID])
  304. [self.photoBrowser setCurrentPhotoIndex:index];
  305. [self.photos addObject:[MWPhoto photoWithImage:nil]];
  306. // add directory
  307. [dataSourceDirectoryID addObject:metadata.directoryID];
  308. index++;
  309. }
  310. // PhotoBrowser
  311. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  312. self.photoBrowser.displayActionButton = NO;
  313. } else {
  314. self.photoBrowser.displayActionButton = YES;
  315. }
  316. self.photoBrowser.displayDeleteButton = YES;
  317. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) // E2EE
  318. self.photoBrowser.displayShareButton = NO;
  319. else
  320. self.photoBrowser.displayShareButton = YES;
  321. self.photoBrowser.displayNavArrows = YES;
  322. self.photoBrowser.displaySelectionButtons = NO;
  323. self.photoBrowser.alwaysShowControls = NO;
  324. self.photoBrowser.zoomPhotosToFill = NO;
  325. self.photoBrowser.autoPlayOnAppear = NO;
  326. self.photoBrowser.delayToHideElements = 15;
  327. if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)
  328. self.photoBrowser.enableSwipeToDismiss = NO;
  329. if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
  330. [self addChildViewController:self.photoBrowser];
  331. [self.view addSubview:self.photoBrowser.view];
  332. [self.photoBrowser didMoveToParentViewController:self];
  333. } else {
  334. [self.navigationController pushViewController:self.photoBrowser animated:NO];
  335. }
  336. }
  337. - (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
  338. {
  339. return [self.photoDataSource count];
  340. }
  341. - (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index
  342. {
  343. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  344. NSString *titleDir = metadata.fileNameView;
  345. self.title = titleDir;
  346. return titleDir;
  347. }
  348. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
  349. {
  350. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  351. indexNowVisible = index;
  352. fileIDNowVisible = metadata.fileID;
  353. photoBrowser.toolbar.hidden = NO;
  354. // Download image ?
  355. if (metadata) {
  356. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  357. NSInteger status;
  358. tableMetadata *metadataDB = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  359. if (metadataDB) {
  360. status = metadataDB.status;
  361. } else {
  362. status = k_metadataStatusNormal;
  363. }
  364. NSString *ext = [[metadata.fileNameView pathExtension] uppercaseString];
  365. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView] == NO && status == k_metadataStatusNormal) {
  366. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO) {
  367. [CCGraphics addImageToTitle:NSLocalizedString(@"_...loading..._", nil) colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"load"] multiplier:2 color:[NCBrandColor sharedInstance].brandText] imageRight:NO navigationItem:self.navigationItem];
  368. CGFloat width = [[NCUtility sharedInstance] getScreenWidthForPreview];
  369. CGFloat height = [[NCUtility sharedInstance] getScreenHeightForPreview];
  370. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  371. [ocNetworking downloadPreviewWithMetadata:metadata serverUrl:serverUrl withWidth:width andHeight:height completion:^(NSString *message, NSInteger errorCode) {
  372. self.navigationItem.titleView = nil;
  373. self.title = metadata.fileNameView;
  374. if (([CCUtility getOptimizedPhoto] == YES && errorCode != 0) || [CCUtility getOptimizedPhoto] == NO || [ext isEqualToString:@"GIF"]) {
  375. [self downloadPhotoBrowser:metadata serverUrl:serverUrl];
  376. }
  377. [self.photoBrowser reloadData];
  378. }];
  379. } else {
  380. if ([CCUtility getOptimizedPhoto] == NO || [ext isEqualToString:@"GIF"]) {
  381. [self downloadPhotoBrowser:metadata serverUrl:serverUrl];
  382. }
  383. }
  384. }
  385. }
  386. // Title
  387. if (metadata)
  388. self.title = metadata.fileNameView;
  389. }
  390. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
  391. {
  392. UIImage *image;
  393. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  394. if (index < self.photos.count) {
  395. if (metadata.fileID) {
  396. UIImage *imagePreview = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  397. // if (!imagePreview) imagePreview = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"file_photo"] multiplier:3 color:[[NCBrandColor sharedInstance] icon]];
  398. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  399. NSString *fileImage = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView];
  400. NSString *ext = [CCUtility getExtension:metadata.fileNameView];
  401. if ([ext isEqualToString:@"GIF"]) image = [UIImage animatedImageWithAnimatedGIFURL:[NSURL fileURLWithPath:fileImage]];
  402. else image = [UIImage imageWithContentsOfFile:fileImage];
  403. if (image) {
  404. MWPhoto *photo = [MWPhoto photoWithImage:image];
  405. // Location ??
  406. [self setLocationCaptionPhoto:photo fileID:metadata.fileID];
  407. [self.photos replaceObjectAtIndex:index withObject:photo];
  408. } else {
  409. if (metadata.status == k_metadataStatusDownloadError) {
  410. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  411. } else {
  412. if (imagePreview)
  413. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:imagePreview]];
  414. }
  415. }
  416. }
  417. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  418. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  419. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  420. MWPhoto *video = [MWPhoto photoWithImage:[CCGraphics thumbnailImageForVideo:url atTime:1.0]];
  421. video.videoURL = url;
  422. [self.photos replaceObjectAtIndex:index withObject:video];
  423. } else {
  424. if (metadata.status == k_metadataStatusDownloadError) {
  425. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  426. } else {
  427. if (imagePreview)
  428. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:imagePreview]];
  429. }
  430. }
  431. }
  432. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) {
  433. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  434. MWPhoto *audio;
  435. UIImage *audioImage;
  436. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  437. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]) {
  438. audioImage = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  439. } else {
  440. audioImage = [UIImage imageNamed:@"notaMusic"]; //[CCGraphics scaleImage:[UIImage imageNamed:@"notaMusic"] toSize:CGSizeMake(200, 200) isAspectRation:YES];
  441. }
  442. audio = [MWPhoto photoWithImage:audioImage];
  443. audio.videoURL = url;
  444. [self.photos replaceObjectAtIndex:index withObject:audio];
  445. } else {
  446. if (metadata.status == k_metadataStatusDownloadError) {
  447. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  448. } else {
  449. if (imagePreview)
  450. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:imagePreview]];
  451. }
  452. }
  453. }
  454. }
  455. // energy saving memory
  456. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  457. int iPrev = (int)index - 2;
  458. if (iPrev >= 0) {
  459. if ([self.photos objectAtIndex:iPrev] != nil)
  460. [self.photos replaceObjectAtIndex:iPrev withObject:[MWPhoto photoWithImage:nil]];
  461. }
  462. int iNext = (int)index + 2;
  463. if (iNext < _photos.count) {
  464. if ([self.photos objectAtIndex:iNext] != nil)
  465. [self.photos replaceObjectAtIndex:iNext withObject:[MWPhoto photoWithImage:nil]];
  466. }
  467. });
  468. return [self.photos objectAtIndex:index];
  469. }
  470. return nil;
  471. }
  472. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index
  473. {
  474. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  475. if (metadata == nil) return;
  476. docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]]];
  477. docController.delegate = self;
  478. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  479. [docController presentOptionsMenuFromRect:photoBrowser.view.frame inView:photoBrowser.view animated:YES];
  480. [docController presentOptionsMenuFromBarButtonItem:photoBrowser.actionButton animated:YES];
  481. }
  482. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser shareButtonPressedForPhotoAtIndex:(NSUInteger)index
  483. {
  484. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  485. [appDelegate.activeMain openWindowShare:metadata];
  486. }
  487. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser deleteButtonPressedForPhotoAtIndex:(NSUInteger)index deleteButton:(UIBarButtonItem *)deleteButton
  488. {
  489. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  490. if (metadata == nil || [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView] == NO) {
  491. [appDelegate messageNotification:@"_info_" description:@"_file_not_found_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  492. return;
  493. }
  494. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  495. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  496. style:UIAlertActionStyleDestructive
  497. handler:^(UIAlertAction *action) {
  498. [self deleteFile:metadata];
  499. }]];
  500. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  501. style:UIAlertActionStyleCancel
  502. handler:^(UIAlertAction *action) {
  503. }]];
  504. alertController.popoverPresentationController.barButtonItem = deleteButton;
  505. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  506. [alertController.view layoutIfNeeded];
  507. [self.parentViewController presentViewController:alertController animated:YES completion:NULL];
  508. }
  509. - (void)photoBrowserDidFinishPresentation:(MWPhotoBrowser *)photoBrowser
  510. {
  511. [self.navigationController popViewControllerAnimated:YES];
  512. }
  513. - (void)triggerProgressTask:(NSNotification *)notification
  514. {
  515. /*
  516. NSDictionary *dict = notification.userInfo;
  517. NSString *fileID = [dict valueForKey:@"fileID"];
  518. //NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  519. //long status = [[dict valueForKey:@"status"] longValue];
  520. float progress = [[dict valueForKey:@"progress"] floatValue];
  521. //long long totalBytes = [[dict valueForKey:@"totalBytes"] longLongValue];
  522. //long long totalBytesExpected = [[dict valueForKey:@"totalBytesExpected"] longLongValue];
  523. if ([fileID isEqualToString:_fileIDNowVisible])
  524. [_hud progress:progress];
  525. */
  526. }
  527. - (void)downloadPhotoBrowserSuccessFailure:(tableMetadata *)metadata selector:(NSString *)selector errorCode:(NSInteger)errorCode
  528. {
  529. // if a message for a directory of these
  530. if (![metadata.fileID isEqualToString:fileIDNowVisible])
  531. return;
  532. // Title
  533. self.navigationItem.titleView = nil;
  534. self.title = metadata.fileNameView;
  535. if (errorCode == 0) {
  536. // verifico se esiste l'icona e se la posso creare
  537. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO) {
  538. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] filterGrayScale:NO typeFile:metadata.typeFile writeImage:YES];
  539. }
  540. [self.photoBrowser reloadData];
  541. } else {
  542. [appDelegate messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  543. [self.navigationController popViewControllerAnimated:YES];
  544. }
  545. }
  546. - (void)downloadPhotoBrowser:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  547. {
  548. tableMetadata *metadataForDownload = [[NCManageDatabase sharedInstance] initNewMetadata:metadata];
  549. metadataForDownload.session = k_download_session;
  550. metadataForDownload.sessionError = @"";
  551. metadataForDownload.sessionSelector = selectorLoadViewImage;
  552. metadataForDownload.status = k_metadataStatusWaitDownload;
  553. // Add Metadata for Download
  554. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  555. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  556. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl fileID:metadataForDownload.fileID action:k_action_MOD];
  557. [CCGraphics addImageToTitle:NSLocalizedString(@"_...loading..._", nil) colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"load"] multiplier:2 color:[NCBrandColor sharedInstance].brandText] imageRight:NO navigationItem:self.navigationItem];
  558. }
  559. - (void)insertGeocoderLocation:(NSNotification *)notification
  560. {
  561. if (notification.userInfo.count == 0)
  562. return;
  563. NSString *fileID = [[notification.userInfo allKeys] objectAtIndex:0];
  564. //NSDate *date = [[notification.userInfo allValues] objectAtIndex:0];
  565. // test [Chrash V 1.14,15]
  566. if (indexNowVisible >= [self.photos count])
  567. return;
  568. if ([fileID isEqualToString:fileIDNowVisible]) {
  569. MWPhoto *photo = [self.photos objectAtIndex:indexNowVisible];
  570. [self setLocationCaptionPhoto:photo fileID:fileID];
  571. [self.photoBrowser reloadData];
  572. }
  573. }
  574. - (void)setLocationCaptionPhoto:(MWPhoto *)photo fileID:(NSString *)fileID
  575. {
  576. tableLocalFile *localFile;
  577. // read Geocoder
  578. localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  579. if ([localFile.exifLatitude doubleValue] != 0 || [localFile.exifLongitude doubleValue] != 0) {
  580. // Fix BUG Geo latitude & longitude
  581. if ([localFile.exifLatitude doubleValue] == 9999 || [localFile.exifLongitude doubleValue] == 9999) {
  582. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  583. if (metadata) {
  584. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  585. }
  586. }
  587. [[CCExifGeo sharedInstance] setGeocoderEtag:fileID exifDate:localFile.exifDate latitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  588. localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  589. if ([localFile.exifLatitude floatValue] != 0 || [localFile.exifLongitude floatValue] != 0) {
  590. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  591. if ([localFile.exifDate isEqualToDate:[NSDate distantPast]] == NO && location) {
  592. NSString *localizedDateTime = [NSDateFormatter localizedStringFromDate:localFile.exifDate dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterMediumStyle];
  593. photo.caption = [NSString stringWithFormat:NSLocalizedString(@"%@\n%@", nil), localizedDateTime, location];
  594. }
  595. }
  596. }
  597. }
  598. #pragma --------------------------------------------------------------------------------------------
  599. #pragma mark ===== View PDF =====
  600. #pragma --------------------------------------------------------------------------------------------
  601. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  602. {
  603. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  604. [[alertView textFieldAtIndex:0] resignFirstResponder];
  605. if (alertView.tag == alertRequestPasswordPDF) [self performSelector:@selector(viewPDF:) withObject:[alertView textFieldAtIndex:0].text afterDelay:0.3];
  606. }
  607. - (void)viewPDF:(NSString *)password
  608. {
  609. // remove cache PDF
  610. NSString *filePlistReader = [NSString stringWithFormat:@"%@/%@.plist", [CCUtility getDirectoryReaderMetadata], self.metadataDetail.fileNameView.stringByDeletingPathExtension];
  611. [CCUtility removeFileAtPath:filePlistReader];
  612. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView];
  613. if ([CCUtility fileProviderStorageExists:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView] == NO) {
  614. // read file error
  615. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  616. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  617. [alertController addAction:okAction];
  618. [self presentViewController:alertController animated:YES completion:nil];
  619. }
  620. CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:fileNamePath]);
  621. if (pdf) {
  622. // Encrypted
  623. if (CGPDFDocumentIsEncrypted(pdf) == YES) {
  624. // Try a blank password first, per Apple's Quartz PDF example
  625. if (CGPDFDocumentUnlockWithPassword(pdf, "") == YES) {
  626. // blank password
  627. [self readerPDF:fileNamePath password:@""];
  628. } else {
  629. if ([password length] == 0) {
  630. // password request
  631. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_insert_password_pfd_",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  632. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  633. alertView.tag = alertRequestPasswordPDF;
  634. [alertView show];
  635. } else {
  636. const char *key = [password UTF8String];
  637. // failure
  638. if (CGPDFDocumentUnlockWithPassword(pdf, key) == NO) {
  639. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_password_pdf_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  640. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  641. [alertController addAction:okAction];
  642. [self presentViewController:alertController animated:YES completion:nil];
  643. } else {
  644. // pdf with password
  645. [self readerPDF:fileNamePath password:password];
  646. }
  647. }
  648. }
  649. } else{
  650. // No password
  651. [self readerPDF:fileNamePath password:@""];
  652. }
  653. } else {
  654. // read file error
  655. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  656. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  657. [alertController addAction:okAction];
  658. [self presentViewController:alertController animated:YES completion:nil];
  659. }
  660. }
  661. - (void)readerPDF:(NSString *)fileName password:(NSString *)password
  662. {
  663. ReaderDocument *documentPDF = [ReaderDocument withDocumentFilePath:fileName password:password];
  664. CGFloat safeAreaBottom = 0;
  665. if (@available(iOS 11, *)) {
  666. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  667. }
  668. if (documentPDF != nil) {
  669. self.readerPDFViewController = [[ReaderViewController alloc] initWithReaderDocument:documentPDF];
  670. self.readerPDFViewController.delegate = self;
  671. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  672. [self.readerPDFViewController updateContentViews];
  673. [self addChildViewController:self.readerPDFViewController];
  674. [self.view addSubview:self.readerPDFViewController.view];
  675. [self.readerPDFViewController didMoveToParentViewController:self];
  676. } else {
  677. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  678. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  679. [alertController addAction:okAction];
  680. [self presentViewController:alertController animated:YES completion:nil];
  681. }
  682. }
  683. - (void)handleSingleTapReader
  684. {
  685. UILayoutGuide *layoutGuide;
  686. CGFloat safeAreaTop = 0;
  687. CGFloat safeAreaBottom = 0;
  688. if (@available(iOS 11, *)) {
  689. layoutGuide = [UIApplication sharedApplication].delegate.window.safeAreaLayoutGuide;
  690. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  691. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  692. }
  693. self.navigationController.navigationBarHidden = !self.navigationController.navigationBarHidden;
  694. self.toolbar.hidden = !self.toolbar.isHidden;
  695. if (self.toolbar.isHidden) {
  696. self.readerPDFViewController.view.frame = CGRectMake(0, safeAreaTop, self.view.bounds.size.width, self.view.bounds.size.height - safeAreaTop - safeAreaBottom);
  697. } else {
  698. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  699. }
  700. [self.readerPDFViewController updateContentViews];
  701. }
  702. - (void)handleSwipeUpDown
  703. {
  704. // REMOVE IT'S UNUSABLE
  705. /*
  706. self.navigationController.navigationBarHidden = false; // iOS App is unusable after swipe up or down with PDF in fullscreen #526
  707. [self removeAllView];
  708. [self.navigationController popViewControllerAnimated:YES];
  709. */
  710. }
  711. #pragma --------------------------------------------------------------------------------------------
  712. #pragma mark ===== Delete =====
  713. #pragma --------------------------------------------------------------------------------------------
  714. - (void)deleteFile:(tableMetadata *)metadata
  715. {
  716. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  717. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND e2eEncrypted == 1 AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  718. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:[[NSArray alloc] initWithObjects:metadata, nil] e2ee:tableDirectory.e2eEncrypted serverUrl:serverUrl folderFileID:tableDirectory.fileID completion:^(NSInteger errorCode, NSString *message) {
  719. if (errorCode == 0) {
  720. // reload data source
  721. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl fileID:metadata.fileID action:k_action_DEL];
  722. // Not image
  723. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_image] == NO) {
  724. // exit
  725. [self.navigationController popViewControllerAnimated:YES];
  726. } else {
  727. for (NSUInteger index=0; index < [self.photoDataSource count] && _photoBrowser; index++ ) {
  728. tableMetadata *metadataTemp = [self.photoDataSource objectAtIndex:index];
  729. if ([metadata isInvalidated] || [metadataTemp.fileID isEqualToString:metadata.fileID]) {
  730. [self.photoDataSource removeObjectAtIndex:index];
  731. [self.photos removeObjectAtIndex:index];
  732. [self.photoBrowser reloadData];
  733. // exit
  734. if ([self.photoDataSource count] == 0) {
  735. [self.navigationController popViewControllerAnimated:YES];
  736. }
  737. }
  738. }
  739. }
  740. } else {
  741. NSLog(@"[LOG] DeleteFileOrFolder failure error %d, %@", (int)errorCode, message);
  742. }
  743. }];
  744. }
  745. #pragma --------------------------------------------------------------------------------------------
  746. #pragma mark ===== ButtonPressed =====
  747. #pragma --------------------------------------------------------------------------------------------
  748. - (void)dismissTextView
  749. {
  750. if (self.webView) {
  751. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNameView];
  752. [[NSFileManager defaultManager] removeItemAtPath:fileNamePath error:nil];
  753. [[NSFileManager defaultManager] linkItemAtPath:[CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView] toPath:fileNamePath error:nil];
  754. [self.webView reload];
  755. }
  756. }
  757. - (void)modifyTxtButtonPressed:(UIBarButtonItem *)sender
  758. {
  759. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", self.metadataDetail.fileID]];
  760. if (metadata) {
  761. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  762. NCText *viewController = (NCText *)navigationController.topViewController;
  763. viewController.metadata = metadata;
  764. viewController.delegate = self;
  765. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  766. navigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  767. [self presentViewController:navigationController animated:YES completion:nil];
  768. }
  769. }
  770. - (void)actionButtonPressed:(UIBarButtonItem *)sender
  771. {
  772. if ([self.metadataDetail.fileNameView length] == 0) return;
  773. NSString *filePath = [CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView];
  774. docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  775. docController.delegate = self;
  776. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  777. [docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  778. [docController presentOptionsMenuFromBarButtonItem:sender animated:YES];
  779. }
  780. - (void)shareButtonPressed:(UIBarButtonItem *)sender
  781. {
  782. [appDelegate.activeMain openWindowShare:self.metadataDetail];
  783. }
  784. - (void)deleteButtonPressed:(UIBarButtonItem *)sender
  785. {
  786. if ([self.metadataDetail.fileNameView length] == 0) return;
  787. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  788. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  789. style:UIAlertActionStyleDestructive
  790. handler:^(UIAlertAction *action) {
  791. [self deleteFile:self.metadataDetail];
  792. }]];
  793. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  794. style:UIAlertActionStyleCancel
  795. handler:^(UIAlertAction *action) {
  796. [alertController dismissViewControllerAnimated:YES completion:nil];
  797. }]];
  798. alertController.popoverPresentationController.barButtonItem = buttonDelete;
  799. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  800. [alertController.view layoutIfNeeded];
  801. [self presentViewController:alertController animated:YES completion:NULL];
  802. }
  803. @end