CCPhotos.m 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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. UIImage *icon;
  125. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  126. icon = [UIImage imageNamed:@"seleziona"];
  127. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(collectionSelectYES)];
  128. icon = [UIImage imageNamed:@"startDirectoryPhotosTab"];
  129. UIBarButtonItem *buttonStartDirectoryPhotosTab = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(selectStartDirectoryPhotosTab)];
  130. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  131. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  132. } else {
  133. self.navigationItem.rightBarButtonItems = nil;
  134. }
  135. self.navigationItem.leftBarButtonItems = [[NSArray alloc] initWithObjects:buttonStartDirectoryPhotosTab, nil];
  136. // Title
  137. NSString *directory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  138. NSString *folder = [directory stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl] withString:@""];
  139. if (folder.length == 0) {
  140. self.navigationItem.title = NSLocalizedString(@"_photo_camera_", nil);
  141. } else {
  142. self.navigationItem.title = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"_photo_camera_", nil), [folder substringFromIndex:1]];
  143. }
  144. }
  145. - (void)setUINavigationBarSelected
  146. {
  147. UIImage *icon;
  148. icon = [UIImage imageNamed:@"deleteSelectedFiles"];
  149. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  150. icon = [UIImage imageNamed:@"openSelectedFiles"];
  151. UIBarButtonItem *buttonOpenWith = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(openSelectedFiles)];
  152. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(reloadCollection)];
  153. self.navigationItem.leftBarButtonItem = leftButton;
  154. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonDelete, buttonOpenWith, nil];
  155. // Title
  156. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  157. }
  158. - (void)collectionSelect:(BOOL)edit
  159. {
  160. [self.collectionView setAllowsMultipleSelection:edit];
  161. _cellEditing = edit;
  162. if (edit)
  163. [self setUINavigationBarSelected];
  164. else
  165. [self setUINavigationBarDefault];
  166. }
  167. - (void)collectionSelectYES
  168. {
  169. [self collectionSelect:YES];
  170. }
  171. - (void)cellSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath metadata:(tableMetadata *)metadata
  172. {
  173. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  174. UIVisualEffectView *effect = [cell viewWithTag:200];
  175. UIImageView *checked = [cell viewWithTag:300];
  176. if (select) {
  177. effect.hidden = NO;
  178. effect.alpha = 0.4;
  179. checked.hidden = NO;
  180. [_selectedMetadatas addObject:metadata];
  181. } else {
  182. effect.hidden = YES;
  183. checked.hidden = YES;
  184. [_selectedMetadatas removeObject:metadata];
  185. }
  186. // Title
  187. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  188. }
  189. - (void)scrollToTop
  190. {
  191. [self.collectionView setContentOffset:CGPointMake(0, - self.collectionView.contentInset.top) animated:NO];
  192. }
  193. - (void)getGeoLocationForSection:(NSInteger)section
  194. {
  195. NSString *addLocation = @"";
  196. NSArray *fileIDsForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]];
  197. for (NSString *fileID in fileIDsForKey) {
  198. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  199. if ([localFile.exifLatitude floatValue] > 0 || [localFile.exifLongitude floatValue] > 0) {
  200. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  201. addLocation = [NSString stringWithFormat:@"%@, %@", addLocation, location];
  202. }
  203. }
  204. }
  205. #pragma --------------------------------------------------------------------------------------------
  206. #pragma mark ==== DZNEmptyDataSetSource Methods ====
  207. #pragma --------------------------------------------------------------------------------------------
  208. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  209. {
  210. return [NCBrandColor sharedInstance].backgroundView;
  211. }
  212. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  213. {
  214. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"photosNoRecord"] color:[NCBrandColor sharedInstance].brandElement];
  215. }
  216. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  217. {
  218. NSString *text;
  219. if (_isSearchMode) {
  220. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_search_in_progress_", nil)];
  221. } else {
  222. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  223. }
  224. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  225. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  226. }
  227. /*
  228. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  229. {
  230. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  231. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  232. paragraph.alignment = NSTextAlignmentCenter;
  233. NSString *text;
  234. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  235. if (account.autoUpload)
  236. text = [NSString stringWithFormat:@"%@", @"\n\n\n\n"];
  237. else
  238. text = [NSString stringWithFormat:@"\n%@\n", NSLocalizedString(@"_tutorial_autoupload_view_", nil)];
  239. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  240. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  241. }
  242. - (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
  243. {
  244. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  245. if (!account.autoUpload) {
  246. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"button1000x200"] color:[NCBrandColor sharedInstance].brandElement];
  247. return [CCGraphics drawText:NSLocalizedString(@"_activate_autoupload_", nil) inImage:buttonImage colorText:[UIColor whiteColor] sizeOfFont:26];
  248. } else return nil;
  249. }
  250. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  251. {
  252. CCManageAutoUpload *viewController = [[CCManageAutoUpload alloc] initWithNibName:nil bundle:nil];
  253. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  254. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  255. [self presentViewController:navigationController animated:YES completion:nil];
  256. }
  257. */
  258. #pragma --------------------------------------------------------------------------------------------
  259. #pragma mark ===== openSelectedFiles =====
  260. #pragma--------------------------------------------------------------------------------------------
  261. - (void)openSelectedFiles
  262. {
  263. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  264. for (tableMetadata *metadata in _selectedMetadatas) {
  265. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileName];
  266. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID] toPath:fileNamePath error:nil];
  267. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath]) {
  268. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  269. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  270. [dataToShare addObject:data];
  271. }
  272. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  273. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  274. }
  275. }
  276. }
  277. if ([dataToShare count] > 0) {
  278. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  279. // iPad
  280. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  281. self.navigationItem.leftBarButtonItem.enabled = NO;
  282. self.navigationItem.rightBarButtonItem.enabled = NO;
  283. [self presentViewController:activityViewController animated:YES completion:^{
  284. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  285. self.navigationItem.leftBarButtonItem.enabled = YES;
  286. self.navigationItem.rightBarButtonItem.enabled = YES;
  287. if (completed) {
  288. [self performSelector:@selector(reloadCollection) withObject:nil];
  289. }
  290. }];
  291. }];
  292. }
  293. }
  294. #pragma --------------------------------------------------------------------------------------------
  295. #pragma mark ===== Download =====
  296. #pragma--------------------------------------------------------------------------------------------
  297. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  298. {
  299. if (errorCode == 0) {
  300. NSIndexPath *indexPath;
  301. BOOL existsIcon = NO;
  302. if (fileID) {
  303. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, fileID]];
  304. indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  305. }
  306. if ([self indexPathIsValid:indexPath] && existsIcon) {
  307. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  308. if (cell) {
  309. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  310. UIVisualEffectView *effect = [cell viewWithTag:200];
  311. UIImageView *checked = [cell viewWithTag:300];
  312. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, fileID]];
  313. effect.hidden = YES;
  314. checked.hidden = YES;
  315. }
  316. }
  317. } else {
  318. [appDelegate messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  319. }
  320. }
  321. #pragma --------------------------------------------------------------------------------------------
  322. #pragma mark ===== Delete =====
  323. #pragma--------------------------------------------------------------------------------------------
  324. - (void)deleteFileOrFolderSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  325. {
  326. [_queueMetadatas removeObject:metadataNet.selector];
  327. if ([_queueMetadatas count] == 0) {
  328. [_hud hideHud];
  329. if ([_selectedMetadatas count] > 0) {
  330. [_selectedMetadatas removeObjectAtIndex:0];
  331. if ([_selectedMetadatas count] > 0) {
  332. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  333. } else {
  334. [self reloadDatasource];
  335. }
  336. } else {
  337. [self reloadDatasource];
  338. }
  339. }
  340. }
  341. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  342. {
  343. [_queueMetadatas addObject:selectorDelete];
  344. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self hud:_hud hudTitled:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile]];
  345. }
  346. - (void)deleteSelectedFiles
  347. {
  348. [_queueMetadatas removeAllObjects];
  349. _numSelectedMetadatas = [_selectedMetadatas count];
  350. if ([_selectedMetadatas count] == 0)
  351. return;
  352. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  353. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  354. style:UIAlertActionStyleDestructive
  355. handler:^(UIAlertAction *action) {
  356. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  357. }]];
  358. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  359. style:UIAlertActionStyleCancel
  360. handler:^(UIAlertAction *action) {
  361. [alertController dismissViewControllerAnimated:YES completion:nil];
  362. }]];
  363. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  364. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  365. [alertController.view layoutIfNeeded];
  366. [self presentViewController:alertController animated:YES completion:NULL];
  367. }
  368. #pragma --------------------------------------------------------------------------------------------
  369. #pragma mark ==== Download Thumbnail Delegate ====
  370. #pragma --------------------------------------------------------------------------------------------
  371. - (void)downloadThumbnailSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  372. {
  373. // Check Active Account
  374. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  375. return;
  376. if (errorCode == 0) {
  377. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  378. if ([self indexPathIsValid:indexPath]) {
  379. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadataNet.fileID]])
  380. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  381. }
  382. }
  383. }
  384. - (void)triggerProgressTask:(NSNotification *)notification
  385. {
  386. //NSDictionary *dict = notification.userInfo;
  387. //float progress = [[dict valueForKey:@"progress"] floatValue];
  388. }
  389. #pragma --------------------------------------------------------------------------------------------
  390. #pragma mark ==== Change Start directory ====
  391. #pragma --------------------------------------------------------------------------------------------
  392. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  393. {
  394. NSString *oldStartDirectoryPhotosTab = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  395. if (![serverUrlTo isEqualToString:oldStartDirectoryPhotosTab]) {
  396. // Save
  397. [[NCManageDatabase sharedInstance] setAccountStartDirectoryPhotosTab:serverUrlTo];
  398. // search PhotoVideo with new start directory
  399. [self searchPhotoVideo];
  400. }
  401. }
  402. - (void)selectStartDirectoryPhotosTab
  403. {
  404. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  405. CCMove *viewController = (CCMove *)navigationController.topViewController;
  406. viewController.delegate = self;
  407. viewController.move.title = NSLocalizedString(@"_select_dir_photos_tab_", nil);
  408. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  409. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  410. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  411. viewController.networkingOperationQueue = appDelegate.netQueue;
  412. viewController.hideCreateFolder = YES;
  413. // E2EE
  414. viewController.includeDirectoryE2EEncryption = NO;
  415. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  416. [self presentViewController:navigationController animated:YES completion:nil];
  417. }
  418. #pragma --------------------------------------------------------------------------------------------
  419. #pragma mark ==== readPhotoVideo ====
  420. #pragma --------------------------------------------------------------------------------------------
  421. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  422. {
  423. // Check Active Account
  424. if (![metadataNet.account isEqualToString:appDelegate.activeAccount]) {
  425. _isSearchMode = NO;
  426. return;
  427. }
  428. if (errorCode == 0) {
  429. // Update date
  430. [[NCManageDatabase sharedInstance] setAccountDateSearchContentTypeImageVideo:[NSDate date]];
  431. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  432. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  433. BOOL isUpdate = [[NCManageDatabase sharedInstance] updateTableMetadatasContentTypeImageVideo:metadatas startDirectory:startDirectory activeUrl:appDelegate.activeUrl];
  434. if (isUpdate) {
  435. dispatch_async(dispatch_get_main_queue(), ^{
  436. [self reloadDatasource];
  437. });
  438. }
  439. _isSearchMode = NO;
  440. });
  441. } else {
  442. _isSearchMode = NO;
  443. }
  444. }
  445. - (void)searchPhotoVideo
  446. {
  447. // test
  448. if (appDelegate.activeAccount.length == 0 || _isSearchMode)
  449. return;
  450. // WAITING FOR d:creationdate
  451. //
  452. // tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  453. // account.dateSearchContentTypeImageVideo
  454. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  455. [[CCActions sharedInstance] search:startDirectory fileName:@"" depth:@"infinity" date:[NSDate distantPast] contenType:@[@"image/%", @"video/%"] selector:selectorSearchContentType delegate:self];
  456. _isSearchMode = YES;
  457. }
  458. #pragma --------------------------------------------------------------------------------------------
  459. #pragma mark ==== Collection ====
  460. #pragma --------------------------------------------------------------------------------------------
  461. - (void)reloadDatasource
  462. {
  463. @synchronized(self) {
  464. // test
  465. if (appDelegate.activeAccount.length == 0)
  466. return;
  467. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  468. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  469. NSArray *metadatasDBImageVideo = [[NCManageDatabase sharedInstance] getTableMetadatasContentTypeImageVideo:startDirectory activeUrl:appDelegate.activeUrl];
  470. CCSectionDataSourceMetadata *tempSectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatasDBImageVideo listProgressMetadata:nil groupByField:@"date" activeAccount:appDelegate.activeAccount];
  471. dispatch_async(dispatch_get_main_queue(), ^{
  472. // OPTIMIZED
  473. if (tempSectionDataSource.totalSize != _sectionDataSource.totalSize || tempSectionDataSource.files != _sectionDataSource.files) {
  474. _sectionDataSource = [tempSectionDataSource copy];
  475. [self reloadCollection];
  476. }
  477. });
  478. });
  479. }
  480. }
  481. - (void)reloadCollection
  482. {
  483. [self.collectionView reloadData];
  484. [_selectedMetadatas removeAllObjects];
  485. [self collectionSelect:NO];
  486. }
  487. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  488. {
  489. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  490. }
  491. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  492. {
  493. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  494. }
  495. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  496. {
  497. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  498. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  499. return CGSizeMake(collectionView.frame.size.width / 5.1f, collectionView.frame.size.width / 5.1f);
  500. else
  501. return CGSizeMake(collectionView.frame.size.width / 7.1f, collectionView.frame.size.width / 7.1f);
  502. }
  503. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  504. {
  505. if ([_sectionDataSource.sections count] - 1 == section)
  506. return CGSizeMake(collectionView.frame.size.width, 50);
  507. return CGSizeZero;
  508. }
  509. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  510. {
  511. if (kind == UICollectionElementKindSectionHeader) {
  512. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  513. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  514. [self getGeoLocationForSection:indexPath.section];
  515. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  516. titleLabel.textColor = [UIColor blackColor];
  517. if (_sectionDataSource.sections.count > indexPath.section)
  518. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  519. return headerView;
  520. }
  521. if (kind == UICollectionElementKindSectionFooter) {
  522. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  523. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  524. titleLabel.textColor = [UIColor grayColor];
  525. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  526. return footerView;
  527. }
  528. return nil;
  529. }
  530. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  531. {
  532. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  533. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  534. UIVisualEffectView *effect = [cell viewWithTag:200];
  535. UIImageView *checked = [cell viewWithTag:300];
  536. checked.image = [UIImage imageNamed:@"checked"];
  537. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  538. if ([metadatasForKey count] > indexPath.row) {
  539. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  540. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  541. // Image
  542. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]]) {
  543. // insert Image
  544. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]];
  545. } else {
  546. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", appDelegate.activeAccount, metadata.directoryID]];
  547. // Thumbnail not present
  548. if (directory.e2eEncrypted) {
  549. imageView.image = [UIImage imageNamed:@"file_photo_encrypted"];
  550. } else {
  551. imageView.image = [UIImage imageNamed:@"file_photo"];
  552. if (metadata.thumbnailExists)
  553. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  554. }
  555. }
  556. // Cheched
  557. if (cell.selected) {
  558. checked.hidden = NO;
  559. effect.hidden = NO;
  560. effect.alpha = 0.4;
  561. } else {
  562. checked.hidden = YES;
  563. effect.hidden = YES;
  564. }
  565. }
  566. return cell;
  567. }
  568. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  569. {
  570. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  571. if ([metadatasForKey count] > indexPath.row) {
  572. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  573. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  574. if (_cellEditing) {
  575. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  576. } else {
  577. if ([self shouldPerformSegue])
  578. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  579. }
  580. }
  581. }
  582. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  583. {
  584. // test
  585. if (_cellEditing == NO)
  586. return;
  587. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  588. if ([metadatasForKey count] > indexPath.row) {
  589. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  590. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  591. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  592. }
  593. }
  594. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  595. {
  596. if (!indexPath)
  597. return NO;
  598. NSInteger section = indexPath.section;
  599. NSInteger row = indexPath.row;
  600. NSInteger lastSectionIndex = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
  601. if (section > lastSectionIndex || lastSectionIndex < 0)
  602. return NO;
  603. NSInteger rowCount = [self.collectionView numberOfItemsInSection:indexPath.section] - 1;
  604. if (rowCount < 0)
  605. return NO;
  606. return row <= rowCount;
  607. }
  608. #pragma --------------------------------------------------------------------------------------------
  609. #pragma mark ===== Navigation ====
  610. #pragma --------------------------------------------------------------------------------------------
  611. - (BOOL)shouldPerformSegue
  612. {
  613. // Test
  614. // Background ? exit
  615. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  616. return NO;
  617. // Not in first plain ? exit
  618. if (self.view.window == NO)
  619. return NO;
  620. // Collapsed but in first plain in detail exit
  621. if (self.splitViewController.isCollapsed)
  622. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  623. return NO;
  624. // ok perform segue
  625. return YES;
  626. }
  627. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  628. {
  629. id controller = segue.destinationViewController;
  630. if ([controller isKindOfClass:[UINavigationController class]]) {
  631. UINavigationController *navigationController = controller;
  632. self.detailViewController = (CCDetail *)navigationController.topViewController;
  633. } else {
  634. self.detailViewController = segue.destinationViewController;
  635. }
  636. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  637. for (NSString *fileID in _sectionDataSource.allEtag) {
  638. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  639. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  640. [allRecordsDataSourceImagesVideos addObject:metadata];
  641. }
  642. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  643. self.detailViewController.metadataDetail = _metadata;
  644. self.detailViewController.dateFilterQuery = _metadata.date;
  645. [self.detailViewController setTitle:_metadata.fileName];
  646. }
  647. @end