CCMedia.m 37 KB

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