CCMedia.m 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. //
  2. // CCMedia.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 29/07/15.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 "CCMedia.h"
  24. #import "AppDelegate.h"
  25. #import "CCManageAutoUpload.h"
  26. #import "TOScrollBar.h"
  27. #import "NCBridgeSwift.h"
  28. @interface CCMedia () <NCSelectDelegate>
  29. {
  30. AppDelegate *appDelegate;
  31. NSMutableArray *selectedMetadatas;
  32. CCSectionDataSourceMetadata *sectionDataSource;
  33. BOOL filterTypeFileImage;
  34. BOOL filterTypeFileVideo;
  35. BOOL isSearchMode;
  36. BOOL isEditMode;
  37. TOScrollBar *scrollBar;
  38. NSMutableDictionary *saveEtagForStartDirectory;
  39. // Fix Crash Thumbnail + collectionView ReloadData ?
  40. NSInteger counterThumbnail;
  41. BOOL collectionViewReloadDataInProgress;
  42. // Remenu
  43. REMenu *menu;
  44. REMenuItem *menuSelectMediaFolder;
  45. REMenuItem *menuFilterImage;
  46. REMenuItem *menuFilterVideo;
  47. REMenuItem *menuSelectItems;
  48. }
  49. @end
  50. @implementation CCMedia
  51. #pragma --------------------------------------------------------------------------------------------
  52. #pragma mark ===== Init =====
  53. #pragma --------------------------------------------------------------------------------------------
  54. - (id)initWithCoder:(NSCoder *)aDecoder
  55. {
  56. if (self = [super initWithCoder:aDecoder]) {
  57. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  58. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  59. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  60. appDelegate.activeMedia = self;
  61. }
  62. return self;
  63. }
  64. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  65. {
  66. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  67. if (self) {
  68. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  69. }
  70. return self;
  71. }
  72. #pragma --------------------------------------------------------------------------------------------
  73. #pragma mark ===== View =====
  74. #pragma --------------------------------------------------------------------------------------------
  75. - (void)viewDidLoad
  76. {
  77. [super viewDidLoad];
  78. saveEtagForStartDirectory = [NSMutableDictionary new];
  79. selectedMetadatas = [NSMutableArray new];
  80. self.addMetadatasFromUpload = [NSMutableArray new];
  81. // empty Data Source
  82. self.collectionView.emptyDataSetDelegate = self;
  83. self.collectionView.emptyDataSetSource = self;
  84. // scroll bar
  85. scrollBar = [TOScrollBar new];
  86. [self.collectionView to_addScrollBar:scrollBar];
  87. scrollBar.handleTintColor = [NCBrandColor sharedInstance].brand;
  88. scrollBar.handleWidth = 20;
  89. scrollBar.handleMinimiumHeight = 20;
  90. scrollBar.trackWidth = 0;
  91. scrollBar.edgeInset = 12;
  92. // Query data source
  93. [self queryDatasourceWithReloadData:YES];
  94. }
  95. - (void)viewWillAppear:(BOOL)animated
  96. {
  97. [super viewWillAppear:animated];
  98. // Color
  99. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  100. [appDelegate aspectTabBar:self.tabBarController.tabBar hidden:NO];
  101. // Plus Button
  102. [appDelegate plusButtonVisibile:true];
  103. }
  104. - (void)viewDidAppear:(BOOL)animated
  105. {
  106. [super viewDidAppear:animated];
  107. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  108. [self reloadDatasource:nil action:k_action_NULL];
  109. });
  110. }
  111. - (void)viewSafeAreaInsetsDidChange
  112. {
  113. [super viewSafeAreaInsetsDidChange];
  114. self.collectionView.contentInset = self.view.safeAreaInsets;
  115. }
  116. - (void)changeTheming
  117. {
  118. if (self.isViewLoaded && self.view.window)
  119. [appDelegate changeTheming:self];
  120. scrollBar.handleTintColor = [NCBrandColor sharedInstance].brand;
  121. [self.collectionView reloadData];
  122. }
  123. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  124. {
  125. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  126. [menu close];
  127. // Before rotation
  128. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  129. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  130. // Portrait
  131. } else {
  132. // Landscape
  133. }
  134. [self.collectionView reloadData];
  135. }];
  136. }
  137. #pragma --------------------------------------------------------------------------------------------
  138. #pragma mark ===== Gestione Grafica Window =====
  139. #pragma --------------------------------------------------------------------------------------------
  140. - (void)openMenu
  141. {
  142. if (menu.isOpen) {
  143. [menu close];
  144. } else {
  145. [self createReMainMenu];
  146. [menu showFromNavigationController:self.navigationController];
  147. // Backgroun reMenu & (Gesture)
  148. [self createReMenuBackgroundView:menu];
  149. self.singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openMenu)];
  150. [self.reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  151. }
  152. }
  153. - (void)createReMenuBackgroundView:(REMenu *)menu
  154. {
  155. CGFloat safeAreaBottom = 0;
  156. CGFloat safeAreaTop = 0;
  157. CGFloat statusBar = 0;
  158. if (@available(iOS 11, *)) {
  159. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  160. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  161. }
  162. if ([UIApplication sharedApplication].isStatusBarHidden) {
  163. statusBar = 13;
  164. }
  165. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  166. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  167. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  168. self.reMenuBackgroundView = [UIView new];
  169. self.reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  170. self.reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  171. [UIView animateWithDuration:0.2 animations:^{
  172. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  173. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  174. if (y>minimum) {
  175. self.reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  176. [self.tabBarController.view addSubview:self.reMenuBackgroundView];
  177. }
  178. }];
  179. }
  180. - (void)createReMainMenu
  181. {
  182. menuSelectItems = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"select"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  183. if ([sectionDataSource.allRecordsDataSource count] > 0) {
  184. [self editingModeYES];
  185. }
  186. }];
  187. menuSelectMediaFolder = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_media_folder_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderMedia"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  188. [self selectStartDirectoryPhotosTab];
  189. }];
  190. if (filterTypeFileImage) {
  191. menuFilterImage = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_media_viewimage_show_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"imageno"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  192. filterTypeFileImage = NO;
  193. [self reloadDatasource:nil action:k_action_NULL];
  194. }];
  195. } else {
  196. menuFilterImage = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_media_viewimage_hide_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"imageyes"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  197. filterTypeFileImage = YES;
  198. [self reloadDatasource:nil action:k_action_NULL];
  199. }];
  200. }
  201. if (filterTypeFileVideo) {
  202. menuFilterVideo = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_media_viewvideo_show_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"videono"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  203. filterTypeFileVideo = NO;
  204. [self reloadDatasource:nil action:k_action_NULL];
  205. }];
  206. } else {
  207. menuFilterVideo = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_media_viewvideo_hide_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"videoyes"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  208. filterTypeFileVideo = YES;
  209. [self reloadDatasource:nil action:k_action_NULL];
  210. }];
  211. }
  212. // REMENU --------------------------------------------------------------------------------------------------------------
  213. menu = [[REMenu alloc] initWithItems:@[menuSelectItems, menuSelectMediaFolder, menuFilterImage, menuFilterVideo]];
  214. menu.imageOffset = CGSizeMake(5, -1);
  215. menu.separatorOffset = CGSizeMake(50.0, 0.0);
  216. menu.imageOffset = CGSizeMake(0, 0);
  217. menu.waitUntilAnimationIsComplete = NO;
  218. menu.separatorHeight = 0.5;
  219. menu.separatorColor = [NCBrandColor sharedInstance].seperator;
  220. menu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  221. menu.textColor = [UIColor blackColor];
  222. menu.textAlignment = NSTextAlignmentLeft;
  223. menu.textShadowColor = nil;
  224. menu.textOffset = CGSizeMake(50, 0.0);
  225. menu.font = [UIFont systemFontOfSize:14.0];
  226. menu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  227. menu.highlightedSeparatorColor = nil;
  228. menu.highlightedTextColor = [UIColor blackColor];
  229. menu.highlightedTextShadowColor = nil;
  230. menu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  231. menu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  232. menu.subtitleTextAlignment = NSTextAlignmentLeft;
  233. menu.subtitleTextShadowColor = nil;
  234. menu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  235. menu.subtitleTextOffset = CGSizeMake(50, 0.0);
  236. menu.subtitleFont = [UIFont systemFontOfSize:12.0];
  237. menu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  238. menu.subtitleHighlightedTextShadowColor = nil;
  239. menu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  240. menu.borderWidth = 0.3;
  241. menu.borderColor = [UIColor lightGrayColor];
  242. menu.animationDuration = 0.2;
  243. menu.closeAnimationDuration = 0.2;
  244. menu.bounce = NO;
  245. __weak typeof(self) weakSelf = self;
  246. [menu setClosePreparationBlock:^{
  247. // Backgroun reMenu (Gesture)
  248. [weakSelf.reMenuBackgroundView removeFromSuperview];
  249. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  250. }];
  251. }
  252. - (void)setUINavigationBarDefault
  253. {
  254. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  255. // curront folder search
  256. NSString *directory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryMediaTabView:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  257. NSString *home = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  258. NSString *folder = @"";
  259. if (home.length > 0) {
  260. folder = [directory stringByReplacingOccurrencesOfString:home withString:@""];
  261. }
  262. // Title
  263. NSString *title;
  264. if (folder.length == 0) {
  265. title = NSLocalizedString(@"_media_", nil);
  266. } else {
  267. title = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"_media_", nil), [folder substringFromIndex:1]];
  268. }
  269. self.navigationItem.titleView = nil;
  270. self.navigationItem.title = title;
  271. if (isSearchMode) {
  272. [CCGraphics addImageToTitle:title colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"load"] multiplier:2 color:[NCBrandColor sharedInstance].brandText] imageRight:NO navigationItem:self.navigationItem];
  273. }
  274. // Button Item RIGHT
  275. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(openMenu)];
  276. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  277. self.navigationItem.leftBarButtonItems = nil;
  278. }
  279. - (void)setUINavigationBarSelected
  280. {
  281. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"delete"] style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  282. // UIBarButtonItem *buttonOpenIn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"openFile"] style:UIBarButtonItemStylePlain target:self action:@selector(openSelectedFiles)];
  283. UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(editingModeNO)];
  284. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:cancelButton, nil];
  285. self.navigationItem.leftBarButtonItems = [[NSArray alloc] initWithObjects:buttonDelete, nil];
  286. // Title
  287. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[selectedMetadatas count], (unsigned long)[sectionDataSource.allRecordsDataSource count]];
  288. }
  289. - (void)cellSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath metadata:(tableMetadata *)metadata
  290. {
  291. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  292. UIVisualEffectView *effect = [cell viewWithTag:200];
  293. UIImageView *checked = [cell viewWithTag:300];
  294. if (select) {
  295. effect.hidden = NO;
  296. effect.alpha = 0.4;
  297. checked.hidden = NO;
  298. [selectedMetadatas addObject:metadata];
  299. } else {
  300. effect.hidden = YES;
  301. checked.hidden = YES;
  302. [selectedMetadatas removeObject:metadata];
  303. }
  304. // Title
  305. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[selectedMetadatas count], (unsigned long)[sectionDataSource.allRecordsDataSource count]];
  306. }
  307. - (void)scrollToTop
  308. {
  309. [self.collectionView setContentOffset:CGPointMake(0, - self.collectionView.contentInset.top) animated:NO];
  310. }
  311. - (void)getGeoLocationForSection:(NSInteger)section
  312. {
  313. NSString *addLocation = @"";
  314. NSArray *fileIDsForKey = [sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]];
  315. for (NSString *fileID in fileIDsForKey) {
  316. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  317. if ([localFile.exifLatitude floatValue] > 0 || [localFile.exifLongitude floatValue] > 0) {
  318. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  319. addLocation = [NSString stringWithFormat:@"%@, %@", addLocation, location];
  320. }
  321. }
  322. }
  323. #pragma --------------------------------------------------------------------------------------------
  324. #pragma mark ==== DZNEmptyDataSetSource Methods ====
  325. #pragma --------------------------------------------------------------------------------------------
  326. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  327. {
  328. return [NCBrandColor sharedInstance].backgroundView;
  329. }
  330. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  331. {
  332. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"mediaNoRecord"] multiplier:1 color:[NCBrandColor sharedInstance].graySoft];
  333. }
  334. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  335. {
  336. NSString *text;
  337. if (isSearchMode) {
  338. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_search_in_progress_", nil)];
  339. } else {
  340. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  341. }
  342. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  343. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  344. }
  345. /*
  346. #pragma --------------------------------------------------------------------------------------------
  347. #pragma mark ===== openSelectedFiles =====
  348. #pragma--------------------------------------------------------------------------------------------
  349. - (void)openSelectedFiles
  350. {
  351. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  352. for (tableMetadata *metadata in selectedMetadatas) {
  353. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView];
  354. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  355. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  356. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  357. [dataToShare addObject:data];
  358. }
  359. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  360. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  361. }
  362. }
  363. }
  364. if ([dataToShare count] > 0) {
  365. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  366. // iPad
  367. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  368. self.navigationItem.leftBarButtonItem.enabled = NO;
  369. self.navigationItem.rightBarButtonItem.enabled = NO;
  370. [self presentViewController:activityViewController animated:YES completion:^{
  371. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  372. self.navigationItem.leftBarButtonItem.enabled = YES;
  373. self.navigationItem.rightBarButtonItem.enabled = YES;
  374. [self editingModeNO];
  375. if (completed) {
  376. [self.collectionView reloadData];
  377. }
  378. }];
  379. }];
  380. }
  381. }
  382. */
  383. #pragma --------------------------------------------------------------------------------------------
  384. #pragma mark ===== Download =====
  385. #pragma--------------------------------------------------------------------------------------------
  386. - (void)triggerProgressTask:(NSNotification *)notification
  387. {
  388. }
  389. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  390. {
  391. if (errorCode == 0) {
  392. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  393. if (metadata == nil || metadata.account != appDelegate.activeAccount) {
  394. return;
  395. }
  396. NSIndexPath *indexPath;
  397. BOOL existsIcon = NO;
  398. if (fileID) {
  399. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:fileID fileNameView:fileName]];
  400. indexPath = [sectionDataSource.fileIDIndexPath objectForKey:fileID];
  401. }
  402. if ([self indexPathIsValid:indexPath] && existsIcon) {
  403. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  404. if (cell) {
  405. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  406. UIVisualEffectView *effect = [cell viewWithTag:200];
  407. UIImageView *checked = [cell viewWithTag:300];
  408. imageView.image = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:fileID fileNameView:fileName]];
  409. effect.hidden = YES;
  410. checked.hidden = YES;
  411. }
  412. }
  413. } else {
  414. [appDelegate messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  415. }
  416. }
  417. #pragma --------------------------------------------------------------------------------------------
  418. #pragma mark ===== Delete =====
  419. #pragma--------------------------------------------------------------------------------------------
  420. - (void)deleteFile:(NSArray *)metadatas e2ee:(BOOL)e2ee
  421. {
  422. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:metadatas e2ee:false serverUrl:@"" folderFileID:@"" completion:^(NSInteger errorCode, NSString *message) {
  423. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:nil fileID:nil action:k_action_NULL];
  424. }];
  425. [self editingModeNO];
  426. }
  427. - (void)deleteSelectedFiles
  428. {
  429. if ([selectedMetadatas count] == 0)
  430. return;
  431. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  432. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  433. style:UIAlertActionStyleDestructive
  434. handler:^(UIAlertAction *action) {
  435. [self deleteFile:selectedMetadatas e2ee:false];
  436. }]];
  437. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  438. style:UIAlertActionStyleCancel
  439. handler:^(UIAlertAction *action) {
  440. }]];
  441. alertController.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItems.firstObject;
  442. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  443. [alertController.view layoutIfNeeded];
  444. [self presentViewController:alertController animated:YES completion:NULL];
  445. }
  446. #pragma --------------------------------------------------------------------------------------------
  447. #pragma mark ==== Download Thumbnail ====
  448. #pragma --------------------------------------------------------------------------------------------
  449. - (void)downloadThumbnail:(tableMetadata *)metadata indexPath:(NSIndexPath *)indexPath
  450. {
  451. counterThumbnail++;
  452. CGFloat width = [[NCUtility sharedInstance] getScreenWidthForPreview];
  453. CGFloat height = [[NCUtility sharedInstance] getScreenHeightForPreview];
  454. [[OCNetworking sharedManager] downloadPreviewWithAccount:appDelegate.activeAccount metadata:metadata withWidth:width andHeight:height completion:^(NSString *account, NSString *message, NSInteger errorCode) {
  455. counterThumbnail--;
  456. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount] && [[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] && [self indexPathIsValid:indexPath] && !collectionViewReloadDataInProgress) {
  457. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  458. }
  459. }];
  460. }
  461. #pragma --------------------------------------------------------------------------------------------
  462. #pragma mark ==== Change Start directory ====
  463. #pragma --------------------------------------------------------------------------------------------
  464. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type
  465. {
  466. if ([type isEqualToString:@"mediaFolder"]) {
  467. NSString *oldStartDirectoryMediaTabView = [[NCManageDatabase sharedInstance] getAccountStartDirectoryMediaTabView:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  468. if (![serverUrl isEqualToString:oldStartDirectoryMediaTabView]) {
  469. // Save Start Directory
  470. [[NCManageDatabase sharedInstance] setAccountStartDirectoryMediaTabView:serverUrl];
  471. // search PhotoVideo with new start directory
  472. [self searchPhotoVideo];
  473. }
  474. }
  475. }
  476. - (void)selectStartDirectoryPhotosTab
  477. {
  478. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  479. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  480. viewController.delegate = self;
  481. viewController.hideButtonCreateFolder = true;
  482. viewController.selectFile = false;
  483. viewController.includeDirectoryE2EEncryption = false;
  484. viewController.includeImages = false;
  485. viewController.type = @"mediaFolder";
  486. viewController.titleButtonDone = NSLocalizedString(@"_select_", nil);
  487. viewController.layoutViewSelect = k_layout_view_move;
  488. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  489. [self presentViewController:navigationController animated:YES completion:nil];
  490. }
  491. #pragma --------------------------------------------------------------------------------------------
  492. #pragma mark ==== Search Photo/Video ====
  493. #pragma --------------------------------------------------------------------------------------------
  494. - (void)searchPhotoVideo
  495. {
  496. // test
  497. if (appDelegate.activeAccount.length == 0 || isSearchMode)
  498. return;
  499. // WAITING FOR d:creationdate
  500. //
  501. // tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  502. // account.dateSearchContentTypeImageVideo
  503. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryMediaTabView:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  504. [[OCNetworking sharedManager] readFileWithAccount:appDelegate.activeAccount serverUrl:startDirectory fileName:nil completion:^(NSString *account, tableMetadata *metadata, NSString *message, NSInteger errorCode) {
  505. if (errorCode == 0 && [account isEqualToString:appDelegate.activeAccount]) {
  506. if (![metadata.etag isEqualToString:[saveEtagForStartDirectory objectForKey:startDirectory]] || sectionDataSource.allRecordsDataSource.count == 0) {
  507. isSearchMode = YES;
  508. [self editingModeNO];
  509. [[OCNetworking sharedManager] searchWithAccount:appDelegate.activeAccount fileName:@"" serverUrl:startDirectory contentType:@[@"image/%", @"video/%"] date:[NSDate distantPast] depth:@"infinity" completion:^(NSString *account, NSArray *metadatas, NSString *message, NSInteger errorCode) {
  510. isSearchMode = NO;
  511. if (errorCode == 0 && [appDelegate.activeAccount isEqualToString:account]) {
  512. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  513. // Clear all Hardcoded new foto/video from CCNetworking
  514. [self.addMetadatasFromUpload removeAllObjects];
  515. [[NCManageDatabase sharedInstance] createTablePhotos:metadatas account:account];
  516. dispatch_async(dispatch_get_main_queue(), ^{
  517. [self reloadDatasource:nil action:k_action_NULL];
  518. });
  519. // Update date
  520. [[NCManageDatabase sharedInstance] setAccountDateSearchContentTypeImageVideo:[NSDate date]];
  521. // Save etag
  522. [saveEtagForStartDirectory setObject:metadata.etag forKey:metadata.serverUrl];
  523. });
  524. } else {
  525. [self reloadDatasource:nil action:k_action_NULL];
  526. }
  527. }];
  528. } else {
  529. [self reloadDatasource:nil action:k_action_NULL];
  530. }
  531. }
  532. }];
  533. }
  534. #pragma --------------------------------------------------------------------------------------------
  535. #pragma mark ==== Datasource ====
  536. #pragma --------------------------------------------------------------------------------------------
  537. - (void)reloadDatasource:(NSString *)fileID action:(NSInteger)action
  538. {
  539. // test
  540. if (appDelegate.activeAccount.length == 0 || self.view.window == nil) {
  541. return;
  542. }
  543. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  544. collectionViewReloadDataInProgress = YES;
  545. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO];
  546. dispatch_async(dispatch_get_main_queue(), ^{
  547. if (isEditMode)
  548. [self setUINavigationBarSelected];
  549. else
  550. [self setUINavigationBarDefault];
  551. sectionDataSource = sectionDataSourceTemp;
  552. [self.collectionView reloadData];
  553. [self.collectionView performBatchUpdates:^{} completion:^(BOOL finished) {
  554. collectionViewReloadDataInProgress = NO;
  555. }];
  556. });
  557. });
  558. }
  559. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData
  560. {
  561. // test
  562. if (appDelegate.activeAccount.length == 0) {
  563. return nil;
  564. }
  565. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  566. NSArray *metadatas = [[NCManageDatabase sharedInstance] getTablePhotosWithAddMetadatasFromUpload:self.addMetadatasFromUpload account:appDelegate.activeAccount];
  567. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:@"date" filterFileID:appDelegate.filterFileID filterTypeFileImage:filterTypeFileImage filterTypeFileVideo:filterTypeFileVideo activeAccount:appDelegate.activeAccount];
  568. if (withReloadData) {
  569. sectionDataSource = sectionDataSourceTemp;
  570. [self.collectionView reloadData];
  571. }
  572. return sectionDataSourceTemp;
  573. }
  574. - (void)editingModeYES
  575. {
  576. [self.collectionView setAllowsMultipleSelection:true];
  577. isEditMode = true;
  578. [selectedMetadatas removeAllObjects];
  579. [self setUINavigationBarSelected];
  580. collectionViewReloadDataInProgress = YES;
  581. [self.collectionView reloadData];
  582. [self.collectionView performBatchUpdates:^{} completion:^(BOOL finished) {
  583. collectionViewReloadDataInProgress = NO;
  584. }];
  585. }
  586. - (void)editingModeNO
  587. {
  588. [self.collectionView setAllowsMultipleSelection:false];
  589. isEditMode = false;
  590. [selectedMetadatas removeAllObjects];
  591. [self setUINavigationBarDefault];
  592. collectionViewReloadDataInProgress = YES;
  593. [self.collectionView reloadData];
  594. [self.collectionView performBatchUpdates:^{} completion:^(BOOL finished) {
  595. collectionViewReloadDataInProgress = NO;
  596. }];
  597. }
  598. #pragma --------------------------------------------------------------------------------------------
  599. #pragma mark ==== Collection ====
  600. #pragma --------------------------------------------------------------------------------------------
  601. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  602. {
  603. return indexPath.section < [self numberOfSectionsInCollectionView:self.collectionView] && indexPath.row < [self collectionView:self.collectionView numberOfItemsInSection:indexPath.section];
  604. }
  605. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  606. {
  607. return [[sectionDataSource.sectionArrayRow allKeys] count];
  608. }
  609. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  610. {
  611. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  612. }
  613. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  614. {
  615. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  616. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  617. return CGSizeMake(collectionView.frame.size.width / 5.1f, collectionView.frame.size.width / 5.1f);
  618. else
  619. return CGSizeMake(collectionView.frame.size.width / 7.1f, collectionView.frame.size.width / 7.1f);
  620. }
  621. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  622. {
  623. if ([sectionDataSource.sections count] - 1 == section)
  624. return CGSizeMake(collectionView.frame.size.width, 50);
  625. return CGSizeZero;
  626. }
  627. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  628. {
  629. if (kind == UICollectionElementKindSectionHeader) {
  630. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  631. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  632. [self getGeoLocationForSection:indexPath.section];
  633. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  634. titleLabel.textColor = [UIColor blackColor];
  635. if (sectionDataSource.sections.count > indexPath.section)
  636. titleLabel.text = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:indexPath.section]];
  637. return headerView;
  638. }
  639. if (kind == UICollectionElementKindSectionFooter) {
  640. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  641. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  642. titleLabel.textColor = [UIColor grayColor];
  643. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  644. return footerView;
  645. }
  646. return nil;
  647. }
  648. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  649. {
  650. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  651. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  652. UIVisualEffectView *effect = [cell viewWithTag:200];
  653. UIImageView *checkedOverlay = [cell viewWithTag:300];
  654. checkedOverlay.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"checkedYes"] multiplier:2 color:[NCBrandColor sharedInstance].brand];
  655. UIImageView *videoOverlay = [cell viewWithTag:400];
  656. videoOverlay.image = [UIImage imageNamed:@"VideoOverlay"];
  657. NSArray *metadatasForKey = [sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:indexPath.section]];
  658. if ([metadatasForKey count] > indexPath.row) {
  659. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  660. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  661. // Image
  662. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]) {
  663. // insert Image
  664. imageView.image = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  665. } else {
  666. imageView.image = [UIImage imageNamed:@"file_photo"];
  667. if (metadata.hasPreview == 1 && ![CCUtility fileProviderStorageIconExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  668. [self downloadThumbnail:metadata indexPath:indexPath];
  669. }
  670. }
  671. // Cheched Overlay
  672. if (cell.selected) {
  673. checkedOverlay.hidden = NO;
  674. effect.hidden = NO;
  675. effect.alpha = 0.4;
  676. } else {
  677. checkedOverlay.hidden = YES;
  678. effect.hidden = YES;
  679. }
  680. // Video Overlay
  681. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  682. videoOverlay.hidden = NO;
  683. } else {
  684. videoOverlay.hidden = YES;
  685. }
  686. }
  687. return cell;
  688. }
  689. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  690. {
  691. NSArray *metadatasForKey = [sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:indexPath.section]];
  692. if ([metadatasForKey count] > indexPath.row) {
  693. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  694. self.metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  695. if (isEditMode) {
  696. [self cellSelect:YES indexPath:indexPath metadata:self.metadata];
  697. } else {
  698. if ([self shouldPerformSegue])
  699. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  700. }
  701. }
  702. }
  703. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  704. {
  705. // test
  706. if (isEditMode == NO)
  707. return;
  708. NSArray *metadatasForKey = [sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:indexPath.section]];
  709. if ([metadatasForKey count] > indexPath.row) {
  710. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  711. self.metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  712. [self cellSelect:NO indexPath:indexPath metadata:self.metadata];
  713. }
  714. }
  715. #pragma --------------------------------------------------------------------------------------------
  716. #pragma mark ===== Navigation ====
  717. #pragma --------------------------------------------------------------------------------------------
  718. - (BOOL)shouldPerformSegue
  719. {
  720. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  721. return NO;
  722. // Not in first plain ? exit
  723. if (self.view.window == NO)
  724. return NO;
  725. // Collapsed but in first plain in detail exit
  726. if (self.splitViewController.isCollapsed)
  727. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  728. return NO;
  729. // check if metadata is invalidated
  730. if ([[NCManageDatabase sharedInstance] isTableInvalidated:self.metadata]) {
  731. return NO;
  732. }
  733. // ok perform segue
  734. return YES;
  735. }
  736. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  737. {
  738. id controller = segue.destinationViewController;
  739. if ([controller isKindOfClass:[UINavigationController class]]) {
  740. UINavigationController *navigationController = controller;
  741. self.detailViewController = (CCDetail *)navigationController.topViewController;
  742. } else {
  743. self.detailViewController = segue.destinationViewController;
  744. }
  745. NSMutableArray *photoDataSource = [NSMutableArray new];
  746. for (NSString *fileID in sectionDataSource.allFileID) {
  747. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  748. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  749. [photoDataSource addObject:metadata];
  750. }
  751. self.detailViewController.photoDataSource = photoDataSource;
  752. self.detailViewController.metadataDetail = self.metadata;
  753. self.detailViewController.dateFilterQuery = self.metadata.date;
  754. [self.detailViewController setTitle:self.metadata.fileName];
  755. }
  756. @end