CCDetail.m 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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 Data Source
  324. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:self.metadataDetail.directoryID] fileID:self.metadataDetail.fileID action:k_action_MOD];
  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. NSInteger status;
  422. tableMetadata *metadataDB = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  423. if (metadataDB) {
  424. status = metadataDB.status;
  425. } else {
  426. status = k_metadataStatusNormal;
  427. }
  428. NSString *ext = [[metadata.fileNameView pathExtension] uppercaseString];
  429. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView] == NO && status == k_metadataStatusNormal) {
  430. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO) {
  431. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  432. [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];
  433. CGFloat width = [[NCUtility sharedInstance] getScreenWidthForPreview];
  434. CGFloat height = [[NCUtility sharedInstance] getScreenHeightForPreview];
  435. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  436. [ocNetworking downloadPreviewWithMetadata:metadata serverUrl:serverUrl withWidth:width andHeight:height completion:^(NSString *message, NSInteger errorCode) {
  437. self.navigationItem.titleView = nil;
  438. self.title = metadata.fileNameView;
  439. if (([CCUtility getOptimizedPhoto] == YES && errorCode != 0) || [CCUtility getOptimizedPhoto] == NO || [ext isEqualToString:@"GIF"]) {
  440. [self downloadPhotoBrowser:metadata];
  441. }
  442. [self.photoBrowser reloadData];
  443. }];
  444. } else {
  445. if ([CCUtility getOptimizedPhoto] == NO || [ext isEqualToString:@"GIF"]) {
  446. [self downloadPhotoBrowser:metadata];
  447. }
  448. }
  449. }
  450. }
  451. // Title
  452. if (metadata)
  453. self.title = metadata.fileNameView;
  454. }
  455. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
  456. {
  457. UIImage *image;
  458. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  459. if (index < self.photos.count) {
  460. if (metadata.fileID) {
  461. UIImage *imagePreview = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  462. // if (!imagePreview) imagePreview = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"file_photo"] multiplier:3 color:[[NCBrandColor sharedInstance] icon]];
  463. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  464. NSString *fileImage = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView];
  465. NSString *ext = [CCUtility getExtension:metadata.fileNameView];
  466. if ([ext isEqualToString:@"GIF"]) image = [UIImage animatedImageWithAnimatedGIFURL:[NSURL fileURLWithPath:fileImage]];
  467. else image = [UIImage imageWithContentsOfFile:fileImage];
  468. if (image) {
  469. MWPhoto *photo = [MWPhoto photoWithImage:image];
  470. // Location ??
  471. [self setLocationCaptionPhoto:photo fileID:metadata.fileID];
  472. [self.photos replaceObjectAtIndex:index withObject:photo];
  473. } else {
  474. if (metadata.status == k_metadataStatusDownloadError) {
  475. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  476. } else {
  477. if (imagePreview)
  478. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:imagePreview]];
  479. }
  480. }
  481. }
  482. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  483. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  484. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  485. MWPhoto *video = [MWPhoto photoWithImage:[CCGraphics thumbnailImageForVideo:url atTime:1.0]];
  486. video.videoURL = url;
  487. [self.photos replaceObjectAtIndex:index withObject:video];
  488. } else {
  489. if (metadata.status == k_metadataStatusDownloadError) {
  490. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  491. } else {
  492. if (imagePreview)
  493. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:imagePreview]];
  494. }
  495. }
  496. }
  497. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_audio]) {
  498. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  499. MWPhoto *audio;
  500. UIImage *audioImage;
  501. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  502. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]) {
  503. audioImage = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  504. } else {
  505. audioImage = [UIImage imageNamed:@"notaMusic"]; //[CCGraphics scaleImage:[UIImage imageNamed:@"notaMusic"] toSize:CGSizeMake(200, 200) isAspectRation:YES];
  506. }
  507. audio = [MWPhoto photoWithImage:audioImage];
  508. audio.videoURL = url;
  509. [self.photos replaceObjectAtIndex:index withObject:audio];
  510. } else {
  511. if (metadata.status == k_metadataStatusDownloadError) {
  512. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:[UIImage imageNamed:@"filePreviewError"]]];
  513. } else {
  514. if (imagePreview)
  515. [self.photos replaceObjectAtIndex:index withObject:[MWPhoto photoWithImage:imagePreview]];
  516. }
  517. }
  518. }
  519. }
  520. // energy saving memory
  521. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  522. int iPrev = (int)index - 2;
  523. if (iPrev >= 0) {
  524. if ([self.photos objectAtIndex:iPrev] != nil)
  525. [self.photos replaceObjectAtIndex:iPrev withObject:[MWPhoto photoWithImage:nil]];
  526. }
  527. int iNext = (int)index + 2;
  528. if (iNext < _photos.count) {
  529. if ([self.photos objectAtIndex:iNext] != nil)
  530. [self.photos replaceObjectAtIndex:iNext withObject:[MWPhoto photoWithImage:nil]];
  531. }
  532. });
  533. return [self.photos objectAtIndex:index];
  534. }
  535. return nil;
  536. }
  537. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index
  538. {
  539. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  540. if (metadata == nil) return;
  541. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]]];
  542. self.docController.delegate = self;
  543. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  544. [self.docController presentOptionsMenuFromRect:photoBrowser.view.frame inView:photoBrowser.view animated:YES];
  545. [self.docController presentOptionsMenuFromBarButtonItem:photoBrowser.actionButton animated:YES];
  546. }
  547. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser shareButtonPressedForPhotoAtIndex:(NSUInteger)index
  548. {
  549. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  550. [appDelegate.activeMain openWindowShare:metadata];
  551. }
  552. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser deleteButtonPressedForPhotoAtIndex:(NSUInteger)index deleteButton:(UIBarButtonItem *)deleteButton
  553. {
  554. tableMetadata *metadata = [self.photoDataSource objectAtIndex:index];
  555. if (metadata == nil || [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView] == NO) {
  556. [appDelegate messageNotification:@"_info_" description:@"_file_not_found_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  557. return;
  558. }
  559. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  560. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  561. style:UIAlertActionStyleDestructive
  562. handler:^(UIAlertAction *action) {
  563. [self deleteFile:metadata];
  564. }]];
  565. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  566. style:UIAlertActionStyleCancel
  567. handler:^(UIAlertAction *action) {
  568. }]];
  569. alertController.popoverPresentationController.barButtonItem = deleteButton;
  570. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  571. [alertController.view layoutIfNeeded];
  572. [self.parentViewController presentViewController:alertController animated:YES completion:NULL];
  573. }
  574. - (void)photoBrowserDidFinishPresentation:(MWPhotoBrowser *)photoBrowser
  575. {
  576. [self.navigationController popViewControllerAnimated:YES];
  577. }
  578. - (void)triggerProgressTask:(NSNotification *)notification
  579. {
  580. /*
  581. NSDictionary *dict = notification.userInfo;
  582. NSString *fileID = [dict valueForKey:@"fileID"];
  583. //NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  584. //long status = [[dict valueForKey:@"status"] longValue];
  585. float progress = [[dict valueForKey:@"progress"] floatValue];
  586. //long long totalBytes = [[dict valueForKey:@"totalBytes"] longLongValue];
  587. //long long totalBytesExpected = [[dict valueForKey:@"totalBytesExpected"] longLongValue];
  588. if ([fileID isEqualToString:_fileIDNowVisible])
  589. [_hud progress:progress];
  590. */
  591. }
  592. - (void)downloadPhotoBrowserSuccessFailure:(tableMetadata *)metadata selector:(NSString *)selector errorCode:(NSInteger)errorCode
  593. {
  594. // if a message for a directory of these
  595. if (![metadata.fileID isEqualToString:fileIDNowVisible])
  596. return;
  597. // Title
  598. self.navigationItem.titleView = nil;
  599. self.title = metadata.fileNameView;
  600. if (errorCode == 0) {
  601. // verifico se esiste l'icona e se la posso creare
  602. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] == NO) {
  603. [CCGraphics createNewImageFrom:metadata.fileNameView fileID:metadata.fileID extension:[metadata.fileNameView pathExtension] size:@"m" imageForUpload:NO typeFile:metadata.typeFile writeImage:YES];
  604. }
  605. [self.photoBrowser reloadData];
  606. } else {
  607. [appDelegate messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  608. [self backNavigationController];
  609. }
  610. }
  611. - (void)downloadPhotoBrowser:(tableMetadata *)metadata
  612. {
  613. tableMetadata *metadataForDownload = [[NCManageDatabase sharedInstance] initNewMetadata:metadata];
  614. metadataForDownload.session = k_download_session;
  615. metadataForDownload.sessionError = @"";
  616. metadataForDownload.sessionSelector = selectorLoadViewImage;
  617. metadataForDownload.status = k_metadataStatusWaitDownload;
  618. // Add Metadata for Download
  619. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForDownload];
  620. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  621. [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];
  622. }
  623. - (void)insertGeocoderLocation:(NSNotification *)notification
  624. {
  625. if (notification.userInfo.count == 0)
  626. return;
  627. NSString *fileID = [[notification.userInfo allKeys] objectAtIndex:0];
  628. //NSDate *date = [[notification.userInfo allValues] objectAtIndex:0];
  629. // test [Chrash V 1.14,15]
  630. if (indexNowVisible >= [self.photos count])
  631. return;
  632. if ([fileID isEqualToString:fileIDNowVisible]) {
  633. MWPhoto *photo = [self.photos objectAtIndex:indexNowVisible];
  634. [self setLocationCaptionPhoto:photo fileID:fileID];
  635. [self.photoBrowser reloadData];
  636. }
  637. }
  638. - (void)setLocationCaptionPhoto:(MWPhoto *)photo fileID:(NSString *)fileID
  639. {
  640. tableLocalFile *localFile;
  641. // read Geocoder
  642. localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  643. if ([localFile.exifLatitude doubleValue] != 0 || [localFile.exifLongitude doubleValue] != 0) {
  644. // Fix BUG Geo latitude & longitude
  645. if ([localFile.exifLatitude doubleValue] == 9999 || [localFile.exifLongitude doubleValue] == 9999) {
  646. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  647. if (metadata) {
  648. [[CCExifGeo sharedInstance] setExifLocalTableEtag:metadata];
  649. }
  650. }
  651. [[CCExifGeo sharedInstance] setGeocoderEtag:fileID exifDate:localFile.exifDate latitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  652. localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  653. if ([localFile.exifLatitude floatValue] != 0 || [localFile.exifLongitude floatValue] != 0) {
  654. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  655. if ([localFile.exifDate isEqualToDate:[NSDate distantPast]] == NO && location) {
  656. NSString *localizedDateTime = [NSDateFormatter localizedStringFromDate:localFile.exifDate dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterMediumStyle];
  657. photo.caption = [NSString stringWithFormat:NSLocalizedString(@"%@\n%@", nil), localizedDateTime, location];
  658. }
  659. }
  660. }
  661. }
  662. #pragma --------------------------------------------------------------------------------------------
  663. #pragma mark ===== View PDF =====
  664. #pragma --------------------------------------------------------------------------------------------
  665. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  666. {
  667. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  668. [[alertView textFieldAtIndex:0] resignFirstResponder];
  669. if (alertView.tag == alertRequestPasswordPDF) [self performSelector:@selector(viewPDF:) withObject:[alertView textFieldAtIndex:0].text afterDelay:0.3];
  670. }
  671. - (void)viewPDF:(NSString *)password
  672. {
  673. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView];
  674. if ([CCUtility fileProviderStorageExists:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView] == NO) {
  675. // read file error
  676. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  677. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  678. [alertController addAction:okAction];
  679. [self presentViewController:alertController animated:YES completion:nil];
  680. }
  681. CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:fileNamePath]);
  682. if (pdf) {
  683. // Encrypted
  684. if (CGPDFDocumentIsEncrypted(pdf) == YES) {
  685. // Try a blank password first, per Apple's Quartz PDF example
  686. if (CGPDFDocumentUnlockWithPassword(pdf, "") == YES) {
  687. // blank password
  688. [self readerPDF:fileNamePath password:@""];
  689. } else {
  690. if ([password length] == 0) {
  691. // password request
  692. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_insert_password_pfd_",nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  693. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  694. alertView.tag = alertRequestPasswordPDF;
  695. [alertView show];
  696. } else {
  697. const char *key = [password UTF8String];
  698. // failure
  699. if (CGPDFDocumentUnlockWithPassword(pdf, key) == NO) {
  700. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_password_pdf_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  701. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  702. [alertController addAction:okAction];
  703. [self presentViewController:alertController animated:YES completion:nil];
  704. } else {
  705. // pdf with password
  706. [self readerPDF:fileNamePath password:password];
  707. }
  708. }
  709. }
  710. } else{
  711. // No password
  712. [self readerPDF:fileNamePath password:@""];
  713. }
  714. } else {
  715. // read file error
  716. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  717. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  718. [alertController addAction:okAction];
  719. [self presentViewController:alertController animated:YES completion:nil];
  720. }
  721. }
  722. - (void)readerPDF:(NSString *)fileName password:(NSString *)password
  723. {
  724. ReaderDocument *documentPDF = [ReaderDocument withDocumentFilePath:fileName password:password];
  725. CGFloat safeAreaBottom = 0;
  726. if (@available(iOS 11, *)) {
  727. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  728. }
  729. if (documentPDF != nil) {
  730. self.readerPDFViewController = [[ReaderViewController alloc] initWithReaderDocument:documentPDF];
  731. self.readerPDFViewController.delegate = self;
  732. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  733. [self.readerPDFViewController updateContentViews];
  734. [self addChildViewController:self.readerPDFViewController];
  735. [self.view addSubview:self.readerPDFViewController.view];
  736. [self.readerPDFViewController didMoveToParentViewController:self];
  737. } else {
  738. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_read_file_error_", nil) preferredStyle:UIAlertControllerStyleAlert];
  739. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  740. [alertController addAction:okAction];
  741. [self presentViewController:alertController animated:YES completion:nil];
  742. }
  743. }
  744. - (void)handleSingleTapReader
  745. {
  746. UILayoutGuide *layoutGuide;
  747. CGFloat safeAreaTop = 0;
  748. CGFloat safeAreaBottom = 0;
  749. if (@available(iOS 11, *)) {
  750. layoutGuide = [UIApplication sharedApplication].delegate.window.safeAreaLayoutGuide;
  751. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  752. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  753. }
  754. self.navigationController.navigationBarHidden = !self.navigationController.navigationBarHidden;
  755. self.toolbar.hidden = !self.toolbar.isHidden;
  756. if (self.toolbar.isHidden) {
  757. self.readerPDFViewController.view.frame = CGRectMake(0, safeAreaTop, self.view.bounds.size.width, self.view.bounds.size.height - safeAreaTop - safeAreaBottom);
  758. } else {
  759. self.readerPDFViewController.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - TOOLBAR_HEIGHT - safeAreaBottom);
  760. }
  761. [self.readerPDFViewController updateContentViews];
  762. }
  763. - (void)handleSwipeUpDown
  764. {
  765. // REMOVE IT'S UNUSABLE
  766. /*
  767. self.navigationController.navigationBarHidden = false; // iOS App is unusable after swipe up or down with PDF in fullscreen #526
  768. [self removeAllView];
  769. [self.navigationController popViewControllerAnimated:YES];
  770. */
  771. }
  772. #pragma --------------------------------------------------------------------------------------------
  773. #pragma mark ===== Delete =====
  774. #pragma --------------------------------------------------------------------------------------------
  775. - (void)deleteFile:(tableMetadata *)metadata
  776. {
  777. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  778. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND e2eEncrypted == 1 AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  779. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:[[NSArray alloc] initWithObjects:metadata, nil] e2ee:tableDirectory.e2eEncrypted serverUrl:serverUrl folderFileID:tableDirectory.fileID completion:^(NSInteger errorCode, NSString *message) {
  780. if (errorCode == 0) {
  781. // reload data source
  782. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:serverUrl fileID:metadata.fileID action:k_action_DEL];
  783. // Not image
  784. if ([self.metadataDetail.typeFile isEqualToString: k_metadataTypeFile_image] == NO) {
  785. // exit
  786. [self backNavigationController];
  787. } else {
  788. for (NSUInteger index=0; index < [self.photoDataSource count] && _photoBrowser; index++ ) {
  789. tableMetadata *metadataTemp = [self.photoDataSource objectAtIndex:index];
  790. if ([metadata isInvalidated] || [metadataTemp.fileID isEqualToString:metadata.fileID]) {
  791. [self.photoDataSource removeObjectAtIndex:index];
  792. [self.photos removeObjectAtIndex:index];
  793. [self.photoBrowser reloadData];
  794. // exit
  795. if ([self.photoDataSource count] == 0) {
  796. [self backNavigationController];
  797. }
  798. }
  799. }
  800. }
  801. } else {
  802. NSLog(@"[LOG] DeleteFileOrFolder failure error %d, %@", (int)errorCode, message);
  803. }
  804. }];
  805. }
  806. #pragma --------------------------------------------------------------------------------------------
  807. #pragma mark ===== ButtonPressed =====
  808. #pragma --------------------------------------------------------------------------------------------
  809. - (void)dismissTextView
  810. {
  811. if (self.webView) {
  812. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:self.metadataDetail.fileNameView];
  813. [[NSFileManager defaultManager] removeItemAtPath:fileNamePath error:nil];
  814. [[NSFileManager defaultManager] linkItemAtPath:[CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView] toPath:fileNamePath error:nil];
  815. [self.webView reload];
  816. }
  817. }
  818. - (void)modifyTxtButtonPressed:(UIBarButtonItem *)sender
  819. {
  820. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", self.metadataDetail.fileID]];
  821. if (metadata) {
  822. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  823. NCText *viewController = (NCText *)navigationController.topViewController;
  824. viewController.metadata = metadata;
  825. viewController.delegate = self;
  826. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  827. navigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  828. [self presentViewController:navigationController animated:YES completion:nil];
  829. }
  830. }
  831. - (void)actionButtonPressed:(UIBarButtonItem *)sender
  832. {
  833. if ([self.metadataDetail.fileNameView length] == 0) return;
  834. NSString *filePath = [CCUtility getDirectoryProviderStorageFileID:self.metadataDetail.fileID fileNameView:self.metadataDetail.fileNameView];
  835. self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
  836. self.docController.delegate = self;
  837. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
  838. [self.docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  839. [self.docController presentOptionsMenuFromBarButtonItem:sender animated:YES];
  840. }
  841. - (void)shareButtonPressed:(UIBarButtonItem *)sender
  842. {
  843. [appDelegate.activeMain openWindowShare:self.metadataDetail];
  844. }
  845. - (void)deleteButtonPressed:(UIBarButtonItem *)sender
  846. {
  847. if ([self.metadataDetail.fileNameView length] == 0) return;
  848. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  849. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  850. style:UIAlertActionStyleDestructive
  851. handler:^(UIAlertAction *action) {
  852. [self deleteFile:self.metadataDetail];
  853. }]];
  854. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  855. style:UIAlertActionStyleCancel
  856. handler:^(UIAlertAction *action) {
  857. [alertController dismissViewControllerAnimated:YES completion:nil];
  858. }]];
  859. alertController.popoverPresentationController.barButtonItem = buttonDelete;
  860. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  861. [alertController.view layoutIfNeeded];
  862. [self presentViewController:alertController animated:YES completion:NULL];
  863. }
  864. @end