CCDetail.m 53 KB

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