CCDetail.m 43 KB

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