CCDetail.m 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. //
  2. // CCDetail.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 16/01/15.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCDetail.h"
  24. #import "AppDelegate.h"
  25. #import "CCMain.h"
  26. #import "NCUchardet.h"
  27. #import "NCBridgeSwift.h"
  28. #define TOOLBAR_HEIGHT 49.0f
  29. #define alertRequestPasswordPDF 1
  30. @interface CCDetail () <CCActionsDeleteDelegate>
  31. {
  32. AppDelegate *appDelegate;
  33. UIToolbar *_toolbar;
  34. UIBarButtonItem *_buttonModifyTxt;
  35. UIBarButtonItem *_buttonAction;
  36. UIBarButtonItem *_buttonShare;
  37. UIBarButtonItem *_buttonDelete;
  38. NSInteger _indexNowVisible;
  39. NSString *_fileIDNowVisible;
  40. NSMutableOrderedSet *_dataSourceDirectoryID;
  41. NSString *_fileNameExtension;
  42. CCHud *_hud;
  43. }
  44. @end
  45. @implementation CCDetail
  46. #pragma --------------------------------------------------------------------------------------------
  47. #pragma mark ===== init =====
  48. #pragma --------------------------------------------------------------------------------------------
  49. - (id)initWithCoder:(NSCoder *)aDecoder
  50. {
  51. if (self = [super initWithCoder:aDecoder]) {
  52. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  53. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  54. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backNavigationController) name:@"detailBack" object:nil];
  55. self.metadataDetail = [[tableMetadata alloc] init];
  56. self.photos = [[NSMutableArray alloc] init];
  57. self.dataSourceImagesVideos = [[NSMutableArray alloc] init];
  58. _dataSourceDirectoryID = [[NSMutableOrderedSet alloc] init];
  59. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  60. _indexNowVisible = -1;
  61. _fileIDNowVisible = nil;
  62. app.activeDetail = self;
  63. }
  64. return self;
  65. }
  66. #pragma --------------------------------------------------------------------------------------------
  67. #pragma mark ===== View =====
  68. #pragma --------------------------------------------------------------------------------------------
  69. - (void)viewDidLoad
  70. {
  71. [super viewDidLoad];
  72. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  73. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertGeocoderLocation:) name:@"insertGeocoderLocation" object:nil];
  74. self.imageBackground.image = [UIImage imageNamed:@"backgroundDetail"];
  75. if ([self.metadataDetail.fileNameView length] > 0 || [self.metadataDetail.directoryID length] > 0 || [self.metadataDetail.fileID length] > 0) {
  76. // open view
  77. [self viewFile];
  78. }
  79. }
  80. // Apparirà
  81. - (void)viewWillAppear:(BOOL)animated
  82. {
  83. [super viewWillAppear:animated];
  84. if (self.splitViewController.isCollapsed) {
  85. self.tabBarController.tabBar.hidden = YES;
  86. self.tabBarController.tabBar.translucent = YES;
  87. }
  88. if (self.splitViewController.isCollapsed)
  89. [app plusButtonVisibile:false];
  90. }
  91. // E' scomparso
  92. - (void)viewDidDisappear:(BOOL)animated
  93. {
  94. [super viewDidDisappear:animated];
  95. // remove all
  96. if (self.isMovingFromParentViewController)
  97. [self removeAllView];
  98. }
  99. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  100. {
  101. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  102. }];
  103. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  104. }
  105. // remove all view
  106. - (void)removeAllView
  107. {
  108. // Document
  109. if (_webView) {
  110. [_webView removeFromSuperview];
  111. _webView = nil;
  112. }
  113. // PDF
  114. if (_readerPDFViewController) {
  115. [_readerPDFViewController.view removeFromSuperview];
  116. _readerPDFViewController.delegate = nil;
  117. _readerPDFViewController = nil;
  118. }
  119. // Photo-Video-Audio
  120. if (_photoBrowser) {
  121. [_photos removeAllObjects];
  122. _photoBrowser.delegate = nil;
  123. _photoBrowser = nil;
  124. }
  125. // ToolBar
  126. if (_toolbar) {
  127. [_toolbar removeFromSuperview];
  128. _toolbar = nil;
  129. }
  130. // Title
  131. self.title = nil;
  132. }
  133. - (void)backNavigationController
  134. {
  135. [self removeAllView];
  136. [self.navigationController popViewControllerAnimated:NO];
  137. }
  138. - (void)changeToDisplayMode
  139. {
  140. if (_readerPDFViewController)
  141. [self.readerPDFViewController updateContentViews];
  142. }
  143. - (void)createToolbar
  144. {
  145. CGFloat safeAreaBottom = 0;
  146. if (@available(iOS 11, *)) {
  147. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  148. }
  149. _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom, self.view.bounds.size.width, TOOLBAR_HEIGHT)];
  150. UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
  151. UIBarButtonItem *fixedSpaceMini = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  152. fixedSpaceMini.width = 25;
  153. _buttonModifyTxt = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"actionSheetModify"] style:UIBarButtonItemStylePlain target:self action:@selector(modifyTxtButtonPressed:)];
  154. _buttonAction = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"actionSheetOpenIn"] style:UIBarButtonItemStylePlain target:self action:@selector(actionButtonPressed:)];
  155. _buttonShare = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"actionSheetShare"] style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonPressed:)];
  156. _buttonDelete = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteButtonPressed:)];
  157. if ([_fileNameExtension isEqualToString:@"TXT"])
  158. [_toolbar setItems:[NSArray arrayWithObjects: _buttonModifyTxt, flexible, _buttonDelete, fixedSpaceMini, _buttonShare, fixedSpaceMini, _buttonAction, nil]];
  159. else
  160. [_toolbar setItems:[NSArray arrayWithObjects: flexible, _buttonDelete, fixedSpaceMini, _buttonShare, fixedSpaceMini, _buttonAction, nil]];
  161. [_toolbar setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  162. _toolbar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  163. _toolbar.tintColor = [NCBrandColor sharedInstance].brand;
  164. [self.view addSubview:_toolbar];
  165. }
  166. - (void)changeTheming
  167. {
  168. [app changeTheming:self];
  169. if (_toolbar) {
  170. _toolbar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  171. _toolbar.tintColor = [NCBrandColor sharedInstance].brand;
  172. }
  173. }
  174. #pragma --------------------------------------------------------------------------------------------
  175. #pragma mark ===== View File =====
  176. #pragma --------------------------------------------------------------------------------------------
  177. - (void)viewFile
  178. {
  179. // verifico se esiste l'icona e se la posso creare
  180. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, self.metadataDetail.fileID]] == NO) {
  181. [CCGraphics createNewImageFrom:self.metadataDetail.fileID directoryUser:app.directoryUser fileNameTo:self.metadataDetail.fileID extension:[self.metadataDetail.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:self.metadataDetail.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  182. }
  183. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_image] || [self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_audio]) {
  184. self.edgesForExtendedLayout = UIRectEdgeAll;
  185. [self viewImageVideoAudio];
  186. }
  187. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_document]) {
  188. _fileNameExtension = [[self.metadataDetail.fileNameView pathExtension] uppercaseString];
  189. if ([_fileNameExtension isEqualToString:@"PDF"]) {
  190. self.edgesForExtendedLayout = UIRectEdgeBottom;
  191. [self viewPDF:@""];
  192. [self createToolbar];
  193. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  194. } else {
  195. self.edgesForExtendedLayout = UIRectEdgeBottom;
  196. [self viewDocument];
  197. [self createToolbar];
  198. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  199. }
  200. }
  201. }
  202. #pragma --------------------------------------------------------------------------------------------
  203. #pragma mark ===== View Document =====
  204. #pragma --------------------------------------------------------------------------------------------
  205. - (void)viewDocument
  206. {
  207. NSString *fileName;
  208. CGFloat safeAreaBottom = 0;
  209. if (@available(iOS 11, *)) {
  210. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  211. }
  212. fileName = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNameView];
  213. [[NSFileManager defaultManager] removeItemAtPath:fileName error:nil];
  214. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, self.metadataDetail.fileID] toPath:fileName error:nil];
  215. if ([[NSFileManager defaultManager] fileExistsAtPath:fileName] == NO) {
  216. [self backNavigationController];
  217. return;
  218. }
  219. NSURL *url = [NSURL fileURLWithPath:fileName];
  220. WKPreferences *wkPreferences = [[WKPreferences alloc] init];
  221. wkPreferences.javaScriptEnabled = true;
  222. WKWebViewConfiguration *wkConfig = [[WKWebViewConfiguration alloc] init];
  223. wkConfig.preferences = wkPreferences;
  224. self.webView = [[WKWebView alloc] initWithFrame:(CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom)) configuration:wkConfig];
  225. self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  226. [self.webView setBackgroundColor:[UIColor whiteColor]];
  227. [self.webView setOpaque:NO];
  228. if ( [_fileNameExtension isEqualToString:@"CSS"] || [_fileNameExtension isEqualToString:@"PY"] || [_fileNameExtension isEqualToString:@"XML"] || [_fileNameExtension isEqualToString:@"JS"] ) {
  229. NSString *dataFile = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:url] encoding:NSASCIIStringEncoding];
  230. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  231. [self.webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-size:%@;font-family:%@;'><pre>%@",@"40",@"Sans-Serif",dataFile] baseURL:nil];
  232. }else{
  233. [self.webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-size:%@;font-family:%@;'><pre>%@",@"20",@"Sans-Serif",dataFile] baseURL:nil];
  234. }
  235. } else if ([_fileNameExtension isEqualToString:@"TXT"]) {
  236. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  237. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
  238. NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
  239. [headRequest setHTTPMethod:@"HEAD"];
  240. NSURLSessionDataTask *task = [session dataTaskWithRequest:headRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  241. NSString *encodingName = [[NCUchardet sharedNUCharDet] encodingStringDetectWithData:data];
  242. [self.webView loadData:[NSData dataWithContentsOfURL: url] MIMEType:response.MIMEType characterEncodingName:encodingName baseURL:url];
  243. }];
  244. [task resume];
  245. } else {
  246. [self.webView loadRequest:[NSMutableURLRequest requestWithURL:url]];
  247. }
  248. [self.view addSubview:self.webView];
  249. }
  250. #pragma --------------------------------------------------------------------------------------------
  251. #pragma mark ===== View Image =====
  252. #pragma --------------------------------------------------------------------------------------------
  253. - (void)viewImageVideoAudio
  254. {
  255. self.photoBrowser = [[MWPhotoBrowser alloc] initWithDelegate:self];
  256. _indexNowVisible = -1;
  257. _fileIDNowVisible = nil;
  258. [self.photos removeAllObjects];
  259. [_dataSourceDirectoryID removeAllObjects];
  260. // if not images, exit
  261. if ([self.dataSourceImagesVideos count] == 0) return;
  262. NSUInteger index = 0;
  263. for (tableMetadata *metadata in self.dataSourceImagesVideos) {
  264. // start from here ?
  265. if (self.metadataDetail.fileID && [metadata.fileID isEqualToString:self.metadataDetail.fileID])
  266. [self.photoBrowser setCurrentPhotoIndex:index];
  267. [self.photos addObject:[MWPhoto photoWithImage:nil]];
  268. // add directory
  269. [_dataSourceDirectoryID addObject:metadata.directoryID];
  270. index++;
  271. }
  272. // PhotoBrowser
  273. self.photoBrowser.displayActionButton = YES;
  274. self.photoBrowser.displayDeleteButton = YES;
  275. self.photoBrowser.displayNavArrows = YES;
  276. self.photoBrowser.displaySelectionButtons = NO;
  277. self.photoBrowser.alwaysShowControls = NO;
  278. self.photoBrowser.zoomPhotosToFill = NO;
  279. self.photoBrowser.autoPlayOnAppear = NO;
  280. self.photoBrowser.delayToHideElements = 15;
  281. if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
  282. [self addChildViewController:self.photoBrowser];
  283. [self.view addSubview:self.photoBrowser.view];
  284. [self.photoBrowser didMoveToParentViewController:self];
  285. } else {
  286. [self.navigationController pushViewController:self.photoBrowser animated:NO];
  287. }
  288. }
  289. - (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
  290. {
  291. return [self.dataSourceImagesVideos count];
  292. }
  293. - (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index
  294. {
  295. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  296. NSString *titleDir = metadata.fileNameView;
  297. self.title = titleDir;
  298. return titleDir;
  299. }
  300. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
  301. {
  302. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  303. _indexNowVisible = index;
  304. _fileIDNowVisible = metadata.fileID;
  305. photoBrowser.toolbar.hidden = NO;
  306. // Download image ?
  307. if (metadata) {
  308. tableMetadata *metadataDB = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  309. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]] == NO && [metadataDB.session length] == 0)
  310. [self downloadPhotoBrowser:metadata];
  311. }
  312. // Title
  313. if (metadata)
  314. self.title = metadata.fileNameView;
  315. }
  316. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
  317. {
  318. UIImage *image;
  319. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  320. if (index < self.photos.count) {
  321. if (metadata.fileID) {
  322. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  323. NSString *fileImage = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  324. NSString *ext = [CCUtility getExtension:metadata.fileNameView];
  325. if ([ext isEqualToString:@"GIF"]) image = [UIImage animatedImageWithAnimatedGIFURL:[NSURL fileURLWithPath:fileImage]];
  326. else image = [UIImage imageWithContentsOfFile:fileImage];
  327. if (image) {
  328. MWPhoto *photo = [MWPhoto photoWithImage:image];
  329. // Location ??
  330. [self setLocationCaptionPhoto:photo fileID:metadata.fileID];
  331. [self.photos replaceObjectAtIndex:index withObject:photo];
  332. } else {
  333. if ([metadata.sessionError length] > 0 ) {
  334. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  335. }
  336. }
  337. }
  338. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  339. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  340. // remove and make the simbolic link in temp
  341. NSString *toPath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView];
  342. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  343. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:toPath error:nil];
  344. NSURL *url = [NSURL fileURLWithPath:toPath];
  345. MWPhoto *video = [MWPhoto photoWithImage:[CCGraphics thumbnailImageForVideo:url atTime:1.0]];
  346. video.videoURL = url;
  347. [self.photos replaceObjectAtIndex:index withObject:video];
  348. } else {
  349. if ([metadata.sessionError length] > 0 ) {
  350. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  351. }
  352. }
  353. }
  354. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) {
  355. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  356. MWPhoto *audio;
  357. UIImage *audioImage;
  358. // remove and make the simbolic link in temp
  359. NSString *toPath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView];
  360. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  361. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:toPath error:nil];
  362. NSURL *url = [NSURL fileURLWithPath:toPath];
  363. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  364. audioImage = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  365. } else {
  366. audioImage = [UIImage imageNamed:@"notaMusic"]; //[CCGraphics scaleImage:[UIImage imageNamed:@"notaMusic"] toSize:CGSizeMake(200, 200) isAspectRation:YES];
  367. }
  368. audio = [MWPhoto photoWithImage:audioImage];
  369. audio.videoURL = url;
  370. [self.photos replaceObjectAtIndex:index withObject:audio];
  371. } else {
  372. if ([metadata.sessionError length] > 0 ) {
  373. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  374. }
  375. }
  376. }
  377. }
  378. // energy saving memory
  379. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  380. int iPrev = (int)index - 2;
  381. if (iPrev >= 0) {
  382. if ([self.photos objectAtIndex:iPrev] != nil)
  383. [self.photos replaceObjectAtIndex:iPrev withObject:[MWPhoto photoWithImage:nil]];
  384. }
  385. int iNext = (int)index + 2;
  386. if (iNext < _photos.count) {
  387. if ([self.photos objectAtIndex:iNext] != nil)
  388. [self.photos replaceObjectAtIndex:iNext withObject:[MWPhoto photoWithImage:nil]];
  389. }
  390. });
  391. return [self.photos objectAtIndex:index];
  392. }
  393. return nil;
  394. }
  395. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index
  396. {
  397. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  398. if (metadata == nil) return;
  399. NSString *filePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNameView];
  400. [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
  401. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:filePath error:nil];
  402. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  403. self.docController.delegate = self;
  404. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  405. [self.docController presentOptionsMenuFromRect:photoBrowser.view.frame inView:photoBrowser.view animated:YES];
  406. [self.docController presentOptionsMenuFromBarButtonItem:photoBrowser.actionButton animated:YES];
  407. }
  408. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser shareButtonPressedForPhotoAtIndex:(NSUInteger)index
  409. {
  410. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  411. [app.activeMain openWindowShare:metadata];
  412. }
  413. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser deleteButtonPressedForPhotoAtIndex:(NSUInteger)index deleteButton:(UIBarButtonItem *)deleteButton
  414. {
  415. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  416. if (metadata == nil || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]] == NO) {
  417. [app messageNotification:@"_info_" description:@"_file_not_found_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  418. return;
  419. }
  420. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  421. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  422. style:UIAlertActionStyleDestructive
  423. handler:^(UIAlertAction *action) {
  424. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  425. }]];
  426. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  427. style:UIAlertActionStyleCancel
  428. handler:^(UIAlertAction *action) {
  429. [alertController dismissViewControllerAnimated:YES completion:nil];
  430. }]];
  431. alertController.popoverPresentationController.barButtonItem = deleteButton;
  432. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  433. [alertController.view layoutIfNeeded];
  434. [self.parentViewController presentViewController:alertController animated:YES completion:NULL];
  435. }
  436. - (void)triggerProgressTask:(NSNotification *)notification
  437. {
  438. NSDictionary *dict = notification.userInfo;
  439. NSString *fileID = [dict valueForKey:@"fileID"];
  440. //NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  441. float progress = [[dict valueForKey:@"progress"] floatValue];
  442. if ([fileID isEqualToString:_fileIDNowVisible])
  443. [_hud progress:progress];
  444. }
  445. - (void)downloadPhotoBrowserSuccessFailure:(tableMetadata *)metadata selector:(NSString *)selector errorCode:(NSInteger)errorCode
  446. {
  447. // if a message for a directory of these
  448. if (![metadata.fileID isEqualToString:_fileIDNowVisible])
  449. return;
  450. [_hud hideHud];
  451. if (errorCode == 0) {
  452. // verifico se esiste l'icona e se la posso creare
  453. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  454. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:app.directoryUser fileNameTo:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  455. } else {
  456. [app messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  457. }
  458. [self.photoBrowser reloadData];
  459. }
  460. - (void)downloadPhotoBrowser:(tableMetadata *)metadata
  461. {
  462. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  463. if (serverUrl) {
  464. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorLoadViewImage selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:app.activeMain];
  465. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeDeterminate color:[NCBrandColor sharedInstance].brand];
  466. }
  467. }
  468. - (void)insertGeocoderLocation:(NSNotification *)notification
  469. {
  470. if (notification.userInfo.count == 0)
  471. return;
  472. NSString *fileID = [[notification.userInfo allKeys] objectAtIndex:0];
  473. //NSDate *date = [[notification.userInfo allValues] objectAtIndex:0];
  474. // test [Chrash V 1.14,15]
  475. if (_indexNowVisible >= [self.photos count])
  476. return;
  477. if ([fileID isEqualToString:_fileIDNowVisible]) {
  478. MWPhoto *photo = [self.photos objectAtIndex:_indexNowVisible];
  479. [self setLocationCaptionPhoto:photo fileID:fileID];
  480. [self.photoBrowser reloadData];
  481. }
  482. }
  483. - (void)setLocationCaptionPhoto:(MWPhoto *)photo fileID:(NSString *)fileID
  484. {
  485. tableLocalFile *localFile;
  486. // read Geocoder
  487. localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  488. if ([localFile.exifLatitude doubleValue] != 0 || [localFile.exifLongitude doubleValue] != 0) {
  489. // Fix BUG Geo latitude & longitude
  490. if ([localFile.exifLatitude doubleValue] == 9999 || [localFile.exifLongitude doubleValue] == 9999) {
  491. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  492. if (metadata) {
  493. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata directoryUser:app.directoryUser activeAccount:app.activeAccount];
  494. }
  495. }
  496. [[CCExifGeo sharedInstance] setGeocoderEtag:fileID exifDate:localFile.exifDate latitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  497. localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  498. if ([localFile.exifLatitude floatValue] != 0 || [localFile.exifLongitude floatValue] != 0) {
  499. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  500. if ([localFile.exifDate isEqualToDate:[NSDate distantPast]] == NO && location) {
  501. NSString *localizedDateTime = [NSDateFormatter localizedStringFromDate:localFile.exifDate dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterMediumStyle];
  502. photo.caption = [NSString stringWithFormat:NSLocalizedString(@"%@\n%@", nil), localizedDateTime, location];
  503. }
  504. }
  505. }
  506. }
  507. #pragma --------------------------------------------------------------------------------------------
  508. #pragma mark ===== View PDF =====
  509. #pragma --------------------------------------------------------------------------------------------
  510. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  511. {
  512. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  513. [[alertView textFieldAtIndex:0] resignFirstResponder];
  514. if (alertView.tag == alertRequestPasswordPDF) [self performSelector:@selector(viewPDF:) withObject:[alertView textFieldAtIndex:0].text afterDelay:0.3];
  515. }
  516. - (void)viewPDF:(NSString *)password
  517. {
  518. NSString *fileName = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNameView];
  519. [[NSFileManager defaultManager] removeItemAtPath:fileName error:nil];
  520. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, self.metadataDetail.fileID] toPath:fileName error:nil];
  521. if ([[NSFileManager defaultManager] fileExistsAtPath:fileName isDirectory:nil] == NO) {
  522. // read file error
  523. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  524. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  525. [alertController addAction:okAction];
  526. [self presentViewController:alertController animated:YES completion:nil];
  527. }
  528. CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:fileName]);
  529. if (pdf) {
  530. // Encrypted
  531. if (CGPDFDocumentIsEncrypted(pdf) == YES) {
  532. // Try a blank password first, per Apple's Quartz PDF example
  533. if (CGPDFDocumentUnlockWithPassword(pdf, "") == YES) {
  534. // blank password
  535. [self readerPDF:fileName password:@""];
  536. } else {
  537. if ([password length] == 0) {
  538. // password request
  539. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_insert_password_pfd_",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  540. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  541. alertView.tag = alertRequestPasswordPDF;
  542. [alertView show];
  543. } else {
  544. const char *key = [password UTF8String];
  545. // failure
  546. if (CGPDFDocumentUnlockWithPassword(pdf, key) == NO) {
  547. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_password_pdf_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  548. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  549. [alertController addAction:okAction];
  550. [self presentViewController:alertController animated:YES completion:nil];
  551. } else {
  552. // pdf with password
  553. [self readerPDF:fileName password:password];
  554. }
  555. }
  556. }
  557. } else{
  558. // No password
  559. [self readerPDF:fileName password:@""];
  560. }
  561. } else {
  562. // read file error
  563. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  564. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  565. [alertController addAction:okAction];
  566. [self presentViewController:alertController animated:YES completion:nil];
  567. }
  568. }
  569. - (void)readerPDF:(NSString *)fileName password:(NSString *)password
  570. {
  571. ReaderDocument *documentPDF = [ReaderDocument withDocumentFilePath:fileName password:password];
  572. CGFloat safeAreaBottom = 0;
  573. if (@available(iOS 11, *)) {
  574. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  575. }
  576. if (documentPDF != nil) {
  577. self.readerPDFViewController = [[ReaderViewController alloc] initWithReaderDocument:documentPDF];
  578. self.readerPDFViewController.delegate = self;
  579. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  580. [self.readerPDFViewController updateContentViews];
  581. [self addChildViewController:self.readerPDFViewController];
  582. [self.view addSubview:self.readerPDFViewController.view];
  583. [self.readerPDFViewController didMoveToParentViewController:self];
  584. } else {
  585. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  586. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  587. [alertController addAction:okAction];
  588. [self presentViewController:alertController animated:YES completion:nil];
  589. }
  590. }
  591. - (void)handleSingleTapReader
  592. {
  593. UILayoutGuide *layoutGuide;
  594. CGFloat safeAreaTop = 0;
  595. CGFloat safeAreaBottom = 0;
  596. if (@available(iOS 11, *)) {
  597. layoutGuide = [UIApplication sharedApplication].delegate.window.safeAreaLayoutGuide;
  598. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  599. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  600. }
  601. self.navigationController.navigationBarHidden = !self.navigationController.navigationBarHidden;
  602. _toolbar.hidden = !_toolbar.isHidden;
  603. if (_toolbar.isHidden) {
  604. self.readerPDFViewController.view.frame = CGRectMake(0, safeAreaTop, self.view.bounds.size.width, self.view.bounds.size.height - safeAreaTop - safeAreaBottom);
  605. } else {
  606. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  607. }
  608. [self.readerPDFViewController updateContentViews];
  609. }
  610. #pragma --------------------------------------------------------------------------------------------
  611. #pragma mark ===== Delete =====
  612. #pragma --------------------------------------------------------------------------------------------
  613. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  614. {
  615. NSLog(@"[LOG] DeleteFileOrFolder failure error %lu, %@", (long)errorCode, message);
  616. }
  617. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  618. {
  619. // reload Main
  620. [app.activeMain reloadDatasource];
  621. // If removed document (web) or PDF close
  622. if (_webView || _readerPDFViewController)
  623. [self removeAllView];
  624. // if a message for a directory of these
  625. if (![_dataSourceDirectoryID containsObject:metadataNet.directoryID])
  626. return;
  627. // if we are not in browserPhoto and it's removed photo/video in preview then "< Back"
  628. if (!self.photoBrowser && [self.metadataDetail.fileID isEqualToString:metadataNet.fileID]) {
  629. NSArray *viewsToRemove = [self.view subviews];
  630. for (id element in viewsToRemove) {
  631. if ([element isMemberOfClass:[UIView class]] || [element isMemberOfClass:[UIToolbar class]])
  632. [element removeFromSuperview];
  633. }
  634. self.title = @"";
  635. [self.navigationController popViewControllerAnimated:YES];
  636. } else {
  637. // only photoBrowser if exists
  638. for (NSUInteger index=0; index < [self.dataSourceImagesVideos count] && _photoBrowser; index++ ) {
  639. tableMetadata *metadata = [self.dataSourceImagesVideos objectAtIndex:index];
  640. // ricerca index
  641. if ([metadata.fileID isEqualToString:metadataNet.fileID]) {
  642. [self.dataSourceImagesVideos removeObjectAtIndex:index];
  643. [self.photos removeObjectAtIndex:index];
  644. [self.photoBrowser reloadData];
  645. // Title
  646. if ([self.dataSourceImagesVideos count] == 0) {
  647. self.title = @"";
  648. [self.navigationController popViewControllerAnimated:YES];
  649. }
  650. break;
  651. }
  652. }
  653. }
  654. }
  655. #pragma --------------------------------------------------------------------------------------------
  656. #pragma mark ===== ButtonPressed =====
  657. #pragma --------------------------------------------------------------------------------------------
  658. - (void)modifyTxtButtonPressed:(UIBarButtonItem *)sender
  659. {
  660. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  661. NCText *viewController = (NCText *)navigationController.topViewController;
  662. viewController.metadata = self.metadataDetail;
  663. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  664. navigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  665. [self presentViewController:navigationController animated:YES completion:nil];
  666. }
  667. - (void)actionButtonPressed:(UIBarButtonItem *)sender
  668. {
  669. if ([self.metadataDetail.fileNameView length] == 0) return;
  670. NSString *filePath = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), self.metadataDetail.fileNameView];
  671. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  672. self.docController.delegate = self;
  673. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  674. [self.docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  675. [self.docController presentOptionsMenuFromBarButtonItem:sender animated:YES];
  676. }
  677. - (void)shareButtonPressed:(UIBarButtonItem *)sender
  678. {
  679. [app.activeMain openWindowShare:self.metadataDetail];
  680. }
  681. - (void)deleteButtonPressed:(UIBarButtonItem *)sender
  682. {
  683. if ([self.metadataDetail.fileNameView length] == 0) return;
  684. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  685. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  686. style:UIAlertActionStyleDestructive
  687. handler:^(UIAlertAction *action) {
  688. [[CCActions sharedInstance] deleteFileOrFolder:self.metadataDetail delegate:self];
  689. }]];
  690. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  691. style:UIAlertActionStyleCancel
  692. handler:^(UIAlertAction *action) {
  693. [alertController dismissViewControllerAnimated:YES completion:nil];
  694. }]];
  695. alertController.popoverPresentationController.barButtonItem = _buttonDelete;
  696. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  697. [alertController.view layoutIfNeeded];
  698. [self presentViewController:alertController animated:YES completion:NULL];
  699. }
  700. @end