CCDetail.m 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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. #define TOOLBAR_HEIGHT 49.0f
  29. #define alertRequestPasswordPDF 1
  30. @interface CCDetail () <CCActionsDeleteDelegate>
  31. {
  32. AppDelegate *appDelegate;
  33. UIToolbar *_toolbar;
  34. UIBarButtonItem *_buttonModifyTxt;
  35. UIBarButtonItem *_buttonAction;
  36. UIBarButtonItem *_buttonShare;
  37. UIBarButtonItem *_buttonDelete;
  38. NSInteger _indexNowVisible;
  39. NSString *_fileIDNowVisible;
  40. NSMutableOrderedSet *_dataSourceDirectoryID;
  41. NSString *_fileNameExtension;
  42. CCHud *_hud;
  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. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backNavigationController) name:@"detailBack" object:nil];
  56. self.metadataDetail = [[tableMetadata alloc] init];
  57. self.photos = [[NSMutableArray alloc] init];
  58. self.dataSourceImagesVideos = [[NSMutableArray alloc] init];
  59. _dataSourceDirectoryID = [[NSMutableOrderedSet alloc] init];
  60. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  61. _indexNowVisible = -1;
  62. _fileIDNowVisible = nil;
  63. appDelegate.activeDetail = self;
  64. }
  65. return self;
  66. }
  67. #pragma --------------------------------------------------------------------------------------------
  68. #pragma mark ===== View =====
  69. #pragma --------------------------------------------------------------------------------------------
  70. - (void)viewDidLoad
  71. {
  72. [super viewDidLoad];
  73. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertGeocoderLocation:) name:@"insertGeocoderLocation" object:nil];
  74. self.imageBackground.image = [UIImage imageNamed:@"backgroundDetail"];
  75. // Change bar bottom line shadow
  76. self.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  77. if ([self.metadataDetail.fileNameView length] > 0 || [self.metadataDetail.directoryID length] > 0 || [self.metadataDetail.fileID length] > 0) {
  78. // open view
  79. [self viewFile];
  80. }
  81. }
  82. // Apparirà
  83. - (void)viewWillAppear:(BOOL)animated
  84. {
  85. [super viewWillAppear:animated];
  86. if (self.splitViewController.isCollapsed) {
  87. self.tabBarController.tabBar.hidden = YES;
  88. self.tabBarController.tabBar.translucent = YES;
  89. }
  90. if (self.splitViewController.isCollapsed)
  91. [appDelegate plusButtonVisibile:false];
  92. }
  93. // E' scomparso
  94. - (void)viewDidDisappear:(BOOL)animated
  95. {
  96. [super viewDidDisappear:animated];
  97. // remove all
  98. if (self.isMovingFromParentViewController)
  99. [self removeAllView];
  100. }
  101. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  102. {
  103. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  104. }];
  105. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  106. }
  107. // remove all view
  108. - (void)removeAllView
  109. {
  110. // Document
  111. if (_webView) {
  112. [_webView removeFromSuperview];
  113. _webView = nil;
  114. }
  115. // PDF
  116. if (_readerPDFViewController) {
  117. [_readerPDFViewController.view removeFromSuperview];
  118. _readerPDFViewController.delegate = nil;
  119. _readerPDFViewController = nil;
  120. }
  121. // Photo-Video-Audio
  122. if (_photoBrowser) {
  123. [_photos removeAllObjects];
  124. _photoBrowser.delegate = nil;
  125. _photoBrowser = nil;
  126. }
  127. // ToolBar
  128. if (_toolbar) {
  129. [_toolbar removeFromSuperview];
  130. _toolbar = nil;
  131. }
  132. // Title
  133. self.title = nil;
  134. }
  135. - (void)backNavigationController
  136. {
  137. [self removeAllView];
  138. [self.navigationController popViewControllerAnimated:NO];
  139. }
  140. - (void)changeToDisplayMode
  141. {
  142. if (_readerPDFViewController)
  143. [self.readerPDFViewController updateContentViews];
  144. }
  145. - (void)createToolbar
  146. {
  147. CGFloat safeAreaBottom = 0;
  148. if (@available(iOS 11, *)) {
  149. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  150. }
  151. _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom, self.view.bounds.size.width, TOOLBAR_HEIGHT)];
  152. UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
  153. UIBarButtonItem *fixedSpaceMini = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  154. fixedSpaceMini.width = 25;
  155. _buttonModifyTxt = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"actionSheetModify"] style:UIBarButtonItemStylePlain target:self action:@selector(modifyTxtButtonPressed:)];
  156. _buttonAction = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"openFile"] style:UIBarButtonItemStylePlain target:self action:@selector(actionButtonPressed:)];
  157. _buttonShare = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share"] style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonPressed:)];
  158. _buttonDelete = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteButtonPressed:)];
  159. if ([_fileNameExtension isEqualToString:@"TXT"]) {
  160. if ([CCUtility isFolderEncrypted:[[NCManageDatabase sharedInstance] getServerUrl:_metadataDetail.directoryID] account:appDelegate.activeAccount]) // E2EE
  161. [_toolbar setItems:[NSArray arrayWithObjects: _buttonModifyTxt, flexible, _buttonDelete, fixedSpaceMini, _buttonAction, nil]];
  162. else
  163. [_toolbar setItems:[NSArray arrayWithObjects: _buttonModifyTxt, flexible, _buttonDelete, fixedSpaceMini, _buttonShare, fixedSpaceMini, _buttonAction, nil]];
  164. } else {
  165. if ([CCUtility isFolderEncrypted:[[NCManageDatabase sharedInstance] getServerUrl:_metadataDetail.directoryID] account:appDelegate.activeAccount]) // E2EE
  166. [_toolbar setItems:[NSArray arrayWithObjects: flexible, _buttonDelete, fixedSpaceMini, _buttonAction, nil]];
  167. else
  168. [_toolbar setItems:[NSArray arrayWithObjects: flexible, _buttonDelete, fixedSpaceMini, _buttonShare, fixedSpaceMini, _buttonAction, nil]];
  169. }
  170. [_toolbar setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  171. _toolbar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  172. _toolbar.tintColor = [NCBrandColor sharedInstance].brandElement;
  173. [self.view addSubview:_toolbar];
  174. }
  175. - (void)changeTheming
  176. {
  177. [appDelegate changeTheming:self];
  178. if (_toolbar) {
  179. _toolbar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  180. _toolbar.tintColor = [NCBrandColor sharedInstance].brandElement;
  181. }
  182. }
  183. #pragma --------------------------------------------------------------------------------------------
  184. #pragma mark ===== View File =====
  185. #pragma --------------------------------------------------------------------------------------------
  186. - (void)viewFile
  187. {
  188. // verifico se esiste l'icona e se la posso creare
  189. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView]] == NO) {
  190. [CCGraphics createNewImageFrom:self.metadataDetail.fileNameView fileID:self.metadataDetail.fileID extension:[self.metadataDetail.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:self.metadataDetail.typeFile writeImage:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  191. }
  192. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_image] || [self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_audio]) {
  193. self.edgesForExtendedLayout = UIRectEdgeAll;
  194. [self viewImageVideoAudio];
  195. }
  196. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_document]) {
  197. _fileNameExtension = [[self.metadataDetail.fileNameView pathExtension] uppercaseString];
  198. if ([_fileNameExtension isEqualToString:@"PDF"]) {
  199. self.edgesForExtendedLayout = UIRectEdgeBottom;
  200. [self viewPDF:@""];
  201. [self createToolbar];
  202. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  203. } else {
  204. self.edgesForExtendedLayout = UIRectEdgeBottom;
  205. [self viewDocument];
  206. [self createToolbar];
  207. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  208. }
  209. }
  210. }
  211. #pragma --------------------------------------------------------------------------------------------
  212. #pragma mark ===== View Document =====
  213. #pragma --------------------------------------------------------------------------------------------
  214. - (void)viewDocument
  215. {
  216. CGFloat safeAreaBottom = 0;
  217. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView];
  218. if (@available(iOS 11, *)) {
  219. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  220. }
  221. if ([CCUtility fileProviderStorageExists:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView] == NO) {
  222. [self backNavigationController];
  223. return;
  224. }
  225. NSURL *url = [NSURL fileURLWithPath:fileNamePath];
  226. WKPreferences *wkPreferences = [[WKPreferences alloc] init];
  227. wkPreferences.javaScriptEnabled = true;
  228. WKWebViewConfiguration *wkConfig = [[WKWebViewConfiguration alloc] init];
  229. wkConfig.preferences = wkPreferences;
  230. self.webView = [[WKWebView alloc] initWithFrame:(CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom)) configuration:wkConfig];
  231. self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  232. [self.webView setBackgroundColor:[NCBrandColor sharedInstance].backgroundView];
  233. [self.webView setOpaque:NO];
  234. if ( [_fileNameExtension isEqualToString:@"CSS"] || [_fileNameExtension isEqualToString:@"PY"] || [_fileNameExtension isEqualToString:@"XML"] || [_fileNameExtension isEqualToString:@"JS"] ) {
  235. NSString *dataFile = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:url] encoding:NSASCIIStringEncoding];
  236. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  237. [self.webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-size:%@;font-family:%@;'><pre>%@",@"40",@"Sans-Serif",dataFile] baseURL:nil];
  238. }else{
  239. [self.webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-size:%@;font-family:%@;'><pre>%@",@"20",@"Sans-Serif",dataFile] baseURL:nil];
  240. }
  241. } else if ([_fileNameExtension isEqualToString:@"TXT"] || [_fileNameExtension isEqualToString:@"MD"]) {
  242. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  243. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
  244. NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
  245. [headRequest setHTTPMethod:@"HEAD"];
  246. NSURLSessionDataTask *task = [session dataTaskWithRequest:headRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  247. dispatch_async(dispatch_get_main_queue(), ^{
  248. NSString *encodingName = [[NCUchardet sharedNUCharDet] encodingStringDetectWithData:data];
  249. [self.webView loadData:[NSData dataWithContentsOfURL: url] MIMEType:response.MIMEType characterEncodingName:encodingName baseURL:url];
  250. });
  251. }];
  252. [task resume];
  253. } else {
  254. [self.webView loadRequest:[NSMutableURLRequest requestWithURL:url]];
  255. }
  256. [self.view addSubview:self.webView];
  257. }
  258. #pragma --------------------------------------------------------------------------------------------
  259. #pragma mark ===== View Image =====
  260. #pragma --------------------------------------------------------------------------------------------
  261. - (void)viewImageVideoAudio
  262. {
  263. self.photoBrowser = [[MWPhotoBrowser alloc] initWithDelegate:self];
  264. _indexNowVisible = -1;
  265. _fileIDNowVisible = nil;
  266. [self.photos removeAllObjects];
  267. [_dataSourceDirectoryID removeAllObjects];
  268. // if not images, exit
  269. if ([self.dataSourceImagesVideos count] == 0) return;
  270. NSUInteger index = 0;
  271. for (tableMetadata *metadata in self.dataSourceImagesVideos) {
  272. // start from here ?
  273. if (self.metadataDetail.fileID && [metadata.fileID isEqualToString:self.metadataDetail.fileID])
  274. [self.photoBrowser setCurrentPhotoIndex:index];
  275. [self.photos addObject:[MWPhoto photoWithImage:nil]];
  276. // add directory
  277. [_dataSourceDirectoryID addObject:metadata.directoryID];
  278. index++;
  279. }
  280. // PhotoBrowser
  281. self.photoBrowser.displayActionButton = YES;
  282. self.photoBrowser.displayDeleteButton = YES;
  283. if ([CCUtility isFolderEncrypted:[[NCManageDatabase sharedInstance] getServerUrl:_metadataDetail.directoryID] account:appDelegate.activeAccount]) // E2EE
  284. self.photoBrowser.displayShareButton = NO;
  285. else
  286. self.photoBrowser.displayShareButton = YES;
  287. self.photoBrowser.displayNavArrows = YES;
  288. self.photoBrowser.displaySelectionButtons = NO;
  289. self.photoBrowser.alwaysShowControls = NO;
  290. self.photoBrowser.zoomPhotosToFill = NO;
  291. self.photoBrowser.autoPlayOnAppear = NO;
  292. self.photoBrowser.delayToHideElements = 15;
  293. if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)
  294. self.photoBrowser.enableSwipeToDismiss = NO;
  295. if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
  296. [self addChildViewController:self.photoBrowser];
  297. [self.view addSubview:self.photoBrowser.view];
  298. [self.photoBrowser didMoveToParentViewController:self];
  299. } else {
  300. [self.navigationController pushViewController:self.photoBrowser animated:NO];
  301. }
  302. }
  303. - (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
  304. {
  305. return [self.dataSourceImagesVideos count];
  306. }
  307. - (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index
  308. {
  309. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  310. NSString *titleDir = metadata.fileNameView;
  311. self.title = titleDir;
  312. return titleDir;
  313. }
  314. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
  315. {
  316. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  317. _indexNowVisible = index;
  318. _fileIDNowVisible = metadata.fileID;
  319. photoBrowser.toolbar.hidden = NO;
  320. // Download image ?
  321. if (metadata) {
  322. tableMetadata *metadataDB = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  323. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView] == NO && metadataDB.status == k_metadataStatusNormal) {
  324. [self downloadPhotoBrowser:metadata];
  325. }
  326. }
  327. // Title
  328. if (metadata)
  329. self.title = metadata.fileNameView;
  330. }
  331. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
  332. {
  333. UIImage *image;
  334. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  335. if (index < self.photos.count) {
  336. if (metadata.fileID) {
  337. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  338. NSString *fileImage = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView];
  339. NSString *ext = [CCUtility getExtension:metadata.fileNameView];
  340. if ([ext isEqualToString:@"GIF"]) image = [UIImage animatedImageWithAnimatedGIFURL:[NSURL fileURLWithPath:fileImage]];
  341. else image = [UIImage imageWithContentsOfFile:fileImage];
  342. if (image) {
  343. MWPhoto *photo = [MWPhoto photoWithImage:image];
  344. // Location ??
  345. [self setLocationCaptionPhoto:photo fileID:metadata.fileID];
  346. [self.photos replaceObjectAtIndex:index withObject:photo];
  347. } else {
  348. if (metadata.status == k_metadataStatusDownloadError) {
  349. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  350. }
  351. }
  352. }
  353. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  354. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  355. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]];
  356. MWPhoto *video = [MWPhoto photoWithImage:[CCGraphics thumbnailImageForVideo:url atTime:1.0]];
  357. video.videoURL = url;
  358. [self.photos replaceObjectAtIndex:index withObject:video];
  359. } else {
  360. if (metadata.status == k_metadataStatusDownloadError) {
  361. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  362. }
  363. }
  364. }
  365. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) {
  366. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  367. MWPhoto *audio;
  368. UIImage *audioImage;
  369. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]];
  370. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]) {
  371. audioImage = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  372. } else {
  373. audioImage = [UIImage imageNamed:@"notaMusic"]; //[CCGraphics scaleImage:[UIImage imageNamed:@"notaMusic"] toSize:CGSizeMake(200, 200) isAspectRation:YES];
  374. }
  375. audio = [MWPhoto photoWithImage:audioImage];
  376. audio.videoURL = url;
  377. [self.photos replaceObjectAtIndex:index withObject:audio];
  378. } else {
  379. if (metadata.status == k_metadataStatusDownloadError) {
  380. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  381. }
  382. }
  383. }
  384. }
  385. // energy saving memory
  386. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  387. int iPrev = (int)index - 2;
  388. if (iPrev >= 0) {
  389. if ([self.photos objectAtIndex:iPrev] != nil)
  390. [self.photos replaceObjectAtIndex:iPrev withObject:[MWPhoto photoWithImage:nil]];
  391. }
  392. int iNext = (int)index + 2;
  393. if (iNext < _photos.count) {
  394. if ([self.photos objectAtIndex:iNext] != nil)
  395. [self.photos replaceObjectAtIndex:iNext withObject:[MWPhoto photoWithImage:nil]];
  396. }
  397. });
  398. return [self.photos objectAtIndex:index];
  399. }
  400. return nil;
  401. }
  402. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index
  403. {
  404. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  405. if (metadata == nil) return;
  406. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]]];
  407. self.docController.delegate = self;
  408. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  409. [self.docController presentOptionsMenuFromRect:photoBrowser.view.frame inView:photoBrowser.view animated:YES];
  410. [self.docController presentOptionsMenuFromBarButtonItem:photoBrowser.actionButton animated:YES];
  411. }
  412. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser shareButtonPressedForPhotoAtIndex:(NSUInteger)index
  413. {
  414. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  415. [appDelegate.activeMain openWindowShare:metadata];
  416. }
  417. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser deleteButtonPressedForPhotoAtIndex:(NSUInteger)index deleteButton:(UIBarButtonItem *)deleteButton
  418. {
  419. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  420. if (metadata == nil || [CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView] == NO) {
  421. [appDelegate messageNotification:@"_info_" description:@"_file_not_found_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  422. return;
  423. }
  424. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  425. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  426. style:UIAlertActionStyleDestructive
  427. handler:^(UIAlertAction *action) {
  428. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self hud:nil hudTitled:nil];
  429. }]];
  430. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  431. style:UIAlertActionStyleCancel
  432. handler:^(UIAlertAction *action) {
  433. [alertController dismissViewControllerAnimated:YES completion:nil];
  434. }]];
  435. alertController.popoverPresentationController.barButtonItem = deleteButton;
  436. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  437. [alertController.view layoutIfNeeded];
  438. [self.parentViewController presentViewController:alertController animated:YES completion:NULL];
  439. }
  440. - (void)photoBrowserDidFinishPresentation:(MWPhotoBrowser *)photoBrowser
  441. {
  442. [self removeAllView];
  443. [self.navigationController popViewControllerAnimated:YES];
  444. }
  445. - (void)triggerProgressTask:(NSNotification *)notification
  446. {
  447. NSDictionary *dict = notification.userInfo;
  448. NSString *fileID = [dict valueForKey:@"fileID"];
  449. //NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  450. float progress = [[dict valueForKey:@"progress"] floatValue];
  451. if ([fileID isEqualToString:_fileIDNowVisible])
  452. [_hud progress:progress];
  453. }
  454. - (void)downloadPhotoBrowserSuccessFailure:(tableMetadata *)metadata selector:(NSString *)selector errorCode:(NSInteger)errorCode
  455. {
  456. // if a message for a directory of these
  457. if (![metadata.fileID isEqualToString:_fileIDNowVisible])
  458. return;
  459. [_hud hideHud];
  460. if (errorCode == 0) {
  461. // verifico se esiste l'icona e se la posso creare
  462. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO)
  463. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writeImage:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  464. } else {
  465. [appDelegate messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  466. }
  467. [self.photoBrowser reloadData];
  468. }
  469. - (void)downloadPhotoBrowser:(tableMetadata *)metadata
  470. {
  471. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  472. if (serverUrl) {
  473. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeDeterminate color:[NCBrandColor sharedInstance].brandElement];
  474. metadata.session = k_download_session;
  475. metadata.sessionError = @"";
  476. metadata.sessionSelector = selectorLoadViewImage;
  477. metadata.sessionSelectorPost = @"";
  478. metadata.status = k_metadataStatusWaitDownload;
  479. // Add Metadata for Download
  480. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  481. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  482. }
  483. }
  484. - (void)insertGeocoderLocation:(NSNotification *)notification
  485. {
  486. if (notification.userInfo.count == 0)
  487. return;
  488. NSString *fileID = [[notification.userInfo allKeys] objectAtIndex:0];
  489. //NSDate *date = [[notification.userInfo allValues] objectAtIndex:0];
  490. // test [Chrash V 1.14,15]
  491. if (_indexNowVisible >= [self.photos count])
  492. return;
  493. if ([fileID isEqualToString:_fileIDNowVisible]) {
  494. MWPhoto *photo = [self.photos objectAtIndex:_indexNowVisible];
  495. [self setLocationCaptionPhoto:photo fileID:fileID];
  496. [self.photoBrowser reloadData];
  497. }
  498. }
  499. - (void)setLocationCaptionPhoto:(MWPhoto *)photo fileID:(NSString *)fileID
  500. {
  501. tableLocalFile *localFile;
  502. // read Geocoder
  503. localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  504. if ([localFile.exifLatitude doubleValue] != 0 || [localFile.exifLongitude doubleValue] != 0) {
  505. // Fix BUG Geo latitude & longitude
  506. if ([localFile.exifLatitude doubleValue] == 9999 || [localFile.exifLongitude doubleValue] == 9999) {
  507. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  508. if (metadata) {
  509. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  510. }
  511. }
  512. [[CCExifGeo sharedInstance] setGeocoderEtag:fileID exifDate:localFile.exifDate latitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  513. localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  514. if ([localFile.exifLatitude floatValue] != 0 || [localFile.exifLongitude floatValue] != 0) {
  515. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  516. if ([localFile.exifDate isEqualToDate:[NSDate distantPast]] == NO && location) {
  517. NSString *localizedDateTime = [NSDateFormatter localizedStringFromDate:localFile.exifDate dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterMediumStyle];
  518. photo.caption = [NSString stringWithFormat:NSLocalizedString(@"%@\n%@", nil), localizedDateTime, location];
  519. }
  520. }
  521. }
  522. }
  523. #pragma --------------------------------------------------------------------------------------------
  524. #pragma mark ===== View PDF =====
  525. #pragma --------------------------------------------------------------------------------------------
  526. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  527. {
  528. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  529. [[alertView textFieldAtIndex:0] resignFirstResponder];
  530. if (alertView.tag == alertRequestPasswordPDF) [self performSelector:@selector(viewPDF:) withObject:[alertView textFieldAtIndex:0].text afterDelay:0.3];
  531. }
  532. - (void)viewPDF:(NSString *)password
  533. {
  534. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView];
  535. if ([CCUtility fileProviderStorageExists:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView] == NO) {
  536. // read file error
  537. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  538. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  539. [alertController addAction:okAction];
  540. [self presentViewController:alertController animated:YES completion:nil];
  541. }
  542. CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:fileNamePath]);
  543. if (pdf) {
  544. // Encrypted
  545. if (CGPDFDocumentIsEncrypted(pdf) == YES) {
  546. // Try a blank password first, per Apple's Quartz PDF example
  547. if (CGPDFDocumentUnlockWithPassword(pdf, "") == YES) {
  548. // blank password
  549. [self readerPDF:fileNamePath password:@""];
  550. } else {
  551. if ([password length] == 0) {
  552. // password request
  553. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_insert_password_pfd_",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  554. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  555. alertView.tag = alertRequestPasswordPDF;
  556. [alertView show];
  557. } else {
  558. const char *key = [password UTF8String];
  559. // failure
  560. if (CGPDFDocumentUnlockWithPassword(pdf, key) == NO) {
  561. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_password_pdf_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  562. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  563. [alertController addAction:okAction];
  564. [self presentViewController:alertController animated:YES completion:nil];
  565. } else {
  566. // pdf with password
  567. [self readerPDF:fileNamePath password:password];
  568. }
  569. }
  570. }
  571. } else{
  572. // No password
  573. [self readerPDF:fileNamePath password:@""];
  574. }
  575. } else {
  576. // read file error
  577. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  578. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  579. [alertController addAction:okAction];
  580. [self presentViewController:alertController animated:YES completion:nil];
  581. }
  582. }
  583. - (void)readerPDF:(NSString *)fileName password:(NSString *)password
  584. {
  585. ReaderDocument *documentPDF = [ReaderDocument withDocumentFilePath:fileName password:password];
  586. CGFloat safeAreaBottom = 0;
  587. if (@available(iOS 11, *)) {
  588. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  589. }
  590. if (documentPDF != nil) {
  591. self.readerPDFViewController = [[ReaderViewController alloc] initWithReaderDocument:documentPDF];
  592. self.readerPDFViewController.delegate = self;
  593. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  594. [self.readerPDFViewController updateContentViews];
  595. [self addChildViewController:self.readerPDFViewController];
  596. [self.view addSubview:self.readerPDFViewController.view];
  597. [self.readerPDFViewController didMoveToParentViewController:self];
  598. } else {
  599. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  600. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  601. [alertController addAction:okAction];
  602. [self presentViewController:alertController animated:YES completion:nil];
  603. }
  604. }
  605. - (void)handleSingleTapReader
  606. {
  607. UILayoutGuide *layoutGuide;
  608. CGFloat safeAreaTop = 0;
  609. CGFloat safeAreaBottom = 0;
  610. if (@available(iOS 11, *)) {
  611. layoutGuide = [UIApplication sharedApplication].delegate.window.safeAreaLayoutGuide;
  612. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  613. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  614. }
  615. self.navigationController.navigationBarHidden = !self.navigationController.navigationBarHidden;
  616. _toolbar.hidden = !_toolbar.isHidden;
  617. if (_toolbar.isHidden) {
  618. self.readerPDFViewController.view.frame = CGRectMake(0, safeAreaTop, self.view.bounds.size.width, self.view.bounds.size.height - safeAreaTop - safeAreaBottom);
  619. } else {
  620. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  621. }
  622. [self.readerPDFViewController updateContentViews];
  623. }
  624. - (void)handleSwipeUpDown
  625. {
  626. // REMOVE IT'S UNUSABLE
  627. /*
  628. self.navigationController.navigationBarHidden = false; // iOS App is unusable after swipe up or down with PDF in fullscreen #526
  629. [self removeAllView];
  630. [self.navigationController popViewControllerAnimated:YES];
  631. */
  632. }
  633. #pragma --------------------------------------------------------------------------------------------
  634. #pragma mark ===== Delete =====
  635. #pragma --------------------------------------------------------------------------------------------
  636. - (void)deleteFileOrFolderSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  637. {
  638. if (errorCode == 0) {
  639. // reload Main
  640. [appDelegate.activeMain reloadDatasource];
  641. // If removed document (web) or PDF close
  642. if (_webView || _readerPDFViewController)
  643. [self removeAllView];
  644. // if a message for a directory of these
  645. if (![_dataSourceDirectoryID containsObject:metadataNet.directoryID])
  646. return;
  647. // if we are not in browserPhoto and it's removed photo/video in preview then "< Back"
  648. if (!self.photoBrowser && [self.metadataDetail.fileID isEqualToString:metadataNet.fileID]) {
  649. NSArray *viewsToRemove = [self.view subviews];
  650. for (id element in viewsToRemove) {
  651. if ([element isMemberOfClass:[UIView class]] || [element isMemberOfClass:[UIToolbar class]])
  652. [element removeFromSuperview];
  653. }
  654. self.title = @"";
  655. [self.navigationController popViewControllerAnimated:YES];
  656. } else {
  657. // only photoBrowser if exists
  658. for (NSUInteger index=0; index < [self.dataSourceImagesVideos count] && _photoBrowser; index++ ) {
  659. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  660. // ricerca index
  661. if ([metadata.fileID isEqualToString:metadataNet.fileID]) {
  662. [self.dataSourceImagesVideos removeObjectAtIndex:index];
  663. [self.photos removeObjectAtIndex:index];
  664. [self.photoBrowser reloadData];
  665. // Title
  666. if ([self.dataSourceImagesVideos count] == 0) {
  667. self.title = @"";
  668. [self.navigationController popViewControllerAnimated:YES];
  669. }
  670. break;
  671. }
  672. }
  673. }
  674. } else {
  675. NSLog(@"[LOG] DeleteFileOrFolder failure error %d, %@", (int)errorCode, message);
  676. }
  677. }
  678. #pragma --------------------------------------------------------------------------------------------
  679. #pragma mark ===== ButtonPressed =====
  680. #pragma --------------------------------------------------------------------------------------------
  681. - (void)modifyTxtButtonPressed:(UIBarButtonItem *)sender
  682. {
  683. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  684. NCText *viewController = (NCText *)navigationController.topViewController;
  685. viewController.metadata = self.metadataDetail;
  686. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  687. navigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  688. [self presentViewController:navigationController animated:YES completion:nil];
  689. }
  690. - (void)actionButtonPressed:(UIBarButtonItem *)sender
  691. {
  692. if ([self.metadataDetail.fileNameView length] == 0) return;
  693. NSString *filePath = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), self.metadataDetail.fileNameView];
  694. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  695. self.docController.delegate = self;
  696. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  697. [self.docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  698. [self.docController presentOptionsMenuFromBarButtonItem:sender animated:YES];
  699. }
  700. - (void)shareButtonPressed:(UIBarButtonItem *)sender
  701. {
  702. [appDelegate.activeMain openWindowShare:self.metadataDetail];
  703. }
  704. - (void)deleteButtonPressed:(UIBarButtonItem *)sender
  705. {
  706. if ([self.metadataDetail.fileNameView length] == 0) return;
  707. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  708. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  709. style:UIAlertActionStyleDestructive
  710. handler:^(UIAlertAction *action) {
  711. [[CCActions sharedInstance] deleteFileOrFolder:self.metadataDetail delegate:self hud:nil hudTitled:nil];
  712. }]];
  713. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  714. style:UIAlertActionStyleCancel
  715. handler:^(UIAlertAction *action) {
  716. [alertController dismissViewControllerAnimated:YES completion:nil];
  717. }]];
  718. alertController.popoverPresentationController.barButtonItem = _buttonDelete;
  719. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  720. [alertController.view layoutIfNeeded];
  721. [self presentViewController:alertController animated:YES completion:NULL];
  722. }
  723. @end