CCDetail.m 52 KB

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