CCDetail.m 51 KB

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