CCPhotos.m 32 KB

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