CCDetail.m 50 KB

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