CCDetail.m 43 KB

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