CCDetail.m 52 KB

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