CCDetail.m 43 KB

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