CCDetail.m 54 KB

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