CCDetail.m 54 KB

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