CCDetail.m 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. //
  2. // CCDetail.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 16/01/15.
  6. // Copyright (c) 2014 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 "Nextcloud-Swift.h"
  27. #define TOOLBAR_HEIGHT 49.0f
  28. #define alertRequestPasswordPDF 1
  29. @interface CCDetail () <CCActionsDelegate>
  30. {
  31. UIToolbar *_toolbar;
  32. UIBarButtonItem *_buttonAction;
  33. UIBarButtonItem *_buttonDelete;
  34. BOOL _reload;
  35. NSMutableOrderedSet *_dataSourceDirectoryID;
  36. }
  37. @end
  38. @implementation CCDetail
  39. #pragma --------------------------------------------------------------------------------------------
  40. #pragma mark ===== init =====
  41. #pragma --------------------------------------------------------------------------------------------
  42. - (id)initWithCoder:(NSCoder *)aDecoder
  43. {
  44. if (self = [super initWithCoder:aDecoder]) {
  45. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertGeocoderLocation:) name:@"insertGeocoderLocation" object:nil];
  46. self.metadataDetail = [[CCMetadata alloc] init];
  47. self.photos = [[NSMutableArray alloc] init];
  48. self.thumbs = [[NSMutableArray alloc] init];
  49. self.dataSourceImagesVideos = [[NSMutableArray alloc] init];
  50. _dataSourceDirectoryID = [[NSMutableOrderedSet alloc] init];
  51. self.indexNowVisible = 0;
  52. self.fileIDNowVisible = nil;
  53. app.activeDetail = self;
  54. }
  55. return self;
  56. }
  57. #pragma --------------------------------------------------------------------------------------------
  58. #pragma mark ===== View =====
  59. #pragma --------------------------------------------------------------------------------------------
  60. - (void)viewDidLoad
  61. {
  62. [super viewDidLoad];
  63. self.imageBackground.image = [UIImage imageNamed:image_brandSfondoiPad];
  64. if ([self.metadataDetail.fileName length] > 0 || [self.metadataDetail.directoryID length] > 0 || [self.metadataDetail.fileID length] > 0) {
  65. // open view
  66. [self viewFile];
  67. }
  68. }
  69. // Apparirà
  70. - (void)viewWillAppear:(BOOL)animated
  71. {
  72. [super viewWillAppear:animated];
  73. if (self.splitViewController.isCollapsed) {
  74. self.tabBarController.tabBar.hidden = YES;
  75. self.tabBarController.tabBar.translucent = YES;
  76. }
  77. if (self.splitViewController.isCollapsed)
  78. [app plusButtonVisibile:false];
  79. }
  80. - (void)viewDidAppear:(BOOL)animated
  81. {
  82. [super viewDidAppear:animated];
  83. }
  84. // E' scomparso
  85. - (void)viewDidDisappear:(BOOL)animated
  86. {
  87. [super viewDidDisappear:animated];
  88. // remove all
  89. if (self.isMovingFromParentViewController)
  90. [self removeAllView];
  91. [self.navigationController cancelCCProgress];
  92. }
  93. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  94. {
  95. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  96. }];
  97. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  98. }
  99. // remove all view
  100. - (void)removeAllView
  101. {
  102. // Audio
  103. if (app.player)
  104. [app.player removeFromSuperview];
  105. // Document
  106. if (_webView) {
  107. [_webView removeFromSuperview];
  108. _webView.delegate = nil;
  109. _webView = nil;
  110. }
  111. // PDF
  112. if (_readerPDFViewController) {
  113. [_readerPDFViewController.view removeFromSuperview];
  114. _readerPDFViewController.delegate = nil;
  115. _readerPDFViewController = nil;
  116. }
  117. // Photo-Video
  118. if (_photoBrowser) {
  119. [_photos removeAllObjects];
  120. [_thumbs removeAllObjects];
  121. _photoBrowser.delegate = nil;
  122. _photoBrowser = nil;
  123. }
  124. [self.navigationController popToRootViewControllerAnimated:NO];
  125. }
  126. - (void)changeToDisplayMode
  127. {
  128. if (_readerPDFViewController)
  129. [self.readerPDFViewController updateContentViews];
  130. }
  131. - (void)createToolbar
  132. {
  133. _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - TOOLBAR_HEIGHT, self.view.bounds.size.width, TOOLBAR_HEIGHT)];
  134. UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
  135. UIBarButtonItem *fixedSpaceMini = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  136. fixedSpaceMini.width = 25;
  137. _buttonAction = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_actionSheetOpenIn] style:UIBarButtonItemStylePlain target:self action:@selector(actionButtonPressed:)];
  138. _buttonDelete = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteButtonPressed:)];
  139. [_toolbar setItems:[NSArray arrayWithObjects: flexible, _buttonDelete, fixedSpaceMini, _buttonAction, nil]];
  140. [_toolbar setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  141. [self.view addSubview:_toolbar];
  142. }
  143. #pragma --------------------------------------------------------------------------------------------
  144. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  145. #pragma --------------------------------------------------------------------------------------------
  146. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  147. {
  148. // evitiamo il rimando della eventuale photo e/o video
  149. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  150. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  151. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  152. }
  153. }
  154. #pragma --------------------------------------------------------------------------------------------
  155. #pragma mark ===== View File =====
  156. #pragma --------------------------------------------------------------------------------------------
  157. - (void)viewFile
  158. {
  159. // verifico se esiste l'icona e se la posso creare
  160. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, self.metadataDetail.fileID]] == NO) {
  161. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
  162. [CCGraphics createNewImageFrom:self.metadataDetail.fileID directoryUser:app.directoryUser fileNameTo:self.metadataDetail.fileID fileNamePrint:self.metadataDetail.fileNamePrint size:@"m" imageForUpload:NO typeFile:self.metadataDetail.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  163. });
  164. }
  165. if ([self.metadataDetail.typeFile isEqualToString:metadataTypeFile_image] || [self.metadataDetail.typeFile isEqualToString:metadataTypeFile_video]) {
  166. self.edgesForExtendedLayout = UIRectEdgeAll;
  167. [self viewImage];
  168. }
  169. if ([self.metadataDetail.typeFile isEqualToString:metadataTypeFile_audio]) {
  170. self.edgesForExtendedLayout = UIRectEdgeBottom;
  171. [self viewAudio];
  172. [self createToolbar];
  173. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar hidden:NO];
  174. }
  175. if ([self.metadataDetail.typeFile isEqualToString:metadataTypeFile_document]) {
  176. NSString *ext = [[self.metadataDetail.fileNamePrint pathExtension] lowercaseString];
  177. if ([ext isEqualToString:@"pdf"]) {
  178. self.edgesForExtendedLayout = UIRectEdgeBottom;
  179. [self viewPDF:@""];
  180. [self createToolbar];
  181. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar hidden:NO];
  182. } else {
  183. self.edgesForExtendedLayout = UIRectEdgeBottom;
  184. [self viewDocument];
  185. [self createToolbar];
  186. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar hidden:NO];
  187. }
  188. }
  189. }
  190. #pragma --------------------------------------------------------------------------------------------
  191. #pragma mark ===== View Audio =====
  192. #pragma --------------------------------------------------------------------------------------------
  193. - (void)viewAudio
  194. {
  195. NSString *fileName;
  196. if (_sourceDirectoryLocal) {
  197. fileName = [NSString stringWithFormat:@"%@/%@", self.metadataDetail.directoryID, self.metadataDetail.fileNamePrint];
  198. } else {
  199. fileName = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryAudio], self.metadataDetail.fileNamePrint];
  200. [[NSFileManager defaultManager] removeItemAtPath:fileName error:nil];
  201. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, self.metadataDetail.fileID] toPath:fileName error:nil];
  202. }
  203. app.player.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT);
  204. app.player.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  205. app.player.nextButton.hidden = true;
  206. app.player.previousButton.hidden = true;
  207. app.player.fullscreenButton_.hidden = true;
  208. LMMediaItem *item = [[LMMediaItem alloc] initWithInfo:@{LMMediaItemInfoURLKey:[NSURL fileURLWithPath:fileName], LMMediaItemInfoContentTypeKey:@(LMMediaItemContentTypeVideo)}];
  209. item.title = self.metadataDetail.fileNamePrint;
  210. item.artist = _brand_;
  211. [app.player.mediaPlayer removeAllMediaInQueue];
  212. [app.player.mediaPlayer addMedia:item];
  213. [app.player.mediaPlayer play];
  214. // Info
  215. NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
  216. [songInfo setObject:app.player.mediaPlayer.nowPlayingItem.title forKey:MPMediaItemPropertyTitle];
  217. [songInfo setObject:app.player.mediaPlayer.nowPlayingItem.artist forKey:MPMediaItemPropertyArtist];
  218. [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
  219. [self.view addSubview:app.player];
  220. }
  221. #pragma --------------------------------------------------------------------------------------------
  222. #pragma mark ===== View Document =====
  223. #pragma --------------------------------------------------------------------------------------------
  224. - (void)viewDocument
  225. {
  226. NSString *fileName;
  227. if (_sourceDirectoryLocal) {
  228. fileName = [NSString stringWithFormat:@"%@/%@", self.metadataDetail.directoryID, self.metadataDetail.fileNamePrint];
  229. } else {
  230. fileName = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNamePrint];
  231. [[NSFileManager defaultManager] removeItemAtPath:fileName error:nil];
  232. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, self.metadataDetail.fileID] toPath:fileName error:nil];
  233. }
  234. NSString *ext=@"";
  235. ext = [CCUtility getExtension:self.metadataDetail.fileNamePrint];
  236. self.webView = [[UIWebView alloc] initWithFrame:(CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT))];
  237. self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  238. [self.webView setBackgroundColor:[UIColor whiteColor]];
  239. [self.webView setOpaque:NO];
  240. if ( [ext isEqualToString:@"CSS"] || [ext isEqualToString:@"PY"] || [ext isEqualToString:@"XML"] || [ext isEqualToString:@"JS"] ) {
  241. NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:[NSURL fileURLWithPath:fileName]];
  242. [headRequest setHTTPMethod:@"HEAD"];
  243. NSHTTPURLResponse *headResponse;
  244. NSError *error = nil;
  245. [NSURLConnection sendSynchronousRequest:headRequest returningResponse:&headResponse error:&error];
  246. if (error != nil) {
  247. NSLog(@"[LOG] loadURLWithString %@",[error localizedDescription]);
  248. }
  249. NSString *dataFile = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL fileURLWithPath:fileName]] 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 ([ext isEqualToString:@"TXT"] ) {
  256. NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:[NSURL fileURLWithPath:fileName]];
  257. [headRequest setHTTPMethod:@"HEAD"];
  258. NSHTTPURLResponse *headResponse;
  259. NSError *error = nil;
  260. [NSURLConnection sendSynchronousRequest:headRequest returningResponse:&headResponse error:&error];
  261. if (error != nil) {
  262. NSLog(@"[LOG] loadURLWithString %@",[error localizedDescription]);
  263. }
  264. NSString *mimeType = [headResponse MIMEType];
  265. [self.webView loadData:[NSData dataWithContentsOfURL: [NSURL fileURLWithPath:fileName]] MIMEType:mimeType textEncodingName:@"utf-8" baseURL:[NSURL URLWithString:@""]];
  266. } else {
  267. [self.webView loadRequest:[NSMutableURLRequest requestWithURL:[NSURL fileURLWithPath:fileName]]];
  268. }
  269. [self.webView setScalesPageToFit:YES];
  270. [self.view addSubview:self.webView];
  271. }
  272. #pragma --------------------------------------------------------------------------------------------
  273. #pragma mark ===== View Image =====
  274. #pragma --------------------------------------------------------------------------------------------
  275. - (void)viewImage
  276. {
  277. self.photoBrowser = [[MWPhotoBrowser alloc] initWithDelegate:self];
  278. _reload = NO;
  279. [self.photos removeAllObjects];
  280. [self.thumbs removeAllObjects];
  281. [_dataSourceDirectoryID removeAllObjects];
  282. // if not images, exit
  283. if ([self.dataSourceImagesVideos count] == 0) return;
  284. NSUInteger index = 0;
  285. for (CCMetadata *metadata in self.dataSourceImagesVideos) {
  286. // start from here ?
  287. if (self.metadataDetail.fileID && [metadata.fileID isEqualToString:self.metadataDetail.fileID])
  288. [self.photoBrowser setCurrentPhotoIndex:index];
  289. if (metadata.cryptated) {
  290. [self.photos addObject:[MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewDownloadCrypto]]];
  291. [self.thumbs addObject:[MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewDownloadCrypto]]];
  292. } else {
  293. [self.photos addObject:[MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewDownload]]];
  294. MWPhoto *thumb = [MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewDownload]];
  295. if ([metadata.typeFile isEqualToString:metadataTypeFile_video]) thumb.isVideo = YES;
  296. [self.thumbs addObject:thumb];
  297. }
  298. // add directory
  299. [_dataSourceDirectoryID addObject:metadata.directoryID];
  300. index++;
  301. }
  302. // PhotoBrowser
  303. self.photoBrowser.displayActionButton = YES;
  304. self.photoBrowser.displayDeleteButton = YES;
  305. self.photoBrowser.displayNavArrows = YES;
  306. self.photoBrowser.displaySelectionButtons = NO;
  307. self.photoBrowser.alwaysShowControls = NO;
  308. self.photoBrowser.zoomPhotosToFill = NO;
  309. self.photoBrowser.startOnGrid = NO;
  310. self.photoBrowser.autoPlayOnAppear = NO;
  311. self.photoBrowser.delayToHideElements = 15;
  312. self.photoBrowser.enableGrid = YES;
  313. if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
  314. [self addChildViewController:self.photoBrowser];
  315. [self.view addSubview:self.photoBrowser.view];
  316. [self.photoBrowser didMoveToParentViewController:self];
  317. } else {
  318. [self.navigationController pushViewController:self.photoBrowser animated:NO];
  319. }
  320. }
  321. - (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
  322. {
  323. return [self.dataSourceImagesVideos count];
  324. }
  325. - (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index
  326. {
  327. NSString *titleDir = [NSString stringWithFormat:@"%lu %@ %lu", (unsigned long)index+1, NSLocalizedString(@"of", nil), (unsigned long)self.photos.count];
  328. self.title = titleDir;
  329. return titleDir;
  330. }
  331. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
  332. {
  333. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  334. NSString *directory;
  335. self.indexNowVisible = index;
  336. self.fileIDNowVisible = metadata.fileID;
  337. photoBrowser.toolbar.hidden = NO;
  338. if (_reload) {
  339. [self.photoBrowser performSelector:@selector(reloadData) withObject:nil afterDelay:0.1];
  340. _reload = NO;
  341. }
  342. if (_sourceDirectoryLocal)
  343. directory = self.metadataDetail.directoryID;
  344. else
  345. directory = app.directoryUser;
  346. // Download
  347. if (metadata && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directory, metadata.fileID]] == NO && [metadata.session length] == 0)
  348. [self performSelector:@selector(downloadPhotoBrowser:) withObject:metadata afterDelay:0.1];
  349. }
  350. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
  351. {
  352. NSString *directory;
  353. UIImage *image;
  354. if (_sourceDirectoryLocal)
  355. directory = self.metadataDetail.directoryID;
  356. else
  357. directory = app.directoryUser;
  358. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  359. //NSLog(@"[LOG] photoBrowser: photoAtIndex : %lu ---- di totali photo : %lu", (unsigned long)index, (unsigned long)_photos.count);
  360. if (index < self.photos.count) {
  361. if (metadata.fileID) {
  362. if ([metadata.typeFile isEqualToString:metadataTypeFile_image]) {
  363. NSString *fileImage = [NSString stringWithFormat:@"%@/%@", directory, metadata.fileID];
  364. NSString *ext = [CCUtility getExtension:metadata.fileNamePrint];
  365. if ([ext isEqualToString:@"GIF"]) image = [UIImage animatedImageWithAnimatedGIFURL:[NSURL fileURLWithPath:fileImage]];
  366. else image = [UIImage imageWithContentsOfFile:fileImage];
  367. if (image) {
  368. MWPhoto *photo = [MWPhoto photoWithImage:image];
  369. // Location ??
  370. [self setLocationCaptionPhoto:photo fileID:metadata.fileID];
  371. if (!photo.caption)
  372. photo.caption = metadata.fileNamePrint;
  373. [self.photos replaceObjectAtIndex:index withObject:photo];
  374. } else {
  375. if ([metadata.sessionError length] > 0 ) {
  376. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewError]]];
  377. } else {
  378. NSURL *url = [[NSBundle mainBundle] URLForResource:@"loading" withExtension:@"gif"];
  379. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage animatedImageWithAnimatedGIFURL:url]]];
  380. }
  381. }
  382. }
  383. if ([metadata.typeFile isEqualToString:metadataTypeFile_video]) {
  384. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directory, metadata.fileID]]) {
  385. // remove and make the simbolic link in temp
  386. NSString *toPath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint];
  387. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  388. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", directory, metadata.fileID] toPath:toPath error:nil];
  389. NSURL *url = [NSURL fileURLWithPath:toPath];
  390. MWPhoto *video = [MWPhoto photoWithImage:[CCGraphics thumbnailImageForVideo:url atTime:1.0]];
  391. video.caption = metadata.fileNamePrint;
  392. video.videoURL = url;
  393. [self.photos replaceObjectAtIndex:index withObject:video];
  394. } else {
  395. if ([metadata.sessionError length] > 0 ) {
  396. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewError]]];
  397. } else {
  398. NSURL *url = [[NSBundle mainBundle] URLForResource:@"loading" withExtension:@"gif"];
  399. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage animatedImageWithAnimatedGIFURL:url]]];
  400. }
  401. }
  402. }
  403. }
  404. // energy saving memory
  405. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  406. int iPrev = (int)index - 2;
  407. if (iPrev >= 0) {
  408. if ([self.photos objectAtIndex:iPrev] != nil)
  409. [self.photos replaceObjectAtIndex:iPrev withObject:[MWPhoto photoWithImage:nil]];
  410. }
  411. int iNext = (int)index + 2;
  412. if (iNext < _photos.count) {
  413. if ([self.photos objectAtIndex:iNext] != nil)
  414. [self.photos replaceObjectAtIndex:iNext withObject:[MWPhoto photoWithImage:nil]];
  415. }
  416. });
  417. return [self.photos objectAtIndex:index];
  418. }
  419. return nil;
  420. }
  421. - (void)gridWillAppear:(MWPhotoBrowser *)photoBrowser
  422. {
  423. // reload [BUG]
  424. [self.photoBrowser reloadData];
  425. // in grid clear all MWPhoto : energy saving memory
  426. if (self.photos.count > 1 && [self.dataSourceImagesVideos count] > 0) {
  427. for(int index=0; index < self.photos.count; index++)
  428. [_photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:nil]];
  429. }
  430. self.title = [NSString stringWithFormat:@"Album %lu %@", (unsigned long)_photos.count, NSLocalizedString(@"photos", nil)];
  431. }
  432. - (void)gridWillDisappear:(MWPhotoBrowser *)photoBrowser
  433. {
  434. //
  435. photoBrowser.toolbar.hidden = NO;
  436. }
  437. - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated permanent:(BOOL)permanent
  438. {
  439. // Control Center
  440. if (self.splitViewController.isCollapsed)
  441. [app.controlCenter setControlCenterHidden:hidden];
  442. self.navigationController.navigationBar.hidden = hidden;
  443. }
  444. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index
  445. {
  446. NSString *directory;
  447. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  448. if (_sourceDirectoryLocal)
  449. directory = self.metadataDetail.directoryID;
  450. else
  451. directory = app.directoryUser;
  452. if (index < self.thumbs.count) {
  453. if (metadata.fileID) {
  454. UIImage *image;
  455. if (_sourceDirectoryLocal) {
  456. image = [CCGraphics createNewImageFrom:metadata.fileID directoryUser:directory fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:NO optimizedFileName:[CCUtility getOptimizedPhoto]];
  457. } else {
  458. NSString *fileImage = [NSString stringWithFormat:@"%@/%@.ico", directory, metadata.fileID];
  459. image = [UIImage animatedImageWithAnimatedGIFURL:[NSURL fileURLWithPath:fileImage]];
  460. }
  461. if (image) {
  462. MWPhoto *thumb = [MWPhoto photoWithImage:image];
  463. if ([metadata.typeFile isEqualToString:metadataTypeFile_video]) thumb.isVideo = YES;
  464. [self.thumbs replaceObjectAtIndex:index withObject:thumb];
  465. }
  466. }
  467. return [self.thumbs objectAtIndex:index];
  468. }
  469. return nil;
  470. }
  471. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index
  472. {
  473. NSString *filePath;
  474. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  475. if (metadata == nil) return;
  476. if (_sourceDirectoryLocal) {
  477. filePath = [NSString stringWithFormat:@"%@/%@", self.metadataDetail.directoryID, self.metadataDetail.fileNamePrint];
  478. } else {
  479. filePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  480. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  481. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:filePath error:nil];
  482. }
  483. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  484. self.docController.delegate = self;
  485. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) [self.docController presentOptionsMenuFromRect:photoBrowser.view.frame inView:photoBrowser.view animated:YES];
  486. [self.docController presentOptionsMenuFromBarButtonItem:photoBrowser.actionButton animated:YES];
  487. }
  488. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser deleteButtonPressedForPhotoAtIndex:(NSUInteger)index deleteButton:(UIBarButtonItem *)deleteButton
  489. {
  490. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  491. if (metadata == nil || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]] == NO) return;
  492. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  493. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  494. style:UIAlertActionStyleDestructive
  495. handler:^(UIAlertAction *action) {
  496. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  497. }]];
  498. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  499. style:UIAlertActionStyleCancel
  500. handler:^(UIAlertAction *action) {
  501. [alertController dismissViewControllerAnimated:YES completion:nil];
  502. }]];
  503. alertController.popoverPresentationController.barButtonItem = deleteButton;
  504. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  505. [alertController.view layoutIfNeeded];
  506. [self.parentViewController presentViewController:alertController animated:YES completion:NULL];
  507. }
  508. - (void)progressTask:(NSString *)fileID serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated progress:(float)progress
  509. {
  510. if (progress == 0)
  511. [self.navigationController cancelCCProgress];
  512. else
  513. [self.navigationController setCCProgressPercentage:progress*100 andTintColor:COLOR_BRAND];
  514. }
  515. - (void)downloadPhotoBrowserFailure:(NSInteger)errorCode
  516. {
  517. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  518. [self.photoBrowser reloadData];
  519. [self.navigationController cancelCCProgress];
  520. }
  521. - (void)downloadPhotoBrowserSuccess:(CCMetadata *)metadataVar selector:(NSString *)selector
  522. {
  523. NSUInteger index = 0;
  524. // if a message for a directory of these
  525. if (![_dataSourceDirectoryID containsObject:metadataVar.directoryID])
  526. return;
  527. for (NSUInteger i=0; i < [self.dataSourceImagesVideos count]; i++ ) {
  528. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:i];
  529. // search index
  530. if ([metadataVar.fileID isEqualToString:metadata.fileID]) {
  531. index = i;
  532. break;
  533. }
  534. }
  535. // do not reload is Video on air
  536. if (_photoBrowser.currentVideoPlayerViewController.isViewLoaded && _photoBrowser.currentVideoPlayerViewController.view.window) return;
  537. //NSLog(@"[LOG] Add Download Photo Browser");
  538. if ([metadataVar.fileID isEqualToString:self.fileIDNowVisible] || [self.photoBrowser isGridReload:index]) {
  539. [self.photoBrowser reloadData];
  540. _reload = NO;
  541. } else {
  542. _reload = YES;
  543. }
  544. [self.navigationController cancelCCProgress];
  545. }
  546. - (void)downloadPhotoBrowser:(CCMetadata *)metadata
  547. {
  548. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  549. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadViewImage selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:nil];
  550. }
  551. - (void)insertGeocoderLocation:(NSNotification *)notification
  552. {
  553. NSString *fileID = [[notification.userInfo allKeys] objectAtIndex:0];
  554. //NSDate *date = [[notification.userInfo allValues] objectAtIndex:0];
  555. // test [Chrash V 1.14,15]
  556. if (self.indexNowVisible >= [self.photos count])
  557. return;
  558. dispatch_async(dispatch_get_main_queue(), ^{
  559. if ([fileID isEqualToString:self.fileIDNowVisible]) {
  560. MWPhoto *photo = [self.photos objectAtIndex:self.indexNowVisible];
  561. [self setLocationCaptionPhoto:photo fileID:fileID];
  562. if (![self.photoBrowser isGridController]) {
  563. [self.photoBrowser hideControls];
  564. [self.photoBrowser showControls];
  565. }
  566. }
  567. });
  568. }
  569. - (void)setLocationCaptionPhoto:(MWPhoto *)photo fileID:(NSString *)fileID
  570. {
  571. TableLocalFile *localFile;
  572. // read Geocoder
  573. localFile = [CCCoreData getLocalFileWithFileID:fileID activeAccount:app.activeAccount];
  574. if ([localFile.exifLatitude doubleValue] != 0 || [localFile.exifLongitude doubleValue] != 0) {
  575. // Fix BUG Geo latitude & longitude
  576. if ([localFile.exifLatitude doubleValue] == 9999 || [localFile.exifLongitude doubleValue] == 9999) {
  577. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  578. [CCExifGeo setExifLocalTableFileID:metadata directoryUser:app.directoryUser activeAccount:app.activeAccount];
  579. }
  580. [CCExifGeo setGeocoderFileID:fileID exifDate:localFile.exifDate latitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  581. localFile = [CCCoreData getLocalFileWithFileID:fileID activeAccount:app.activeAccount];
  582. if ([localFile.exifLatitude floatValue] != 0 || [localFile.exifLongitude floatValue] != 0) {
  583. NSString *location = [CCCoreData getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  584. if ([localFile.exifDate isEqualToDate:[NSDate distantPast]] == NO && location) {
  585. NSString *localizedDateTime = [NSDateFormatter localizedStringFromDate:localFile.exifDate dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterMediumStyle];
  586. photo.caption = [NSString stringWithFormat:NSLocalizedString(@"%@\n%@", nil), localizedDateTime, location];
  587. }
  588. }
  589. }
  590. }
  591. #pragma --------------------------------------------------------------------------------------------
  592. #pragma mark ===== View PDF =====
  593. #pragma --------------------------------------------------------------------------------------------
  594. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  595. {
  596. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  597. [[alertView textFieldAtIndex:0] resignFirstResponder];
  598. if (alertView.tag == alertRequestPasswordPDF) [self performSelector:@selector(viewPDF:) withObject:[alertView textFieldAtIndex:0].text afterDelay:0.3];
  599. }
  600. - (void)viewPDF:(NSString *)password
  601. {
  602. NSString *fileName;
  603. if (_sourceDirectoryLocal) {
  604. fileName = [NSString stringWithFormat:@"%@/%@", self.metadataDetail.directoryID, self.metadataDetail.fileNamePrint];
  605. } else {
  606. fileName = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNamePrint];
  607. [[NSFileManager defaultManager] removeItemAtPath:fileName error:nil];
  608. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, self.metadataDetail.fileID] toPath:fileName error:nil];
  609. }
  610. if ([[NSFileManager defaultManager] fileExistsAtPath:fileName isDirectory:nil] == NO) {
  611. // read file error
  612. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  613. [alertView show];
  614. }
  615. CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:fileName]);
  616. if (pdf) {
  617. // Encrypted
  618. if (CGPDFDocumentIsEncrypted(pdf) == YES) {
  619. // Try a blank password first, per Apple's Quartz PDF example
  620. if (CGPDFDocumentUnlockWithPassword(pdf, "") == YES) {
  621. // blank password
  622. [self readerPDF:fileName password:@""];
  623. } else {
  624. if ([password length] == 0) {
  625. // password request
  626. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_insert_password_pfd_",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  627. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  628. alertView.tag = alertRequestPasswordPDF;
  629. [alertView show];
  630. } else {
  631. const char *key = [password UTF8String];
  632. // failure
  633. if (CGPDFDocumentUnlockWithPassword(pdf, key) == NO) {
  634. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_password_pdf_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  635. [alertView show];
  636. } else {
  637. // pdf with password
  638. [self readerPDF:fileName password:password];
  639. }
  640. }
  641. }
  642. } else{
  643. // No password
  644. [self readerPDF:fileName password:@""];
  645. }
  646. } else {
  647. // read file error
  648. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  649. [alertView show];
  650. }
  651. }
  652. - (void)readerPDF:(NSString *)fileName password:(NSString *)password
  653. {
  654. ReaderDocument *documentPDF = [ReaderDocument withDocumentFilePath:fileName password:password];
  655. if (documentPDF != nil) {
  656. self.readerPDFViewController = [[ReaderViewController alloc] initWithReaderDocument:documentPDF];
  657. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT);
  658. [self.readerPDFViewController updateContentViews];
  659. [self addChildViewController:self.readerPDFViewController];
  660. [self.view addSubview:self.readerPDFViewController.view];
  661. [self.readerPDFViewController didMoveToParentViewController:self];
  662. } else {
  663. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  664. [alertView show];
  665. }
  666. }
  667. #pragma --------------------------------------------------------------------------------------------
  668. #pragma mark ===== Delete =====
  669. #pragma --------------------------------------------------------------------------------------------
  670. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  671. {
  672. NSLog(@"[LOG] delete failure");
  673. }
  674. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  675. {
  676. // if a message for a directory of these
  677. if (![_dataSourceDirectoryID containsObject:metadataNet.metadata.directoryID])
  678. return;
  679. // if we are not in browserPhoto and it's removed photo/video in preview then "< Back"
  680. if (!self.photoBrowser && [self.metadataDetail.fileID isEqualToString:metadataNet.metadata.fileID]) {
  681. if ([metadataNet.metadata.typeFile isEqualToString:metadataTypeFile_audio])
  682. [app.player.mediaPlayer stop];
  683. NSArray *viewsToRemove = [self.view subviews];
  684. for (id element in viewsToRemove) {
  685. if ([element isMemberOfClass:[UIView class]] || [element isMemberOfClass:[UIToolbar class]] || [element isMemberOfClass:[LMMediaPlayerView class]])
  686. [element removeFromSuperview];
  687. }
  688. self.title = @"";
  689. [self.navigationController popViewControllerAnimated:YES];
  690. } else {
  691. // only photoBrowser if exists
  692. for (NSUInteger index=0; index < [self.dataSourceImagesVideos count] && _photoBrowser; index++ ) {
  693. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  694. // ricerca index
  695. if ([metadataNet.metadata.fileID isEqualToString:metadata.fileID]) {
  696. [self.dataSourceImagesVideos removeObjectAtIndex:index];
  697. [self.photos removeObjectAtIndex:index];
  698. [self.thumbs removeObjectAtIndex:index];
  699. [self.photoBrowser reloadData];
  700. if ([self.dataSourceImagesVideos count] == 1) {
  701. self.title = [NSString stringWithFormat:@"1 %@ 1", NSLocalizedString(@"of", nil)];
  702. }
  703. if ([self.dataSourceImagesVideos count] == 0) {
  704. self.title = @"";
  705. [self.navigationController popViewControllerAnimated:YES];
  706. }
  707. break;
  708. }
  709. }
  710. }
  711. }
  712. #pragma --------------------------------------------------------------------------------------------
  713. #pragma mark ===== ButtonPressed =====
  714. #pragma --------------------------------------------------------------------------------------------
  715. - (void)actionButtonPressed:(UIBarButtonItem *)sender
  716. {
  717. NSString *filePath;
  718. if ([self.metadataDetail.fileNamePrint length] == 0) return;
  719. if (_sourceDirectoryLocal) {
  720. filePath = [NSString stringWithFormat:@"%@/%@", self.metadataDetail.directoryID, self.metadataDetail.fileNamePrint];
  721. } else {
  722. filePath = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), self.metadataDetail.fileNamePrint];
  723. }
  724. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  725. self.docController.delegate = self;
  726. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) [self.docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  727. [self.docController presentOptionsMenuFromBarButtonItem:sender animated:YES];
  728. }
  729. - (void)deleteButtonPressed:(UIBarButtonItem *)sender
  730. {
  731. if ([self.metadataDetail.fileNamePrint length] == 0) return;
  732. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  733. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  734. style:UIAlertActionStyleDestructive
  735. handler:^(UIAlertAction *action) {
  736. [[CCActions sharedInstance] deleteFileOrFolder:self.metadataDetail delegate:self];
  737. }]];
  738. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  739. style:UIAlertActionStyleCancel
  740. handler:^(UIAlertAction *action) {
  741. [alertController dismissViewControllerAnimated:YES completion:nil];
  742. }]];
  743. alertController.popoverPresentationController.barButtonItem = _buttonDelete;
  744. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  745. [alertController.view layoutIfNeeded];
  746. [self presentViewController:alertController animated:YES completion:NULL];
  747. }
  748. @end