CCDetail.m 42 KB

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