CCMedia.m 36 KB

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