CCPhotos.m 38 KB

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