CCPhotos.m 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. //
  2. // CCPhotos.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 "CCPhotos.h"
  24. #import "AppDelegate.h"
  25. #import "CCManageAutoUpload.h"
  26. #import "TOScrollBar.h"
  27. #import "NCBridgeSwift.h"
  28. @interface CCPhotos () <CCActionsDeleteDelegate, CCActionsDownloadThumbnailDelegate>
  29. {
  30. AppDelegate *appDelegate;
  31. tableMetadata *_metadata;
  32. BOOL _cellEditing;
  33. NSMutableArray *_queueMetadatas;
  34. NSMutableArray *_selectedMetadatas;
  35. NSUInteger _numSelectedMetadatas;
  36. CCSectionDataSourceMetadata *_sectionDataSource;
  37. CCHud *_hud;
  38. TOScrollBar *_scrollBar;
  39. BOOL _isSearchMode;
  40. }
  41. @end
  42. @implementation CCPhotos
  43. #pragma --------------------------------------------------------------------------------------------
  44. #pragma mark ===== Init =====
  45. #pragma --------------------------------------------------------------------------------------------
  46. - (id)initWithCoder:(NSCoder *)aDecoder
  47. {
  48. if (self = [super initWithCoder:aDecoder]) {
  49. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  50. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  51. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  52. appDelegate.activePhotos = self;
  53. }
  54. return self;
  55. }
  56. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  57. {
  58. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  59. if (self) {
  60. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  61. }
  62. return self;
  63. }
  64. #pragma --------------------------------------------------------------------------------------------
  65. #pragma mark ===== View =====
  66. #pragma --------------------------------------------------------------------------------------------
  67. - (void)viewDidLoad
  68. {
  69. [super viewDidLoad];
  70. _queueMetadatas = [[NSMutableArray alloc] init];
  71. _selectedMetadatas = [[NSMutableArray alloc] init];
  72. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  73. // empty Data Source
  74. self.collectionView.emptyDataSetDelegate = self;
  75. self.collectionView.emptyDataSetSource = self;
  76. // scroll bar
  77. _scrollBar = [TOScrollBar new];
  78. [self.collectionView to_addScrollBar:_scrollBar];
  79. _scrollBar.handleTintColor = [NCBrandColor sharedInstance].brand;
  80. _scrollBar.handleWidth = 20;
  81. _scrollBar.handleMinimiumHeight = 20;
  82. _scrollBar.trackWidth = 0;
  83. _scrollBar.edgeInset = 12;
  84. }
  85. // Apparirà
  86. - (void)viewWillAppear:(BOOL)animated
  87. {
  88. [super viewWillAppear:animated];
  89. // Color
  90. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  91. [appDelegate aspectTabBar:self.tabBarController.tabBar hidden:NO];
  92. // Plus Button
  93. [appDelegate plusButtonVisibile:true];
  94. [self reloadDatasource];
  95. }
  96. - (void)viewSafeAreaInsetsDidChange
  97. {
  98. [super viewSafeAreaInsetsDidChange];
  99. self.collectionView.contentInset = self.view.safeAreaInsets;
  100. }
  101. - (void)changeTheming
  102. {
  103. if (self.isViewLoaded && self.view.window)
  104. [appDelegate changeTheming:self];
  105. _scrollBar.handleTintColor = [NCBrandColor sharedInstance].brand;
  106. [self.collectionView reloadData];
  107. }
  108. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  109. {
  110. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  111. // Before rotation
  112. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  113. 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))) {
  114. // Portrait
  115. } else {
  116. // Landscape
  117. }
  118. }];
  119. }
  120. #pragma --------------------------------------------------------------------------------------------
  121. #pragma mark ===== Gestione Grafica Window =====
  122. #pragma --------------------------------------------------------------------------------------------
  123. - (void)setUINavigationBarDefault
  124. {
  125. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  126. // select
  127. UIImage *icon = [UIImage imageNamed:@"seleziona"];
  128. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(collectionSelectYES)];
  129. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  130. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  131. } else {
  132. self.navigationItem.rightBarButtonItems = nil;
  133. }
  134. self.navigationItem.leftBarButtonItem = nil;
  135. // Title
  136. self.navigationItem.title = NSLocalizedString(@"_photo_camera_", nil);
  137. }
  138. - (void)setUINavigationBarSelected
  139. {
  140. UIImage *icon;
  141. icon = [UIImage imageNamed:@"deleteSelectedFiles"];
  142. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  143. icon = [UIImage imageNamed:@"openSelectedFiles"];
  144. UIBarButtonItem *buttonOpenWith = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(openSelectedFiles)];
  145. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(reloadCollection)];
  146. self.navigationItem.leftBarButtonItem = leftButton;
  147. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonDelete, buttonOpenWith, nil];
  148. // Title
  149. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  150. }
  151. - (void)collectionSelect:(BOOL)edit
  152. {
  153. [self.collectionView setAllowsMultipleSelection:edit];
  154. _cellEditing = edit;
  155. if (edit)
  156. [self setUINavigationBarSelected];
  157. else
  158. [self setUINavigationBarDefault];
  159. }
  160. - (void)collectionSelectYES
  161. {
  162. [self collectionSelect:YES];
  163. }
  164. - (void)cellSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath metadata:(tableMetadata *)metadata
  165. {
  166. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  167. UIVisualEffectView *effect = [cell viewWithTag:200];
  168. UIImageView *checked = [cell viewWithTag:300];
  169. if (select) {
  170. effect.hidden = NO;
  171. effect.alpha = 0.4;
  172. checked.hidden = NO;
  173. [_selectedMetadatas addObject:metadata];
  174. } else {
  175. effect.hidden = YES;
  176. checked.hidden = YES;
  177. [_selectedMetadatas removeObject:metadata];
  178. }
  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)scrollToTop
  183. {
  184. [self.collectionView setContentOffset:CGPointMake(0, - self.collectionView.contentInset.top) animated:NO];
  185. }
  186. - (void)getGeoLocationForSection:(NSInteger)section
  187. {
  188. NSString *addLocation = @"";
  189. NSArray *fileIDsForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]];
  190. for (NSString *fileID in fileIDsForKey) {
  191. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  192. if ([localFile.exifLatitude floatValue] > 0 || [localFile.exifLongitude floatValue] > 0) {
  193. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  194. addLocation = [NSString stringWithFormat:@"%@, %@", addLocation, location];
  195. }
  196. }
  197. }
  198. #pragma --------------------------------------------------------------------------------------------
  199. #pragma mark ==== DZNEmptyDataSetSource Methods ====
  200. #pragma --------------------------------------------------------------------------------------------
  201. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  202. {
  203. return [NCBrandColor sharedInstance].backgroundView;
  204. }
  205. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  206. {
  207. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"photosNoRecord"] color:[NCBrandColor sharedInstance].brandElement];
  208. }
  209. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  210. {
  211. NSString *text;
  212. if (_isSearchMode) {
  213. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_search_in_progress_", nil)];
  214. } else {
  215. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  216. }
  217. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  218. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  219. }
  220. /*
  221. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  222. {
  223. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  224. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  225. paragraph.alignment = NSTextAlignmentCenter;
  226. NSString *text;
  227. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  228. if (account.autoUpload)
  229. text = [NSString stringWithFormat:@"%@", @"\n\n\n\n"];
  230. else
  231. text = [NSString stringWithFormat:@"\n%@\n", NSLocalizedString(@"_tutorial_autoupload_view_", nil)];
  232. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  233. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  234. }
  235. - (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
  236. {
  237. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  238. if (!account.autoUpload) {
  239. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"button1000x200"] color:[NCBrandColor sharedInstance].brandElement];
  240. return [CCGraphics drawText:NSLocalizedString(@"_activate_autoupload_", nil) inImage:buttonImage colorText:[UIColor whiteColor] sizeOfFont:26];
  241. } else return nil;
  242. }
  243. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  244. {
  245. CCManageAutoUpload *viewController = [[CCManageAutoUpload alloc] initWithNibName:nil bundle:nil];
  246. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  247. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  248. [self presentViewController:navigationController animated:YES completion:nil];
  249. }
  250. */
  251. #pragma --------------------------------------------------------------------------------------------
  252. #pragma mark ===== openSelectedFiles =====
  253. #pragma--------------------------------------------------------------------------------------------
  254. - (void)openSelectedFiles
  255. {
  256. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  257. for (tableMetadata *metadata in _selectedMetadatas) {
  258. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileName];
  259. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID] toPath:fileNamePath error:nil];
  260. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath]) {
  261. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  262. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  263. [dataToShare addObject:data];
  264. }
  265. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  266. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  267. }
  268. }
  269. }
  270. if ([dataToShare count] > 0) {
  271. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  272. // iPad
  273. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  274. self.navigationItem.leftBarButtonItem.enabled = NO;
  275. self.navigationItem.rightBarButtonItem.enabled = NO;
  276. [self presentViewController:activityViewController animated:YES completion:^{
  277. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  278. self.navigationItem.leftBarButtonItem.enabled = YES;
  279. self.navigationItem.rightBarButtonItem.enabled = YES;
  280. if (completed) {
  281. [self performSelector:@selector(reloadCollection) withObject:nil];
  282. }
  283. }];
  284. }];
  285. }
  286. }
  287. #pragma --------------------------------------------------------------------------------------------
  288. #pragma mark ===== Download =====
  289. #pragma--------------------------------------------------------------------------------------------
  290. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  291. {
  292. if (errorCode == 0) {
  293. NSIndexPath *indexPath;
  294. BOOL existsIcon = NO;
  295. if (fileID) {
  296. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, fileID]];
  297. indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  298. }
  299. if ([self indexPathIsValid:indexPath] && existsIcon) {
  300. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  301. if (cell) {
  302. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  303. UIVisualEffectView *effect = [cell viewWithTag:200];
  304. UIImageView *checked = [cell viewWithTag:300];
  305. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, fileID]];
  306. effect.hidden = YES;
  307. checked.hidden = YES;
  308. }
  309. }
  310. } else {
  311. [appDelegate messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  312. }
  313. }
  314. #pragma --------------------------------------------------------------------------------------------
  315. #pragma mark ===== Delete =====
  316. #pragma--------------------------------------------------------------------------------------------
  317. - (void)deleteFileOrFolderSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  318. {
  319. [_queueMetadatas removeObject:metadataNet.selector];
  320. if ([_queueMetadatas count] == 0) {
  321. [_hud hideHud];
  322. if ([_selectedMetadatas count] > 0) {
  323. [_selectedMetadatas removeObjectAtIndex:0];
  324. if ([_selectedMetadatas count] > 0) {
  325. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  326. } else {
  327. [self reloadDatasource];
  328. }
  329. } else {
  330. [self reloadDatasource];
  331. }
  332. }
  333. }
  334. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  335. {
  336. [_queueMetadatas addObject:selectorDelete];
  337. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self hud:_hud hudTitled:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile]];
  338. }
  339. - (void)deleteSelectedFiles
  340. {
  341. [_queueMetadatas removeAllObjects];
  342. _numSelectedMetadatas = [_selectedMetadatas count];
  343. if ([_selectedMetadatas count] == 0)
  344. return;
  345. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  346. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  347. style:UIAlertActionStyleDestructive
  348. handler:^(UIAlertAction *action) {
  349. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  350. }]];
  351. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  352. style:UIAlertActionStyleCancel
  353. handler:^(UIAlertAction *action) {
  354. [alertController dismissViewControllerAnimated:YES completion:nil];
  355. }]];
  356. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  357. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  358. [alertController.view layoutIfNeeded];
  359. [self presentViewController:alertController animated:YES completion:NULL];
  360. }
  361. #pragma --------------------------------------------------------------------------------------------
  362. #pragma mark ==== Download Thumbnail Delegate ====
  363. #pragma --------------------------------------------------------------------------------------------
  364. - (void)downloadThumbnailSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  365. {
  366. // Check Active Account
  367. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  368. return;
  369. if (errorCode == 0) {
  370. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  371. if ([self indexPathIsValid:indexPath]) {
  372. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadataNet.fileID]])
  373. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  374. }
  375. }
  376. }
  377. - (void)triggerProgressTask:(NSNotification *)notification
  378. {
  379. //NSDictionary *dict = notification.userInfo;
  380. //float progress = [[dict valueForKey:@"progress"] floatValue];
  381. }
  382. #pragma --------------------------------------------------------------------------------------------
  383. #pragma mark ==== readPhotoVideo ====
  384. #pragma --------------------------------------------------------------------------------------------
  385. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  386. {
  387. // Check Active Account
  388. if (![metadataNet.account isEqualToString:appDelegate.activeAccount]) {
  389. _isSearchMode = NO;
  390. return;
  391. }
  392. if (errorCode == 0) {
  393. // Update date
  394. [[NCManageDatabase sharedInstance] setAccountDateSearchContentTypeImageVideo:[NSDate date]];
  395. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  396. BOOL isUpdate = [[NCManageDatabase sharedInstance] updateTableMetadatasContentTypeImageVideo:metadatas];
  397. if (isUpdate) {
  398. dispatch_async(dispatch_get_main_queue(), ^{
  399. [self reloadDatasource];
  400. });
  401. }
  402. _isSearchMode = NO;
  403. });
  404. } else {
  405. _isSearchMode = NO;
  406. }
  407. }
  408. - (void)readPhotoVideo
  409. {
  410. // test
  411. if (appDelegate.activeAccount.length == 0 || _isSearchMode)
  412. return;
  413. // WAITING FOR d:creationdate
  414. //
  415. // tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  416. // account.dateSearchContentTypeImageVideo
  417. [[CCActions sharedInstance] search:@"" fileName:@"" depth:@"infinity" date:[NSDate distantPast] contenType:@[@"image/%", @"video/%"] selector:selectorSearchContentType delegate:self];
  418. _isSearchMode = YES;
  419. }
  420. #pragma --------------------------------------------------------------------------------------------
  421. #pragma mark ==== Collection ====
  422. #pragma --------------------------------------------------------------------------------------------
  423. - (void)reloadDatasource
  424. {
  425. @synchronized(self) {
  426. // test
  427. if (appDelegate.activeAccount.length == 0)
  428. return;
  429. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  430. NSArray *metadatasDBImageVideo = [[NCManageDatabase sharedInstance] getTableMetadatasContentTypeImageVideo];
  431. CCSectionDataSourceMetadata *tempSectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatasDBImageVideo listProgressMetadata:nil groupByField:@"date" activeAccount:appDelegate.activeAccount];
  432. dispatch_async(dispatch_get_main_queue(), ^{
  433. // OPTIMIZED
  434. if (tempSectionDataSource.totalSize != _sectionDataSource.totalSize || tempSectionDataSource.files != _sectionDataSource.files) {
  435. _sectionDataSource = [tempSectionDataSource copy];
  436. [self reloadCollection];
  437. }
  438. });
  439. });
  440. }
  441. }
  442. - (void)reloadCollection
  443. {
  444. [self.collectionView reloadData];
  445. [_selectedMetadatas removeAllObjects];
  446. [self collectionSelect:NO];
  447. }
  448. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  449. {
  450. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  451. }
  452. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  453. {
  454. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  455. }
  456. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  457. {
  458. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  459. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  460. return CGSizeMake(collectionView.frame.size.width / 5.1f, collectionView.frame.size.width / 5.1f);
  461. else
  462. return CGSizeMake(collectionView.frame.size.width / 7.1f, collectionView.frame.size.width / 7.1f);
  463. }
  464. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  465. {
  466. if ([_sectionDataSource.sections count] - 1 == section)
  467. return CGSizeMake(collectionView.frame.size.width, 50);
  468. return CGSizeZero;
  469. }
  470. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  471. {
  472. if (kind == UICollectionElementKindSectionHeader) {
  473. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  474. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  475. [self getGeoLocationForSection:indexPath.section];
  476. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  477. titleLabel.textColor = [UIColor blackColor];
  478. if (_sectionDataSource.sections.count > indexPath.section)
  479. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  480. return headerView;
  481. }
  482. if (kind == UICollectionElementKindSectionFooter) {
  483. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  484. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  485. titleLabel.textColor = [UIColor grayColor];
  486. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  487. return footerView;
  488. }
  489. return nil;
  490. }
  491. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  492. {
  493. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  494. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  495. UIVisualEffectView *effect = [cell viewWithTag:200];
  496. UIImageView *checked = [cell viewWithTag:300];
  497. checked.image = [UIImage imageNamed:@"checked"];
  498. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  499. if ([metadatasForKey count] > indexPath.row) {
  500. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  501. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  502. // Image
  503. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]]) {
  504. // insert Image
  505. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]];
  506. } else {
  507. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", appDelegate.activeAccount, metadata.directoryID]];
  508. // Thumbnail not present
  509. if (directory.e2eEncrypted) {
  510. imageView.image = [UIImage imageNamed:@"file_photo_encrypted"];
  511. } else {
  512. imageView.image = [UIImage imageNamed:@"file_photo"];
  513. if (metadata.thumbnailExists)
  514. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  515. }
  516. }
  517. // Cheched
  518. if (cell.selected) {
  519. checked.hidden = NO;
  520. effect.hidden = NO;
  521. effect.alpha = 0.4;
  522. } else {
  523. checked.hidden = YES;
  524. effect.hidden = YES;
  525. }
  526. }
  527. return cell;
  528. }
  529. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  530. {
  531. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  532. if ([metadatasForKey count] > indexPath.row) {
  533. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  534. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  535. if (_cellEditing) {
  536. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  537. } else {
  538. if ([self shouldPerformSegue])
  539. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  540. }
  541. }
  542. }
  543. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  544. {
  545. // test
  546. if (_cellEditing == NO)
  547. return;
  548. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  549. if ([metadatasForKey count] > indexPath.row) {
  550. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  551. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  552. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  553. }
  554. }
  555. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  556. {
  557. if (!indexPath)
  558. return NO;
  559. NSInteger section = indexPath.section;
  560. NSInteger row = indexPath.row;
  561. NSInteger lastSectionIndex = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
  562. if (section > lastSectionIndex || lastSectionIndex < 0)
  563. return NO;
  564. NSInteger rowCount = [self.collectionView numberOfItemsInSection:indexPath.section] - 1;
  565. if (rowCount < 0)
  566. return NO;
  567. return row <= rowCount;
  568. }
  569. #pragma --------------------------------------------------------------------------------------------
  570. #pragma mark ===== Navigation ====
  571. #pragma --------------------------------------------------------------------------------------------
  572. - (BOOL)shouldPerformSegue
  573. {
  574. // Test
  575. // Background ? exit
  576. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  577. return NO;
  578. // Not in first plain ? exit
  579. if (self.view.window == NO)
  580. return NO;
  581. // Collapsed but in first plain in detail exit
  582. if (self.splitViewController.isCollapsed)
  583. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  584. return NO;
  585. // ok perform segue
  586. return YES;
  587. }
  588. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  589. {
  590. id controller = segue.destinationViewController;
  591. if ([controller isKindOfClass:[UINavigationController class]]) {
  592. UINavigationController *navigationController = controller;
  593. self.detailViewController = (CCDetail *)navigationController.topViewController;
  594. } else {
  595. self.detailViewController = segue.destinationViewController;
  596. }
  597. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  598. for (NSString *fileID in _sectionDataSource.allEtag) {
  599. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  600. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  601. [allRecordsDataSourceImagesVideos addObject:metadata];
  602. }
  603. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  604. self.detailViewController.metadataDetail = _metadata;
  605. self.detailViewController.dateFilterQuery = _metadata.date;
  606. [self.detailViewController setTitle:_metadata.fileName];
  607. }
  608. @end