CCDetail.m 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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) {
  492. [app messageNotification:@"_info_" description:@"_file_not_found_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  493. return;
  494. }
  495. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  496. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  497. style:UIAlertActionStyleDestructive
  498. handler:^(UIAlertAction *action) {
  499. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  500. }]];
  501. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  502. style:UIAlertActionStyleCancel
  503. handler:^(UIAlertAction *action) {
  504. [alertController dismissViewControllerAnimated:YES completion:nil];
  505. }]];
  506. alertController.popoverPresentationController.barButtonItem = deleteButton;
  507. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  508. [alertController.view layoutIfNeeded];
  509. [self.parentViewController presentViewController:alertController animated:YES completion:NULL];
  510. }
  511. - (void)progressTask:(NSString *)fileID serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated progress:(float)progress
  512. {
  513. if (progress == 0)
  514. [self.navigationController cancelCCProgress];
  515. else
  516. [self.navigationController setCCProgressPercentage:progress*100 andTintColor:COLOR_BRAND];
  517. }
  518. - (void)downloadPhotoBrowserFailure:(NSInteger)errorCode
  519. {
  520. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:dismissAfterSecond type:TWMessageBarMessageTypeError];
  521. [self.photoBrowser reloadData];
  522. [self.navigationController cancelCCProgress];
  523. }
  524. - (void)downloadPhotoBrowserSuccess:(CCMetadata *)metadataVar selector:(NSString *)selector
  525. {
  526. NSUInteger index = 0;
  527. // if a message for a directory of these
  528. if (![_dataSourceDirectoryID containsObject:metadataVar.directoryID])
  529. return;
  530. for (NSUInteger i=0; i < [self.dataSourceImagesVideos count]; i++ ) {
  531. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:i];
  532. // search index
  533. if ([metadataVar.fileID isEqualToString:metadata.fileID]) {
  534. index = i;
  535. break;
  536. }
  537. }
  538. // do not reload is Video on air
  539. if (_photoBrowser.currentVideoPlayerViewController.isViewLoaded && _photoBrowser.currentVideoPlayerViewController.view.window) return;
  540. //NSLog(@"[LOG] Add Download Photo Browser");
  541. if ([metadataVar.fileID isEqualToString:self.fileIDNowVisible] || [self.photoBrowser isGridReload:index]) {
  542. [self.photoBrowser reloadData];
  543. _reload = NO;
  544. } else {
  545. _reload = YES;
  546. }
  547. [self.navigationController cancelCCProgress];
  548. }
  549. - (void)downloadPhotoBrowser:(CCMetadata *)metadata
  550. {
  551. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  552. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadViewImage selectorPost:nil session:download_session taskStatus:taskStatusResume delegate:nil];
  553. }
  554. - (void)insertGeocoderLocation:(NSNotification *)notification
  555. {
  556. NSString *fileID = [[notification.userInfo allKeys] objectAtIndex:0];
  557. //NSDate *date = [[notification.userInfo allValues] objectAtIndex:0];
  558. // test [Chrash V 1.14,15]
  559. if (self.indexNowVisible >= [self.photos count])
  560. return;
  561. dispatch_async(dispatch_get_main_queue(), ^{
  562. if ([fileID isEqualToString:self.fileIDNowVisible]) {
  563. MWPhoto *photo = [self.photos objectAtIndex:self.indexNowVisible];
  564. [self setLocationCaptionPhoto:photo fileID:fileID];
  565. if (![self.photoBrowser isGridController]) {
  566. [self.photoBrowser hideControls];
  567. [self.photoBrowser showControls];
  568. }
  569. }
  570. });
  571. }
  572. - (void)setLocationCaptionPhoto:(MWPhoto *)photo fileID:(NSString *)fileID
  573. {
  574. TableLocalFile *localFile;
  575. // read Geocoder
  576. localFile = [CCCoreData getLocalFileWithFileID:fileID activeAccount:app.activeAccount];
  577. if ([localFile.exifLatitude doubleValue] != 0 || [localFile.exifLongitude doubleValue] != 0) {
  578. // Fix BUG Geo latitude & longitude
  579. if ([localFile.exifLatitude doubleValue] == 9999 || [localFile.exifLongitude doubleValue] == 9999) {
  580. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  581. [CCExifGeo setExifLocalTableFileID:metadata directoryUser:app.directoryUser activeAccount:app.activeAccount];
  582. }
  583. [CCExifGeo setGeocoderFileID:fileID exifDate:localFile.exifDate latitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  584. localFile = [CCCoreData getLocalFileWithFileID:fileID activeAccount:app.activeAccount];
  585. if ([localFile.exifLatitude floatValue] != 0 || [localFile.exifLongitude floatValue] != 0) {
  586. NSString *location = [CCCoreData getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  587. if ([localFile.exifDate isEqualToDate:[NSDate distantPast]] == NO && location) {
  588. NSString *localizedDateTime = [NSDateFormatter localizedStringFromDate:localFile.exifDate dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterMediumStyle];
  589. photo.caption = [NSString stringWithFormat:NSLocalizedString(@"%@\n%@", nil), localizedDateTime, location];
  590. }
  591. }
  592. }
  593. }
  594. #pragma --------------------------------------------------------------------------------------------
  595. #pragma mark ===== View PDF =====
  596. #pragma --------------------------------------------------------------------------------------------
  597. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  598. {
  599. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  600. [[alertView textFieldAtIndex:0] resignFirstResponder];
  601. if (alertView.tag == alertRequestPasswordPDF) [self performSelector:@selector(viewPDF:) withObject:[alertView textFieldAtIndex:0].text afterDelay:0.3];
  602. }
  603. - (void)viewPDF:(NSString *)password
  604. {
  605. NSString *fileName;
  606. if (_sourceDirectoryLocal) {
  607. fileName = [NSString stringWithFormat:@"%@/%@", self.metadataDetail.directoryID, self.metadataDetail.fileNamePrint];
  608. } else {
  609. fileName = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNamePrint];
  610. [[NSFileManager defaultManager] removeItemAtPath:fileName error:nil];
  611. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, self.metadataDetail.fileID] toPath:fileName error:nil];
  612. }
  613. if ([[NSFileManager defaultManager] fileExistsAtPath:fileName isDirectory:nil] == NO) {
  614. // read file error
  615. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  616. [alertView show];
  617. }
  618. CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:fileName]);
  619. if (pdf) {
  620. // Encrypted
  621. if (CGPDFDocumentIsEncrypted(pdf) == YES) {
  622. // Try a blank password first, per Apple's Quartz PDF example
  623. if (CGPDFDocumentUnlockWithPassword(pdf, "") == YES) {
  624. // blank password
  625. [self readerPDF:fileName password:@""];
  626. } else {
  627. if ([password length] == 0) {
  628. // password request
  629. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_insert_password_pfd_",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  630. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  631. alertView.tag = alertRequestPasswordPDF;
  632. [alertView show];
  633. } else {
  634. const char *key = [password UTF8String];
  635. // failure
  636. if (CGPDFDocumentUnlockWithPassword(pdf, key) == NO) {
  637. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_password_pdf_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  638. [alertView show];
  639. } else {
  640. // pdf with password
  641. [self readerPDF:fileName password:password];
  642. }
  643. }
  644. }
  645. } else{
  646. // No password
  647. [self readerPDF:fileName password:@""];
  648. }
  649. } else {
  650. // read file error
  651. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  652. [alertView show];
  653. }
  654. }
  655. - (void)readerPDF:(NSString *)fileName password:(NSString *)password
  656. {
  657. ReaderDocument *documentPDF = [ReaderDocument withDocumentFilePath:fileName password:password];
  658. if (documentPDF != nil) {
  659. self.readerPDFViewController = [[ReaderViewController alloc] initWithReaderDocument:documentPDF];
  660. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT);
  661. [self.readerPDFViewController updateContentViews];
  662. [self addChildViewController:self.readerPDFViewController];
  663. [self.view addSubview:self.readerPDFViewController.view];
  664. [self.readerPDFViewController didMoveToParentViewController:self];
  665. } else {
  666. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  667. [alertView show];
  668. }
  669. }
  670. #pragma --------------------------------------------------------------------------------------------
  671. #pragma mark ===== Delete =====
  672. #pragma --------------------------------------------------------------------------------------------
  673. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  674. {
  675. NSLog(@"[LOG] delete failure");
  676. }
  677. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  678. {
  679. // if a message for a directory of these
  680. if (![_dataSourceDirectoryID containsObject:metadataNet.metadata.directoryID])
  681. return;
  682. // if we are not in browserPhoto and it's removed photo/video in preview then "< Back"
  683. if (!self.photoBrowser && [self.metadataDetail.fileID isEqualToString:metadataNet.metadata.fileID]) {
  684. if ([metadataNet.metadata.typeFile isEqualToString:metadataTypeFile_audio])
  685. [app.player.mediaPlayer stop];
  686. NSArray *viewsToRemove = [self.view subviews];
  687. for (id element in viewsToRemove) {
  688. if ([element isMemberOfClass:[UIView class]] || [element isMemberOfClass:[UIToolbar class]] || [element isMemberOfClass:[LMMediaPlayerView class]])
  689. [element removeFromSuperview];
  690. }
  691. self.title = @"";
  692. [self.navigationController popViewControllerAnimated:YES];
  693. } else {
  694. // only photoBrowser if exists
  695. for (NSUInteger index=0; index < [self.dataSourceImagesVideos count] && _photoBrowser; index++ ) {
  696. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  697. // ricerca index
  698. if ([metadataNet.metadata.fileID isEqualToString:metadata.fileID]) {
  699. [self.dataSourceImagesVideos removeObjectAtIndex:index];
  700. [self.photos removeObjectAtIndex:index];
  701. [self.thumbs removeObjectAtIndex:index];
  702. [self.photoBrowser reloadData];
  703. if ([self.dataSourceImagesVideos count] == 1) {
  704. self.title = [NSString stringWithFormat:@"1 %@ 1", NSLocalizedString(@"of", nil)];
  705. }
  706. if ([self.dataSourceImagesVideos count] == 0) {
  707. self.title = @"";
  708. [self.navigationController popViewControllerAnimated:YES];
  709. }
  710. break;
  711. }
  712. }
  713. }
  714. }
  715. #pragma --------------------------------------------------------------------------------------------
  716. #pragma mark ===== ButtonPressed =====
  717. #pragma --------------------------------------------------------------------------------------------
  718. - (void)actionButtonPressed:(UIBarButtonItem *)sender
  719. {
  720. NSString *filePath;
  721. if ([self.metadataDetail.fileNamePrint length] == 0) return;
  722. if (_sourceDirectoryLocal) {
  723. filePath = [NSString stringWithFormat:@"%@/%@", self.metadataDetail.directoryID, self.metadataDetail.fileNamePrint];
  724. } else {
  725. filePath = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), self.metadataDetail.fileNamePrint];
  726. }
  727. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  728. self.docController.delegate = self;
  729. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) [self.docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  730. [self.docController presentOptionsMenuFromBarButtonItem:sender animated:YES];
  731. }
  732. - (void)deleteButtonPressed:(UIBarButtonItem *)sender
  733. {
  734. if ([self.metadataDetail.fileNamePrint length] == 0) return;
  735. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  736. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  737. style:UIAlertActionStyleDestructive
  738. handler:^(UIAlertAction *action) {
  739. [[CCActions sharedInstance] deleteFileOrFolder:self.metadataDetail delegate:self];
  740. }]];
  741. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  742. style:UIAlertActionStyleCancel
  743. handler:^(UIAlertAction *action) {
  744. [alertController dismissViewControllerAnimated:YES completion:nil];
  745. }]];
  746. alertController.popoverPresentationController.barButtonItem = _buttonDelete;
  747. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  748. [alertController.view layoutIfNeeded];
  749. [self presentViewController:alertController animated:YES completion:NULL];
  750. }
  751. @end