CCDetail.m 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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 () <CCActionsDeleteDelegate>
  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_brandBackgroundLite];
  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 = nil;
  109. }
  110. // PDF
  111. if (_readerPDFViewController) {
  112. [_readerPDFViewController.view removeFromSuperview];
  113. _readerPDFViewController.delegate = nil;
  114. _readerPDFViewController = nil;
  115. }
  116. // Photo-Video
  117. if (_photoBrowser) {
  118. [_photos removeAllObjects];
  119. [_thumbs removeAllObjects];
  120. _photoBrowser.delegate = nil;
  121. _photoBrowser = nil;
  122. }
  123. [self.navigationController popToRootViewControllerAnimated:NO];
  124. self.navigationController.navigationBarHidden = YES;
  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: k_metadataTypeFile_image] || [self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_video]) {
  166. self.edgesForExtendedLayout = UIRectEdgeAll;
  167. [self viewImage];
  168. }
  169. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_audio]) {
  170. self.edgesForExtendedLayout = UIRectEdgeBottom;
  171. [self viewAudio];
  172. [self createToolbar];
  173. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] hidden:NO];
  174. }
  175. if ([self.metadataDetail.typeFile isEqualToString: k_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 encrypted:NO online:[app.reachability isReachable] hidden:NO];
  182. } else {
  183. self.edgesForExtendedLayout = UIRectEdgeBottom;
  184. [self viewDocument];
  185. [self createToolbar];
  186. [CCAspect aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:NO online:[app.reachability isReachable] 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. WKPreferences *wkPreferences = [[WKPreferences alloc] init];
  237. wkPreferences.javaScriptEnabled = false;
  238. WKWebViewConfiguration *wkConfig = [[WKWebViewConfiguration alloc] init];
  239. wkConfig.preferences = wkPreferences;
  240. self.webView = [[WKWebView alloc] initWithFrame:(CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT)) configuration:wkConfig];
  241. self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  242. [self.webView setBackgroundColor:[UIColor whiteColor]];
  243. [self.webView setOpaque:NO];
  244. if ( [ext isEqualToString:@"CSS"] || [ext isEqualToString:@"PY"] || [ext isEqualToString:@"XML"] || [ext isEqualToString:@"JS"] ) {
  245. NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:[NSURL fileURLWithPath:fileName]];
  246. [headRequest setHTTPMethod:@"HEAD"];
  247. NSHTTPURLResponse *headResponse;
  248. NSError *error = nil;
  249. [NSURLConnection sendSynchronousRequest:headRequest returningResponse:&headResponse error:&error];
  250. if (error != nil) {
  251. NSLog(@"[LOG] loadURLWithString %@",[error localizedDescription]);
  252. }
  253. NSString *dataFile = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL fileURLWithPath:fileName]] encoding:NSASCIIStringEncoding];
  254. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  255. [self.webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-size:%@;font-family:%@;'><pre>%@",@"40",@"Sans-Serif",dataFile] baseURL:nil];
  256. }else{
  257. [self.webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-size:%@;font-family:%@;'><pre>%@",@"20",@"Sans-Serif",dataFile] baseURL:nil];
  258. }
  259. } else if ([ext isEqualToString:@"TXT"] ) {
  260. NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:[NSURL fileURLWithPath:fileName]];
  261. [headRequest setHTTPMethod:@"HEAD"];
  262. NSHTTPURLResponse *headResponse;
  263. NSError *error = nil;
  264. [NSURLConnection sendSynchronousRequest:headRequest returningResponse:&headResponse error:&error];
  265. if (error != nil) {
  266. NSLog(@"[LOG] loadURLWithString %@",[error localizedDescription]);
  267. }
  268. [self.webView loadRequest:[NSMutableURLRequest requestWithURL:[NSURL fileURLWithPath:fileName]]];
  269. } else {
  270. [self.webView loadRequest:[NSMutableURLRequest requestWithURL:[NSURL fileURLWithPath:fileName]]];
  271. }
  272. [self.view addSubview:self.webView];
  273. }
  274. #pragma --------------------------------------------------------------------------------------------
  275. #pragma mark ===== View Image =====
  276. #pragma --------------------------------------------------------------------------------------------
  277. - (void)viewImage
  278. {
  279. self.photoBrowser = [[MWPhotoBrowser alloc] initWithDelegate:self];
  280. _reload = NO;
  281. [self.photos removeAllObjects];
  282. [self.thumbs removeAllObjects];
  283. [_dataSourceDirectoryID removeAllObjects];
  284. // if not images, exit
  285. if ([self.dataSourceImagesVideos count] == 0) return;
  286. NSUInteger index = 0;
  287. for (CCMetadata *metadata in self.dataSourceImagesVideos) {
  288. // start from here ?
  289. if (self.metadataDetail.fileID && [metadata.fileID isEqualToString:self.metadataDetail.fileID])
  290. [self.photoBrowser setCurrentPhotoIndex:index];
  291. if (metadata.cryptated) {
  292. [self.photos addObject:[MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewDownloadCrypto]]];
  293. [self.thumbs addObject:[MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewDownloadCrypto]]];
  294. } else {
  295. [self.photos addObject:[MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewDownload]]];
  296. MWPhoto *thumb = [MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewDownload]];
  297. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) thumb.isVideo = YES;
  298. [self.thumbs addObject:thumb];
  299. }
  300. // add directory
  301. [_dataSourceDirectoryID addObject:metadata.directoryID];
  302. index++;
  303. }
  304. // PhotoBrowser
  305. self.photoBrowser.displayActionButton = YES;
  306. self.photoBrowser.displayDeleteButton = YES;
  307. self.photoBrowser.displayNavArrows = YES;
  308. self.photoBrowser.displaySelectionButtons = NO;
  309. self.photoBrowser.alwaysShowControls = NO;
  310. self.photoBrowser.zoomPhotosToFill = NO;
  311. self.photoBrowser.startOnGrid = NO;
  312. self.photoBrowser.autoPlayOnAppear = NO;
  313. self.photoBrowser.delayToHideElements = 15;
  314. self.photoBrowser.enableGrid = YES;
  315. if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
  316. [self addChildViewController:self.photoBrowser];
  317. [self.view addSubview:self.photoBrowser.view];
  318. [self.photoBrowser didMoveToParentViewController:self];
  319. } else {
  320. [self.navigationController pushViewController:self.photoBrowser animated:NO];
  321. }
  322. }
  323. - (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
  324. {
  325. return [self.dataSourceImagesVideos count];
  326. }
  327. - (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index
  328. {
  329. NSString *titleDir = [NSString stringWithFormat:@"%lu %@ %lu", (unsigned long)index+1, NSLocalizedString(@"of", nil), (unsigned long)self.photos.count];
  330. self.title = titleDir;
  331. return titleDir;
  332. }
  333. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
  334. {
  335. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  336. NSString *directory;
  337. self.indexNowVisible = index;
  338. self.fileIDNowVisible = metadata.fileID;
  339. photoBrowser.toolbar.hidden = NO;
  340. if (_reload) {
  341. [self.photoBrowser performSelector:@selector(reloadData) withObject:nil afterDelay:0.1];
  342. _reload = NO;
  343. }
  344. if (_sourceDirectoryLocal)
  345. directory = self.metadataDetail.directoryID;
  346. else
  347. directory = app.directoryUser;
  348. // Download
  349. if (metadata && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directory, metadata.fileID]] == NO && [metadata.session length] == 0)
  350. [self performSelector:@selector(downloadPhotoBrowser:) withObject:metadata afterDelay:0.1];
  351. }
  352. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
  353. {
  354. NSString *directory;
  355. UIImage *image;
  356. if (_sourceDirectoryLocal)
  357. directory = self.metadataDetail.directoryID;
  358. else
  359. directory = app.directoryUser;
  360. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  361. //NSLog(@"[LOG] photoBrowser: photoAtIndex : %lu ---- di totali photo : %lu", (unsigned long)index, (unsigned long)_photos.count);
  362. if (index < self.photos.count) {
  363. if (metadata.fileID) {
  364. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  365. NSString *fileImage = [NSString stringWithFormat:@"%@/%@", directory, metadata.fileID];
  366. NSString *ext = [CCUtility getExtension:metadata.fileNamePrint];
  367. if ([ext isEqualToString:@"GIF"]) image = [UIImage animatedImageWithAnimatedGIFURL:[NSURL fileURLWithPath:fileImage]];
  368. else image = [UIImage imageWithContentsOfFile:fileImage];
  369. if (image) {
  370. MWPhoto *photo = [MWPhoto photoWithImage:image];
  371. // Location ??
  372. [self setLocationCaptionPhoto:photo fileID:metadata.fileID];
  373. if (!photo.caption)
  374. photo.caption = metadata.fileNamePrint;
  375. [self.photos replaceObjectAtIndex:index withObject:photo];
  376. } else {
  377. if ([metadata.sessionError length] > 0 ) {
  378. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewError]]];
  379. } else {
  380. NSURL *url = [[NSBundle mainBundle] URLForResource:@"loading" withExtension:@"gif"];
  381. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage animatedImageWithAnimatedGIFURL:url]]];
  382. }
  383. }
  384. }
  385. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  386. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directory, metadata.fileID]]) {
  387. // remove and make the simbolic link in temp
  388. NSString *toPath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint];
  389. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  390. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", directory, metadata.fileID] toPath:toPath error:nil];
  391. NSURL *url = [NSURL fileURLWithPath:toPath];
  392. MWPhoto *video = [MWPhoto photoWithImage:[CCGraphics thumbnailImageForVideo:url atTime:1.0]];
  393. video.caption = metadata.fileNamePrint;
  394. video.videoURL = url;
  395. [self.photos replaceObjectAtIndex:index withObject:video];
  396. } else {
  397. if ([metadata.sessionError length] > 0 ) {
  398. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:image_filePreviewError]]];
  399. } else {
  400. NSURL *url = [[NSBundle mainBundle] URLForResource:@"loading" withExtension:@"gif"];
  401. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage animatedImageWithAnimatedGIFURL:url]]];
  402. }
  403. }
  404. }
  405. }
  406. // energy saving memory
  407. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  408. int iPrev = (int)index - 2;
  409. if (iPrev >= 0) {
  410. if ([self.photos objectAtIndex:iPrev] != nil)
  411. [self.photos replaceObjectAtIndex:iPrev withObject:[MWPhoto photoWithImage:nil]];
  412. }
  413. int iNext = (int)index + 2;
  414. if (iNext < _photos.count) {
  415. if ([self.photos objectAtIndex:iNext] != nil)
  416. [self.photos replaceObjectAtIndex:iNext withObject:[MWPhoto photoWithImage:nil]];
  417. }
  418. });
  419. return [self.photos objectAtIndex:index];
  420. }
  421. return nil;
  422. }
  423. - (void)gridWillAppear:(MWPhotoBrowser *)photoBrowser
  424. {
  425. // reload [BUG]
  426. [self.photoBrowser reloadData];
  427. // in grid clear all MWPhoto : energy saving memory
  428. if (self.photos.count > 1 && [self.dataSourceImagesVideos count] > 0) {
  429. for(int index=0; index < self.photos.count; index++)
  430. [_photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:nil]];
  431. }
  432. self.title = [NSString stringWithFormat:@"Album %lu %@", (unsigned long)_photos.count, NSLocalizedString(@"photos", nil)];
  433. }
  434. - (void)gridWillDisappear:(MWPhotoBrowser *)photoBrowser
  435. {
  436. //
  437. photoBrowser.toolbar.hidden = NO;
  438. }
  439. - (void)setControlsHidden:(BOOL)hidden animated:(BOOL)animated permanent:(BOOL)permanent
  440. {
  441. // Control Center
  442. if (self.splitViewController.isCollapsed)
  443. [app.controlCenter setControlCenterHidden:hidden];
  444. self.navigationController.navigationBar.hidden = hidden;
  445. }
  446. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index
  447. {
  448. NSString *directory;
  449. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  450. if (_sourceDirectoryLocal)
  451. directory = self.metadataDetail.directoryID;
  452. else
  453. directory = app.directoryUser;
  454. if (index < self.thumbs.count) {
  455. if (metadata.fileID) {
  456. UIImage *image;
  457. if (_sourceDirectoryLocal) {
  458. 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]];
  459. } else {
  460. NSString *fileImage = [NSString stringWithFormat:@"%@/%@.ico", directory, metadata.fileID];
  461. image = [UIImage animatedImageWithAnimatedGIFURL:[NSURL fileURLWithPath:fileImage]];
  462. }
  463. if (image) {
  464. MWPhoto *thumb = [MWPhoto photoWithImage:image];
  465. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) thumb.isVideo = YES;
  466. [self.thumbs replaceObjectAtIndex:index withObject:thumb];
  467. }
  468. }
  469. return [self.thumbs objectAtIndex:index];
  470. }
  471. return nil;
  472. }
  473. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index
  474. {
  475. NSString *filePath;
  476. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  477. if (metadata == nil) return;
  478. if (_sourceDirectoryLocal) {
  479. filePath = [NSString stringWithFormat:@"%@/%@", self.metadataDetail.directoryID, self.metadataDetail.fileNamePrint];
  480. } else {
  481. filePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  482. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  483. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:filePath error:nil];
  484. }
  485. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  486. self.docController.delegate = self;
  487. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) [self.docController presentOptionsMenuFromRect:photoBrowser.view.frame inView:photoBrowser.view animated:YES];
  488. [self.docController presentOptionsMenuFromBarButtonItem:photoBrowser.actionButton animated:YES];
  489. }
  490. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser deleteButtonPressedForPhotoAtIndex:(NSUInteger)index deleteButton:(UIBarButtonItem *)deleteButton
  491. {
  492. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  493. if (metadata == nil || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]] == NO) {
  494. [app messageNotification:@"_info_" description:@"_file_not_found_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  495. return;
  496. }
  497. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  498. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  499. style:UIAlertActionStyleDestructive
  500. handler:^(UIAlertAction *action) {
  501. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  502. }]];
  503. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  504. style:UIAlertActionStyleCancel
  505. handler:^(UIAlertAction *action) {
  506. [alertController dismissViewControllerAnimated:YES completion:nil];
  507. }]];
  508. alertController.popoverPresentationController.barButtonItem = deleteButton;
  509. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  510. [alertController.view layoutIfNeeded];
  511. [self.parentViewController presentViewController:alertController animated:YES completion:NULL];
  512. }
  513. - (void)progressTask:(NSString *)fileID serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated progress:(float)progress
  514. {
  515. if (progress == 0)
  516. [self.navigationController cancelCCProgress];
  517. else
  518. [self.navigationController setCCProgressPercentage:progress*100 andTintColor:COLOR_NAVIGATIONBAR_PROGRESS];
  519. }
  520. - (void)downloadPhotoBrowserFailure:(NSInteger)errorCode
  521. {
  522. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  523. [self.photoBrowser reloadData];
  524. [self.navigationController cancelCCProgress];
  525. }
  526. - (void)downloadPhotoBrowserSuccess:(CCMetadata *)metadataVar selector:(NSString *)selector
  527. {
  528. NSUInteger index = 0;
  529. // if a message for a directory of these
  530. if (![_dataSourceDirectoryID containsObject:metadataVar.directoryID])
  531. return;
  532. for (NSUInteger i=0; i < [self.dataSourceImagesVideos count]; i++ ) {
  533. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:i];
  534. // search index
  535. if ([metadataVar.fileID isEqualToString:metadata.fileID]) {
  536. index = i;
  537. break;
  538. }
  539. }
  540. // do not reload is Video on air
  541. if (_photoBrowser.currentVideoPlayerViewController.isViewLoaded && _photoBrowser.currentVideoPlayerViewController.view.window) return;
  542. //NSLog(@"[LOG] Add Download Photo Browser");
  543. if ([metadataVar.fileID isEqualToString:self.fileIDNowVisible] || [self.photoBrowser isGridReload:index]) {
  544. [self.photoBrowser reloadData];
  545. _reload = NO;
  546. } else {
  547. _reload = YES;
  548. }
  549. [self.navigationController cancelCCProgress];
  550. }
  551. - (void)downloadPhotoBrowser:(CCMetadata *)metadata
  552. {
  553. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  554. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadViewImage selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:nil];
  555. }
  556. - (void)insertGeocoderLocation:(NSNotification *)notification
  557. {
  558. NSString *fileID = [[notification.userInfo allKeys] objectAtIndex:0];
  559. //NSDate *date = [[notification.userInfo allValues] objectAtIndex:0];
  560. // test [Chrash V 1.14,15]
  561. if (self.indexNowVisible >= [self.photos count])
  562. return;
  563. dispatch_async(dispatch_get_main_queue(), ^{
  564. if ([fileID isEqualToString:self.fileIDNowVisible]) {
  565. MWPhoto *photo = [self.photos objectAtIndex:self.indexNowVisible];
  566. [self setLocationCaptionPhoto:photo fileID:fileID];
  567. if (![self.photoBrowser isGridController]) {
  568. [self.photoBrowser hideControls];
  569. [self.photoBrowser showControls];
  570. }
  571. }
  572. });
  573. }
  574. - (void)setLocationCaptionPhoto:(MWPhoto *)photo fileID:(NSString *)fileID
  575. {
  576. TableLocalFile *localFile;
  577. // read Geocoder
  578. localFile = [CCCoreData getLocalFileWithFileID:fileID activeAccount:app.activeAccount];
  579. if ([localFile.exifLatitude doubleValue] != 0 || [localFile.exifLongitude doubleValue] != 0) {
  580. // Fix BUG Geo latitude & longitude
  581. if ([localFile.exifLatitude doubleValue] == 9999 || [localFile.exifLongitude doubleValue] == 9999) {
  582. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  583. [CCExifGeo setExifLocalTableFileID:metadata directoryUser:app.directoryUser activeAccount:app.activeAccount];
  584. }
  585. [CCExifGeo setGeocoderFileID:fileID exifDate:localFile.exifDate latitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  586. localFile = [CCCoreData getLocalFileWithFileID:fileID activeAccount:app.activeAccount];
  587. if ([localFile.exifLatitude floatValue] != 0 || [localFile.exifLongitude floatValue] != 0) {
  588. NSString *location = [CCCoreData getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  589. if ([localFile.exifDate isEqualToDate:[NSDate distantPast]] == NO && location) {
  590. NSString *localizedDateTime = [NSDateFormatter localizedStringFromDate:localFile.exifDate dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterMediumStyle];
  591. photo.caption = [NSString stringWithFormat:NSLocalizedString(@"%@\n%@", nil), localizedDateTime, location];
  592. }
  593. }
  594. }
  595. }
  596. #pragma --------------------------------------------------------------------------------------------
  597. #pragma mark ===== View PDF =====
  598. #pragma --------------------------------------------------------------------------------------------
  599. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  600. {
  601. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  602. [[alertView textFieldAtIndex:0] resignFirstResponder];
  603. if (alertView.tag == alertRequestPasswordPDF) [self performSelector:@selector(viewPDF:) withObject:[alertView textFieldAtIndex:0].text afterDelay:0.3];
  604. }
  605. - (void)viewPDF:(NSString *)password
  606. {
  607. NSString *fileName;
  608. if (_sourceDirectoryLocal) {
  609. fileName = [NSString stringWithFormat:@"%@/%@", self.metadataDetail.directoryID, self.metadataDetail.fileNamePrint];
  610. } else {
  611. fileName = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNamePrint];
  612. [[NSFileManager defaultManager] removeItemAtPath:fileName error:nil];
  613. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, self.metadataDetail.fileID] toPath:fileName error:nil];
  614. }
  615. if ([[NSFileManager defaultManager] fileExistsAtPath:fileName isDirectory:nil] == NO) {
  616. // read file error
  617. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  618. [alertView show];
  619. }
  620. CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:fileName]);
  621. if (pdf) {
  622. // Encrypted
  623. if (CGPDFDocumentIsEncrypted(pdf) == YES) {
  624. // Try a blank password first, per Apple's Quartz PDF example
  625. if (CGPDFDocumentUnlockWithPassword(pdf, "") == YES) {
  626. // blank password
  627. [self readerPDF:fileName password:@""];
  628. } else {
  629. if ([password length] == 0) {
  630. // password request
  631. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_insert_password_pfd_",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  632. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  633. alertView.tag = alertRequestPasswordPDF;
  634. [alertView show];
  635. } else {
  636. const char *key = [password UTF8String];
  637. // failure
  638. if (CGPDFDocumentUnlockWithPassword(pdf, key) == NO) {
  639. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_password_pdf_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  640. [alertView show];
  641. } else {
  642. // pdf with password
  643. [self readerPDF:fileName password:password];
  644. }
  645. }
  646. }
  647. } else{
  648. // No password
  649. [self readerPDF:fileName password:@""];
  650. }
  651. } else {
  652. // read file error
  653. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  654. [alertView show];
  655. }
  656. }
  657. - (void)readerPDF:(NSString *)fileName password:(NSString *)password
  658. {
  659. ReaderDocument *documentPDF = [ReaderDocument withDocumentFilePath:fileName password:password];
  660. if (documentPDF != nil) {
  661. self.readerPDFViewController = [[ReaderViewController alloc] initWithReaderDocument:documentPDF];
  662. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT);
  663. [self.readerPDFViewController updateContentViews];
  664. [self addChildViewController:self.readerPDFViewController];
  665. [self.view addSubview:self.readerPDFViewController.view];
  666. [self.readerPDFViewController didMoveToParentViewController:self];
  667. } else {
  668. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  669. [alertView show];
  670. }
  671. }
  672. #pragma --------------------------------------------------------------------------------------------
  673. #pragma mark ===== Delete =====
  674. #pragma --------------------------------------------------------------------------------------------
  675. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  676. {
  677. NSLog(@"[LOG] delete failure");
  678. }
  679. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  680. {
  681. // if a message for a directory of these
  682. if (![_dataSourceDirectoryID containsObject:metadataNet.metadata.directoryID])
  683. return;
  684. // if we are not in browserPhoto and it's removed photo/video in preview then "< Back"
  685. if (!self.photoBrowser && [self.metadataDetail.fileID isEqualToString:metadataNet.metadata.fileID]) {
  686. if ([metadataNet.metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  687. [app.player.mediaPlayer stop];
  688. NSArray *viewsToRemove = [self.view subviews];
  689. for (id element in viewsToRemove) {
  690. if ([element isMemberOfClass:[UIView class]] || [element isMemberOfClass:[UIToolbar class]] || [element isMemberOfClass:[LMMediaPlayerView class]])
  691. [element removeFromSuperview];
  692. }
  693. self.title = @"";
  694. [self.navigationController popViewControllerAnimated:YES];
  695. } else {
  696. // only photoBrowser if exists
  697. for (NSUInteger index=0; index < [self.dataSourceImagesVideos count] && _photoBrowser; index++ ) {
  698. CCMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  699. // ricerca index
  700. if ([metadataNet.metadata.fileID isEqualToString:metadata.fileID]) {
  701. [self.dataSourceImagesVideos removeObjectAtIndex:index];
  702. [self.photos removeObjectAtIndex:index];
  703. [self.thumbs removeObjectAtIndex:index];
  704. [self.photoBrowser reloadData];
  705. if ([self.dataSourceImagesVideos count] == 1) {
  706. self.title = [NSString stringWithFormat:@"1 %@ 1", NSLocalizedString(@"of", nil)];
  707. }
  708. if ([self.dataSourceImagesVideos count] == 0) {
  709. self.title = @"";
  710. [self.navigationController popViewControllerAnimated:YES];
  711. }
  712. break;
  713. }
  714. }
  715. }
  716. }
  717. #pragma --------------------------------------------------------------------------------------------
  718. #pragma mark ===== ButtonPressed =====
  719. #pragma --------------------------------------------------------------------------------------------
  720. - (void)actionButtonPressed:(UIBarButtonItem *)sender
  721. {
  722. NSString *filePath;
  723. if ([self.metadataDetail.fileNamePrint length] == 0) return;
  724. if (_sourceDirectoryLocal) {
  725. filePath = [NSString stringWithFormat:@"%@/%@", self.metadataDetail.directoryID, self.metadataDetail.fileNamePrint];
  726. } else {
  727. filePath = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), self.metadataDetail.fileNamePrint];
  728. }
  729. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  730. self.docController.delegate = self;
  731. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) [self.docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  732. [self.docController presentOptionsMenuFromBarButtonItem:sender animated:YES];
  733. }
  734. - (void)deleteButtonPressed:(UIBarButtonItem *)sender
  735. {
  736. if ([self.metadataDetail.fileNamePrint length] == 0) return;
  737. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  738. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  739. style:UIAlertActionStyleDestructive
  740. handler:^(UIAlertAction *action) {
  741. [[CCActions sharedInstance] deleteFileOrFolder:self.metadataDetail delegate:self];
  742. }]];
  743. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  744. style:UIAlertActionStyleCancel
  745. handler:^(UIAlertAction *action) {
  746. [alertController dismissViewControllerAnimated:YES completion:nil];
  747. }]];
  748. alertController.popoverPresentationController.barButtonItem = _buttonDelete;
  749. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  750. [alertController.view layoutIfNeeded];
  751. [self presentViewController:alertController animated:YES completion:NULL];
  752. }
  753. @end