CCDetail.m 52 KB

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