CCDetail.m 54 KB

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