CCMedia.m 37 KB

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