CCDetail.m 52 KB

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