CCDetail.m 54 KB

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