CCDetail.m 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  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 <KTVHTTPCache/KTVHTTPCache.h>
  28. #import "NCBridgeSwift.h"
  29. #define TOOLBAR_HEIGHT 49.0f
  30. #define alertRequestPasswordPDF 1
  31. @interface CCDetail () <NCTextDelegate>
  32. {
  33. AppDelegate *appDelegate;
  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. NSURL *videoURLProxy;
  43. NSURL *videoURL;
  44. }
  45. @end
  46. @implementation CCDetail
  47. #pragma --------------------------------------------------------------------------------------------
  48. #pragma mark ===== init =====
  49. #pragma --------------------------------------------------------------------------------------------
  50. - (id)initWithCoder:(NSCoder *)aDecoder
  51. {
  52. if (self = [super initWithCoder:aDecoder]) {
  53. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  54. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  55. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  56. self.metadataDetail = [[tableMetadata alloc] init];
  57. self.photos = [[NSMutableArray alloc] init];
  58. self.photoDataSource = [NSMutableArray new];
  59. dataSourceDirectoryID = [[NSMutableOrderedSet alloc] init];
  60. indexNowVisible = -1;
  61. fileIDNowVisible = nil;
  62. appDelegate.activeDetail = self;
  63. }
  64. return self;
  65. }
  66. #pragma --------------------------------------------------------------------------------------------
  67. #pragma mark ===== View =====
  68. #pragma --------------------------------------------------------------------------------------------
  69. - (void)viewDidLoad
  70. {
  71. [super viewDidLoad];
  72. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertGeocoderLocation:) name:@"insertGeocoderLocation" object:nil];
  73. self.imageBackground.image = [UIImage imageNamed:@"backgroundDetail"];
  74. // Proxy
  75. static dispatch_once_t onceToken;
  76. dispatch_once(&onceToken, ^{
  77. [self setupHTTPCache];
  78. });
  79. // Change bar bottom line shadow and remove title back button <"title"
  80. self.navigationController.navigationBar.shadowImage = [CCGraphics generateSinglePixelImageWithColor:[NCBrandColor sharedInstance].brand];
  81. self.navigationController.navigationBar.topItem.title = @"";
  82. // TabBar
  83. self.tabBarController.tabBar.hidden = YES;
  84. self.tabBarController.tabBar.translucent = YES;
  85. // Open View
  86. if ([self.metadataDetail.fileNameView length] > 0 || [self.metadataDetail.directoryID length] > 0 || [self.metadataDetail.fileID length] > 0) {
  87. // open view
  88. [self viewFile];
  89. }
  90. }
  91. - (void)viewWillAppear:(BOOL)animated
  92. {
  93. [super viewWillAppear:animated];
  94. self.tabBarController.tabBar.hidden = YES;
  95. self.tabBarController.tabBar.translucent = YES;
  96. }
  97. - (void)viewDidDisappear:(BOOL)animated
  98. {
  99. [super viewDidDisappear:animated];
  100. // If AVPlayer in play -> Stop
  101. if (appDelegate.player != nil && appDelegate.player.rate != 0) {
  102. [appDelegate.player pause];
  103. }
  104. }
  105. - (void)changeTheming
  106. {
  107. [appDelegate changeTheming:self];
  108. if (self.toolbar) {
  109. self.toolbar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  110. self.toolbar.tintColor = [NCBrandColor sharedInstance].brandElement;
  111. }
  112. }
  113. - (void)backNavigationController
  114. {
  115. [self.navigationController popViewControllerAnimated:YES];
  116. }
  117. - (void)changeToDisplayMode
  118. {
  119. if (_readerPDFViewController)
  120. [self.readerPDFViewController updateContentViews];
  121. }
  122. #pragma --------------------------------------------------------------------------------------------
  123. #pragma mark ===== View File =====
  124. #pragma --------------------------------------------------------------------------------------------
  125. - (void)viewFile
  126. {
  127. // verifico se esiste l'icona e se la posso creare
  128. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView]] == NO) {
  129. [CCGraphics createNewImageFrom:self.metadataDetail.fileNameView fileID:self.metadataDetail.fileID extension:[self.metadataDetail.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:self.metadataDetail.typeFile writeImage:YES];
  130. }
  131. // IMAGE
  132. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_image]) {
  133. self.edgesForExtendedLayout = UIRectEdgeAll;
  134. [self viewImage];
  135. }
  136. // AUDIO VIDEO
  137. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_audio]) {
  138. self.edgesForExtendedLayout = UIRectEdgeAll;
  139. [self createToolbar];
  140. [self viewMedia];
  141. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  142. }
  143. // DOCUMENT
  144. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_document]) {
  145. fileNameExtension = [[self.metadataDetail.fileNameView pathExtension] uppercaseString];
  146. if ([fileNameExtension isEqualToString:@"PDF"]) {
  147. self.edgesForExtendedLayout = UIRectEdgeBottom;
  148. [self createToolbar];
  149. [self viewPDF:@""];
  150. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  151. } else {
  152. self.edgesForExtendedLayout = UIRectEdgeBottom;
  153. [self createToolbar];
  154. [self viewDocument];
  155. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  156. }
  157. }
  158. self.title = _metadataDetail.fileNameView;
  159. }
  160. #pragma --------------------------------------------------------------------------------------------
  161. #pragma mark ===== Toolbar =====
  162. #pragma --------------------------------------------------------------------------------------------
  163. - (void)createToolbar
  164. {
  165. CGFloat safeAreaBottom = 0;
  166. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadataDetail.directoryID];
  167. if (!serverUrl)
  168. return;
  169. if (@available(iOS 11, *)) {
  170. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  171. }
  172. self.toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom, self.view.bounds.size.width, TOOLBAR_HEIGHT)];
  173. UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
  174. UIBarButtonItem *fixedSpaceMini = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
  175. fixedSpaceMini.width = 25;
  176. buttonModifyTxt = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"actionSheetModify"] style:UIBarButtonItemStylePlain target:self action:@selector(modifyTxtButtonPressed:)];
  177. buttonAction = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"openFile"] style:UIBarButtonItemStylePlain target:self action:@selector(actionButtonPressed:)];
  178. buttonShare = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share"] style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonPressed:)];
  179. buttonDelete = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteButtonPressed:)];
  180. if ([CCUtility isDocumentModifiableExtension:fileNameExtension]) {
  181. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) // E2EE
  182. [self.toolbar setItems:[NSArray arrayWithObjects: buttonModifyTxt, flexible, buttonDelete, fixedSpaceMini, buttonAction, nil]];
  183. else
  184. [self.toolbar setItems:[NSArray arrayWithObjects: buttonModifyTxt, flexible, buttonDelete, fixedSpaceMini, buttonShare, fixedSpaceMini, buttonAction, nil]];
  185. } else {
  186. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) // E2EE
  187. [self.toolbar setItems:[NSArray arrayWithObjects: flexible, buttonDelete, fixedSpaceMini, buttonAction, nil]];
  188. else
  189. [self.toolbar setItems:[NSArray arrayWithObjects: flexible, buttonDelete, fixedSpaceMini, buttonShare, fixedSpaceMini, buttonAction, nil]];
  190. }
  191. [self.toolbar setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  192. self.toolbar.barTintColor = [NCBrandColor sharedInstance].tabBar;
  193. self.toolbar.tintColor = [NCBrandColor sharedInstance].brandElement;
  194. [self.view addSubview:self.toolbar];
  195. }
  196. #pragma --------------------------------------------------------------------------------------------
  197. #pragma mark ===== View Document =====
  198. #pragma --------------------------------------------------------------------------------------------
  199. - (void)viewDocument
  200. {
  201. CGFloat safeAreaBottom = 0;
  202. if (@available(iOS 11, *)) {
  203. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  204. }
  205. if ([CCUtility fileProviderStorageExists:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView] == NO) {
  206. [self backNavigationController];
  207. return;
  208. }
  209. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNameView];
  210. [[NSFileManager defaultManager] removeItemAtPath:fileNamePath error:nil];
  211. [[NSFileManager defaultManager] linkItemAtPath:[CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView] toPath:fileNamePath error:nil];
  212. NSURL *url = [NSURL fileURLWithPath:fileNamePath];
  213. WKPreferences *wkPreferences = [[WKPreferences alloc] init];
  214. wkPreferences.javaScriptEnabled = true;
  215. WKWebViewConfiguration *wkConfig = [[WKWebViewConfiguration alloc] init];
  216. wkConfig.preferences = wkPreferences;
  217. self.webView = [[WKWebView alloc] initWithFrame:(CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom)) configuration:wkConfig];
  218. self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  219. [self.webView setBackgroundColor:[NCBrandColor sharedInstance].backgroundView];
  220. [self.webView setOpaque:NO];
  221. if ( [fileNameExtension isEqualToString:@"CSS"] || [fileNameExtension isEqualToString:@"PY"] || [fileNameExtension isEqualToString:@"XML"] || [fileNameExtension isEqualToString:@"JS"] ) {
  222. NSString *dataFile = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:url] encoding:NSASCIIStringEncoding];
  223. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
  224. [self.webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-size:%@;font-family:%@;'><pre>%@",@"40",@"Sans-Serif",dataFile] baseURL:nil];
  225. }else{
  226. [self.webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-size:%@;font-family:%@;'><pre>%@",@"20",@"Sans-Serif",dataFile] baseURL:nil];
  227. }
  228. } else if ([CCUtility isDocumentModifiableExtension:fileNameExtension]) {
  229. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  230. NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
  231. NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
  232. [headRequest setHTTPMethod:@"HEAD"];
  233. NSURLSessionDataTask *task = [session dataTaskWithRequest:headRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  234. dispatch_async(dispatch_get_main_queue(), ^{
  235. NSString *encodingName = [[NCUchardet sharedNUCharDet] encodingStringDetectWithData:data];
  236. [self.webView loadData:[NSData dataWithContentsOfURL: url] MIMEType:response.MIMEType characterEncodingName:encodingName baseURL:url];
  237. });
  238. }];
  239. [task resume];
  240. } else {
  241. [self.webView loadRequest:[NSMutableURLRequest requestWithURL:url]];
  242. }
  243. [self.view addSubview:self.webView];
  244. }
  245. #pragma --------------------------------------------------------------------------------------------
  246. #pragma mark ===== View Media =====
  247. #pragma --------------------------------------------------------------------------------------------
  248. - (void)viewMedia
  249. {
  250. CGFloat safeAreaBottom = 0;
  251. if (@available(iOS 11, *)) {
  252. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  253. }
  254. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadataDetail.directoryID];
  255. if (!serverUrl)
  256. return;
  257. if ([CCUtility fileProviderStorageExists:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView]) {
  258. videoURL = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView]];
  259. videoURLProxy = videoURL;
  260. } else {
  261. videoURL = [NSURL URLWithString:[[NSString stringWithFormat:@"%@/%@", serverUrl, _metadataDetail.fileName] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
  262. videoURLProxy = [KTVHTTPCache proxyURLWithOriginalURL:videoURL];
  263. NSMutableDictionary *header = [NSMutableDictionary new];
  264. NSData *authData = [[NSString stringWithFormat:@"%@:%@", appDelegate.activeUser, appDelegate.activePassword] dataUsingEncoding:NSUTF8StringEncoding];
  265. NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
  266. [header setValue:authValue forKey:@"Authorization"];
  267. [header setValue:[CCUtility getUserAgent] forKey:@"User-Agent"];
  268. [KTVHTTPCache downloadSetAdditionalHeaders:header];
  269. // Disable Button Action (the file is in download via Proxy Server)
  270. buttonAction.enabled = false;
  271. }
  272. appDelegate.player = [AVPlayer playerWithURL:videoURLProxy];
  273. appDelegate.playerController = [AVPlayerViewController new];
  274. appDelegate.playerController.player = appDelegate.player;
  275. appDelegate.playerController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  276. appDelegate.playerController.allowsPictureInPicturePlayback = false;
  277. [self addChildViewController:appDelegate.playerController];
  278. [self.view addSubview:appDelegate.playerController.view];
  279. [appDelegate.playerController didMoveToParentViewController:self];
  280. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:[appDelegate.player currentItem]];
  281. [appDelegate.player addObserver:self forKeyPath:@"rate" options:0 context:nil];
  282. [appDelegate.player play];
  283. }
  284. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  285. if ([keyPath isEqualToString:@"rate"]) {
  286. if ([appDelegate.player rate]) {
  287. NSLog(@"start");
  288. }
  289. else {
  290. NSLog(@"pause");
  291. }
  292. [self saveCacheToFileProvider];
  293. }
  294. }
  295. - (void)itemDidFinishPlaying:(NSNotification *)notification
  296. {
  297. AVPlayerItem *player = [notification object];
  298. [player seekToTime:kCMTimeZero];
  299. }
  300. - (void)saveCacheToFileProvider
  301. {
  302. if (![CCUtility fileProviderStorageExists:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView]) {
  303. NSURL *url = [KTVHTTPCache cacheCompleteFileURLIfExistedWithURL:videoURL];
  304. if (url) {
  305. [CCUtility copyFileAtPath:[url path] toPath:[CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView]];
  306. [[NCManageDatabase sharedInstance] addLocalFileWithMetadata:self.metadataDetail];
  307. [KTVHTTPCache cacheDeleteCacheWithURL:videoURL];
  308. // reload Main
  309. [appDelegate.activeMain reloadDatasource];
  310. // Enabled Button Action (the file is in local)
  311. buttonAction.enabled = true;
  312. }
  313. }
  314. }
  315. - (void)setupHTTPCache
  316. {
  317. [KTVHTTPCache cacheSetMaxCacheLength:k_maxHTTPCache];
  318. #if TARGET_IPHONE_SIMULATOR
  319. [KTVHTTPCache logSetConsoleLogEnable:YES];
  320. #endif
  321. NSError * error;
  322. [KTVHTTPCache proxyStart:&error];
  323. if (error) {
  324. NSLog(@"Proxy Start Failure, %@", error);
  325. } else {
  326. NSLog(@"Proxy Start Success");
  327. }
  328. [KTVHTTPCache tokenSetURLFilter:^NSURL * (NSURL * URL) {
  329. NSLog(@"URL Filter reviced URL : %@", URL);
  330. return URL;
  331. }];
  332. [KTVHTTPCache downloadSetUnsupportContentTypeFilter:^BOOL(NSURL * URL, NSString * contentType) {
  333. NSLog(@"Unsupport Content-Type Filter reviced URL : %@, %@", URL, contentType);
  334. return NO;
  335. }];
  336. }
  337. #pragma --------------------------------------------------------------------------------------------
  338. #pragma mark ===== View Image =====
  339. #pragma --------------------------------------------------------------------------------------------
  340. - (void)viewImage
  341. {
  342. self.photoBrowser = [[MWPhotoBrowser alloc] initWithDelegate:self];
  343. indexNowVisible = -1;
  344. fileIDNowVisible = nil;
  345. [self.photos removeAllObjects];
  346. [dataSourceDirectoryID removeAllObjects];
  347. // if not images, exit
  348. if ([self.photoDataSource count] == 0)
  349. return;
  350. // test
  351. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadataDetail.directoryID];
  352. if (!serverUrl)
  353. return;
  354. NSUInteger index = 0;
  355. for (tableMetadata *metadata in self.photoDataSource) {
  356. // start from here ?
  357. if (self.metadataDetail.fileID && [metadata.fileID isEqualToString:self.metadataDetail.fileID])
  358. [self.photoBrowser setCurrentPhotoIndex:index];
  359. [self.photos addObject:[MWPhoto photoWithImage:nil]];
  360. // add directory
  361. [dataSourceDirectoryID addObject:metadata.directoryID];
  362. index++;
  363. }
  364. // PhotoBrowser
  365. self.photoBrowser.displayActionButton = YES;
  366. self.photoBrowser.displayDeleteButton = YES;
  367. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) // E2EE
  368. self.photoBrowser.displayShareButton = NO;
  369. else
  370. self.photoBrowser.displayShareButton = YES;
  371. self.photoBrowser.displayNavArrows = YES;
  372. self.photoBrowser.displaySelectionButtons = NO;
  373. self.photoBrowser.alwaysShowControls = NO;
  374. self.photoBrowser.zoomPhotosToFill = NO;
  375. self.photoBrowser.autoPlayOnAppear = NO;
  376. self.photoBrowser.delayToHideElements = 15;
  377. if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)
  378. self.photoBrowser.enableSwipeToDismiss = NO;
  379. if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
  380. [self addChildViewController:self.photoBrowser];
  381. [self.view addSubview:self.photoBrowser.view];
  382. [self.photoBrowser didMoveToParentViewController:self];
  383. } else {
  384. [self.navigationController pushViewController:self.photoBrowser animated:NO];
  385. }
  386. }
  387. - (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
  388. {
  389. return [self.photoDataSource count];
  390. }
  391. - (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index
  392. {
  393. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  394. NSString *titleDir = metadata.fileNameView;
  395. self.title = titleDir;
  396. return titleDir;
  397. }
  398. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
  399. {
  400. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  401. indexNowVisible = index;
  402. fileIDNowVisible = metadata.fileID;
  403. photoBrowser.toolbar.hidden = NO;
  404. // Download image ?
  405. if (metadata) {
  406. tableMetadata *metadataDB = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  407. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView] == NO && metadataDB.status == k_metadataStatusNormal) {
  408. [self downloadPhotoBrowser:metadata];
  409. }
  410. }
  411. // Title
  412. if (metadata)
  413. self.title = metadata.fileNameView;
  414. }
  415. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
  416. {
  417. UIImage *image;
  418. // UIImage *loadingGIF = [UIImage animatedImageWithAnimatedGIFURL:[[NSBundle mainBundle] URLForResource:@"loading" withExtension:@"gif"]];
  419. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  420. if (index < self.photos.count) {
  421. if (metadata.fileID) {
  422. UIImage *imagePreview = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  423. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  424. if (!imagePreview) imagePreview = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"file_photo"] multiplier:3 color:[[NCBrandColor sharedInstance] icon]];
  425. NSString *fileImage = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView];
  426. NSString *ext = [CCUtility getExtension:metadata.fileNameView];
  427. if ([ext isEqualToString:@"GIF"]) image = [UIImage animatedImageWithAnimatedGIFURL:[NSURL fileURLWithPath:fileImage]];
  428. else image = [UIImage imageWithContentsOfFile:fileImage];
  429. if (image) {
  430. MWPhoto *photo = [MWPhoto photoWithImage:image];
  431. // Location ??
  432. [self setLocationCaptionPhoto:photo fileID:metadata.fileID];
  433. [self.photos replaceObjectAtIndex:index withObject:photo];
  434. } else {
  435. if (metadata.status == k_metadataStatusDownloadError) {
  436. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  437. } else {
  438. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:imagePreview]];
  439. }
  440. }
  441. }
  442. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  443. if (!imagePreview) imagePreview = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"file_photo"] multiplier:3 color:[[NCBrandColor sharedInstance] icon]];
  444. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  445. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]];
  446. MWPhoto *video = [MWPhoto photoWithImage:[CCGraphics thumbnailImageForVideo:url atTime:1.0]];
  447. video.videoURL = url;
  448. [self.photos replaceObjectAtIndex:index withObject:video];
  449. } else {
  450. if (metadata.status == k_metadataStatusDownloadError) {
  451. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  452. } else {
  453. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:imagePreview]];
  454. }
  455. }
  456. }
  457. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) {
  458. if (!imagePreview) imagePreview = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"file_audio"] multiplier:3 color:[[NCBrandColor sharedInstance] icon]];
  459. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  460. MWPhoto *audio;
  461. UIImage *audioImage;
  462. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]];
  463. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]) {
  464. audioImage = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  465. } else {
  466. audioImage = [UIImage imageNamed:@"notaMusic"]; //[CCGraphics scaleImage:[UIImage imageNamed:@"notaMusic"] toSize:CGSizeMake(200, 200) isAspectRation:YES];
  467. }
  468. audio = [MWPhoto photoWithImage:audioImage];
  469. audio.videoURL = url;
  470. [self.photos replaceObjectAtIndex:index withObject:audio];
  471. } else {
  472. if (metadata.status == k_metadataStatusDownloadError) {
  473. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  474. } else {
  475. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:imagePreview]];
  476. }
  477. }
  478. }
  479. }
  480. // energy saving memory
  481. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  482. int iPrev = (int)index - 2;
  483. if (iPrev >= 0) {
  484. if ([self.photos objectAtIndex:iPrev] != nil)
  485. [self.photos replaceObjectAtIndex:iPrev withObject:[MWPhoto photoWithImage:nil]];
  486. }
  487. int iNext = (int)index + 2;
  488. if (iNext < _photos.count) {
  489. if ([self.photos objectAtIndex:iNext] != nil)
  490. [self.photos replaceObjectAtIndex:iNext withObject:[MWPhoto photoWithImage:nil]];
  491. }
  492. });
  493. return [self.photos objectAtIndex:index];
  494. }
  495. return nil;
  496. }
  497. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index
  498. {
  499. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  500. if (metadata == nil) return;
  501. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView]]];
  502. self.docController.delegate = self;
  503. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  504. [self.docController presentOptionsMenuFromRect:photoBrowser.view.frame inView:photoBrowser.view animated:YES];
  505. [self.docController presentOptionsMenuFromBarButtonItem:photoBrowser.actionButton animated:YES];
  506. }
  507. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser shareButtonPressedForPhotoAtIndex:(NSUInteger)index
  508. {
  509. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  510. [appDelegate.activeMain openWindowShare:metadata];
  511. }
  512. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser deleteButtonPressedForPhotoAtIndex:(NSUInteger)index deleteButton:(UIBarButtonItem *)deleteButton
  513. {
  514. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  515. if (metadata == nil || [CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView] == NO) {
  516. [appDelegate messageNotification:@"_info_" description:@"_file_not_found_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  517. return;
  518. }
  519. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  520. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  521. style:UIAlertActionStyleDestructive
  522. handler:^(UIAlertAction *action) {
  523. [self deleteFile:metadata];
  524. }]];
  525. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  526. style:UIAlertActionStyleCancel
  527. handler:^(UIAlertAction *action) {
  528. }]];
  529. alertController.popoverPresentationController.barButtonItem = deleteButton;
  530. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  531. [alertController.view layoutIfNeeded];
  532. [self.parentViewController presentViewController:alertController animated:YES completion:NULL];
  533. }
  534. - (void)photoBrowserDidFinishPresentation:(MWPhotoBrowser *)photoBrowser
  535. {
  536. [self.navigationController popViewControllerAnimated:YES];
  537. }
  538. - (void)triggerProgressTask:(NSNotification *)notification
  539. {
  540. /*
  541. NSDictionary *dict = notification.userInfo;
  542. NSString *fileID = [dict valueForKey:@"fileID"];
  543. //NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  544. //long status = [[dict valueForKey:@"status"] longValue];
  545. float progress = [[dict valueForKey:@"progress"] floatValue];
  546. //long long totalBytes = [[dict valueForKey:@"totalBytes"] longLongValue];
  547. //long long totalBytesExpected = [[dict valueForKey:@"totalBytesExpected"] longLongValue];
  548. if ([fileID isEqualToString:_fileIDNowVisible])
  549. [_hud progress:progress];
  550. */
  551. }
  552. - (void)downloadPhotoBrowserSuccessFailure:(tableMetadata *)metadata selector:(NSString *)selector errorCode:(NSInteger)errorCode
  553. {
  554. // if a message for a directory of these
  555. if (![metadata.fileID isEqualToString:fileIDNowVisible])
  556. return;
  557. // Title
  558. self.navigationItem.titleView = nil;
  559. self.title = metadata.fileNameView;
  560. if (errorCode == 0) {
  561. // verifico se esiste l'icona e se la posso creare
  562. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO)
  563. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writeImage:YES];
  564. [self.photoBrowser reloadData];
  565. } else {
  566. [appDelegate messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  567. [self backNavigationController];
  568. }
  569. }
  570. - (void)downloadPhotoBrowser:(tableMetadata *)metadata
  571. {
  572. tableMetadata *metadataForUpload = [[NCManageDatabase sharedInstance] initNewMetadata:metadata];
  573. metadataForUpload.session = k_download_session;
  574. metadataForUpload.sessionError = @"";
  575. metadataForUpload.sessionSelector = selectorLoadViewImage;
  576. metadataForUpload.status = k_metadataStatusWaitDownload;
  577. // Add Metadata for Download
  578. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  579. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  580. [CCGraphics addImageToTitle:NSLocalizedString(@"_...loading..._", nil) colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"load"] multiplier:2 color:[NCBrandColor sharedInstance].brandText] navigationItem:self.navigationItem];
  581. }
  582. - (void)insertGeocoderLocation:(NSNotification *)notification
  583. {
  584. if (notification.userInfo.count == 0)
  585. return;
  586. NSString *fileID = [[notification.userInfo allKeys] objectAtIndex:0];
  587. //NSDate *date = [[notification.userInfo allValues] objectAtIndex:0];
  588. // test [Chrash V 1.14,15]
  589. if (indexNowVisible >= [self.photos count])
  590. return;
  591. if ([fileID isEqualToString:fileIDNowVisible]) {
  592. MWPhoto *photo = [self.photos objectAtIndex:indexNowVisible];
  593. [self setLocationCaptionPhoto:photo fileID:fileID];
  594. [self.photoBrowser reloadData];
  595. }
  596. }
  597. - (void)setLocationCaptionPhoto:(MWPhoto *)photo fileID:(NSString *)fileID
  598. {
  599. tableLocalFile *localFile;
  600. // read Geocoder
  601. localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  602. if ([localFile.exifLatitude doubleValue] != 0 || [localFile.exifLongitude doubleValue] != 0) {
  603. // Fix BUG Geo latitude & longitude
  604. if ([localFile.exifLatitude doubleValue] == 9999 || [localFile.exifLongitude doubleValue] == 9999) {
  605. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  606. if (metadata) {
  607. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  608. }
  609. }
  610. [[CCExifGeo sharedInstance] setGeocoderEtag:fileID exifDate:localFile.exifDate latitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  611. localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  612. if ([localFile.exifLatitude floatValue] != 0 || [localFile.exifLongitude floatValue] != 0) {
  613. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  614. if ([localFile.exifDate isEqualToDate:[NSDate distantPast]] == NO && location) {
  615. NSString *localizedDateTime = [NSDateFormatter localizedStringFromDate:localFile.exifDate dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterMediumStyle];
  616. photo.caption = [NSString stringWithFormat:NSLocalizedString(@"%@\n%@", nil), localizedDateTime, location];
  617. }
  618. }
  619. }
  620. }
  621. #pragma --------------------------------------------------------------------------------------------
  622. #pragma mark ===== View PDF =====
  623. #pragma --------------------------------------------------------------------------------------------
  624. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  625. {
  626. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  627. [[alertView textFieldAtIndex:0] resignFirstResponder];
  628. if (alertView.tag == alertRequestPasswordPDF) [self performSelector:@selector(viewPDF:) withObject:[alertView textFieldAtIndex:0].text afterDelay:0.3];
  629. }
  630. - (void)viewPDF:(NSString *)password
  631. {
  632. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView];
  633. if ([CCUtility fileProviderStorageExists:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView] == NO) {
  634. // read file error
  635. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  636. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  637. [alertController addAction:okAction];
  638. [self presentViewController:alertController animated:YES completion:nil];
  639. }
  640. CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:fileNamePath]);
  641. if (pdf) {
  642. // Encrypted
  643. if (CGPDFDocumentIsEncrypted(pdf) == YES) {
  644. // Try a blank password first, per Apple's Quartz PDF example
  645. if (CGPDFDocumentUnlockWithPassword(pdf, "") == YES) {
  646. // blank password
  647. [self readerPDF:fileNamePath password:@""];
  648. } else {
  649. if ([password length] == 0) {
  650. // password request
  651. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_insert_password_pfd_",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  652. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  653. alertView.tag = alertRequestPasswordPDF;
  654. [alertView show];
  655. } else {
  656. const char *key = [password UTF8String];
  657. // failure
  658. if (CGPDFDocumentUnlockWithPassword(pdf, key) == NO) {
  659. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_password_pdf_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  660. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  661. [alertController addAction:okAction];
  662. [self presentViewController:alertController animated:YES completion:nil];
  663. } else {
  664. // pdf with password
  665. [self readerPDF:fileNamePath password:password];
  666. }
  667. }
  668. }
  669. } else{
  670. // No password
  671. [self readerPDF:fileNamePath password:@""];
  672. }
  673. } else {
  674. // read file error
  675. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  676. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  677. [alertController addAction:okAction];
  678. [self presentViewController:alertController animated:YES completion:nil];
  679. }
  680. }
  681. - (void)readerPDF:(NSString *)fileName password:(NSString *)password
  682. {
  683. ReaderDocument *documentPDF = [ReaderDocument withDocumentFilePath:fileName password:password];
  684. CGFloat safeAreaBottom = 0;
  685. if (@available(iOS 11, *)) {
  686. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  687. }
  688. if (documentPDF != nil) {
  689. self.readerPDFViewController = [[ReaderViewController alloc] initWithReaderDocument:documentPDF];
  690. self.readerPDFViewController.delegate = self;
  691. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  692. [self.readerPDFViewController updateContentViews];
  693. [self addChildViewController:self.readerPDFViewController];
  694. [self.view addSubview:self.readerPDFViewController.view];
  695. [self.readerPDFViewController didMoveToParentViewController:self];
  696. } else {
  697. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  698. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  699. [alertController addAction:okAction];
  700. [self presentViewController:alertController animated:YES completion:nil];
  701. }
  702. }
  703. - (void)handleSingleTapReader
  704. {
  705. UILayoutGuide *layoutGuide;
  706. CGFloat safeAreaTop = 0;
  707. CGFloat safeAreaBottom = 0;
  708. if (@available(iOS 11, *)) {
  709. layoutGuide = [UIApplication sharedApplication].delegate.window.safeAreaLayoutGuide;
  710. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  711. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  712. }
  713. self.navigationController.navigationBarHidden = !self.navigationController.navigationBarHidden;
  714. self.toolbar.hidden = !self.toolbar.isHidden;
  715. if (self.toolbar.isHidden) {
  716. self.readerPDFViewController.view.frame = CGRectMake(0, safeAreaTop, self.view.bounds.size.width, self.view.bounds.size.height - safeAreaTop - safeAreaBottom);
  717. } else {
  718. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  719. }
  720. [self.readerPDFViewController updateContentViews];
  721. }
  722. - (void)handleSwipeUpDown
  723. {
  724. // REMOVE IT'S UNUSABLE
  725. /*
  726. self.navigationController.navigationBarHidden = false; // iOS App is unusable after swipe up or down with PDF in fullscreen #526
  727. [self removeAllView];
  728. [self.navigationController popViewControllerAnimated:YES];
  729. */
  730. }
  731. #pragma --------------------------------------------------------------------------------------------
  732. #pragma mark ===== Delete =====
  733. #pragma --------------------------------------------------------------------------------------------
  734. - (void)deleteFile:(tableMetadata *)metadata
  735. {
  736. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  737. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND e2eEncrypted == 1 AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  738. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:[[NSArray alloc] initWithObjects:metadata, nil] e2ee:tableDirectory.e2eEncrypted serverUrl:serverUrl folderFileID:tableDirectory.fileID completion:^(NSInteger errorCode, NSString *message) {
  739. if (errorCode == 0) {
  740. // reload Main
  741. [appDelegate.activeMain reloadDatasource];
  742. // Not image
  743. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_image] == NO) {
  744. // exit
  745. [self backNavigationController];
  746. } else {
  747. for (NSUInteger index=0; index < [self.photoDataSource count] && _photoBrowser; index++ ) {
  748. tableMetadata *metadataTemp = [self.photoDataSource objectAtIndex:index];
  749. if ([metadata isInvalidated] || [metadataTemp.fileID isEqualToString:metadata.fileID]) {
  750. [self.photoDataSource removeObjectAtIndex:index];
  751. [self.photos removeObjectAtIndex:index];
  752. [self.photoBrowser reloadData];
  753. // exit
  754. if ([self.photoDataSource count] == 0) {
  755. [self backNavigationController];
  756. }
  757. }
  758. }
  759. }
  760. } else {
  761. NSLog(@"[LOG] DeleteFileOrFolder failure error %d, %@", (int)errorCode, message);
  762. }
  763. }];
  764. }
  765. #pragma --------------------------------------------------------------------------------------------
  766. #pragma mark ===== ButtonPressed =====
  767. #pragma --------------------------------------------------------------------------------------------
  768. - (void)dismissTextView
  769. {
  770. if (self.webView) {
  771. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNameView];
  772. [[NSFileManager defaultManager] removeItemAtPath:fileNamePath error:nil];
  773. [[NSFileManager defaultManager] linkItemAtPath:[CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView] toPath:fileNamePath error:nil];
  774. [self.webView reload];
  775. }
  776. }
  777. - (void)modifyTxtButtonPressed:(UIBarButtonItem *)sender
  778. {
  779. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", self.metadataDetail.fileID]];
  780. if (metadata) {
  781. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  782. NCText *viewController = (NCText *)navigationController.topViewController;
  783. viewController.metadata = metadata;
  784. viewController.delegate = self;
  785. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  786. navigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  787. [self presentViewController:navigationController animated:YES completion:nil];
  788. }
  789. }
  790. - (void)actionButtonPressed:(UIBarButtonItem *)sender
  791. {
  792. if ([self.metadataDetail.fileNameView length] == 0) return;
  793. NSString *filePath = [CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileName:self.metadataDetail.fileNameView];
  794. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  795. self.docController.delegate = self;
  796. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  797. [self.docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  798. [self.docController presentOptionsMenuFromBarButtonItem:sender animated:YES];
  799. }
  800. - (void)shareButtonPressed:(UIBarButtonItem *)sender
  801. {
  802. [appDelegate.activeMain openWindowShare:self.metadataDetail];
  803. }
  804. - (void)deleteButtonPressed:(UIBarButtonItem *)sender
  805. {
  806. if ([self.metadataDetail.fileNameView length] == 0) return;
  807. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  808. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  809. style:UIAlertActionStyleDestructive
  810. handler:^(UIAlertAction *action) {
  811. [self deleteFile:self.metadataDetail];
  812. }]];
  813. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  814. style:UIAlertActionStyleCancel
  815. handler:^(UIAlertAction *action) {
  816. [alertController dismissViewControllerAnimated:YES completion:nil];
  817. }]];
  818. alertController.popoverPresentationController.barButtonItem = buttonDelete;
  819. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  820. [alertController.view layoutIfNeeded];
  821. [self presentViewController:alertController animated:YES completion:NULL];
  822. }
  823. @end