CCDetail.m 52 KB

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