CCMedia.m 42 KB

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