CCDetail.m 52 KB

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