CCPhotos.m 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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:@"load"] multiplier:2 color:[NCBrandColor sharedInstance].brandText] navigationItem:self.navigationItem];
  140. [self.collectionView reloadData];
  141. return;
  142. }
  143. // Button Item
  144. UIImage *icon;
  145. icon = [UIImage imageNamed:@"select"];
  146. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(editingModeYES)];
  147. icon = [UIImage imageNamed:@"folderPhotos"];
  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:@"delete"];
  161. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  162. icon = [UIImage imageNamed:@"openFile"];
  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"] multiplier:2 color:[NCBrandColor sharedInstance].graySoft];
  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 = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView];
  279. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  280. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  281. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  282. [dataToShare addObject:data];
  283. }
  284. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  285. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  286. }
  287. }
  288. }
  289. if ([dataToShare count] > 0) {
  290. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  291. // iPad
  292. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  293. self.navigationItem.leftBarButtonItem.enabled = NO;
  294. self.navigationItem.rightBarButtonItem.enabled = NO;
  295. [self presentViewController:activityViewController animated:YES completion:^{
  296. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  297. self.navigationItem.leftBarButtonItem.enabled = YES;
  298. self.navigationItem.rightBarButtonItem.enabled = YES;
  299. [self editingModeNO];
  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 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:[CCUtility getDirectoryProviderStorageIconFileID:fileID fileNameView:fileName]];
  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:[CCUtility getDirectoryProviderStorageIconFileID:fileID fileNameView:fileName]];
  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. /* TEST
  338. - (void)deleteFileOrFolder
  339. {
  340. tableMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  341. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  342. [_hud visibleHudTitle:@"c" mode:MBProgressHUDModeIndeterminate color:nil];
  343. [_oc deleteFileOrFolder:metadata.fileName serverUrl:serverUrl success:^{
  344. [_selectedMetadatas removeObjectAtIndex:0];
  345. if ([_selectedMetadatas count] > 0) {
  346. [self performSelectorOnMainThread:@selector(deleteFileOrFolder) withObject:nil waitUntilDone:0];
  347. } else {
  348. [_hud hideHud];
  349. [self editingModeNO];
  350. [self reloadDatasourceFromSearch:NO];
  351. }
  352. } failure:^(NSString *message, NSInteger errorCode) {
  353. [_hud hideHud];
  354. [self editingModeNO];
  355. [self reloadDatasourceFromSearch:NO];
  356. }];
  357. }
  358. */
  359. - (void)deleteFileOrFolderSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  360. {
  361. [_queueMetadatas removeObject:metadataNet.selector];
  362. if ([_queueMetadatas count] == 0) {
  363. [_hud hideHud];
  364. if ([_selectedMetadatas count] > 0) {
  365. [_selectedMetadatas removeObjectAtIndex:0];
  366. if ([_selectedMetadatas count] > 0) {
  367. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  368. } else {
  369. [self reloadDatasourceFromSearch:NO];
  370. [self editingModeNO];
  371. }
  372. } else {
  373. [self reloadDatasourceFromSearch:NO];
  374. }
  375. }
  376. }
  377. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  378. {
  379. [_queueMetadatas addObject:selectorDelete];
  380. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self hud:_hud hudTitled:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile]];
  381. }
  382. - (void)deleteSelectedFiles
  383. {
  384. [_queueMetadatas removeAllObjects];
  385. _numSelectedMetadatas = [_selectedMetadatas count];
  386. if ([_selectedMetadatas count] == 0)
  387. return;
  388. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  389. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  390. style:UIAlertActionStyleDestructive
  391. handler:^(UIAlertAction *action) {
  392. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  393. }]];
  394. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  395. style:UIAlertActionStyleCancel
  396. handler:^(UIAlertAction *action) {
  397. [alertController dismissViewControllerAnimated:YES completion:nil];
  398. }]];
  399. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  400. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  401. [alertController.view layoutIfNeeded];
  402. [self presentViewController:alertController animated:YES completion:NULL];
  403. }
  404. #pragma --------------------------------------------------------------------------------------------
  405. #pragma mark ==== Download Thumbnail Delegate ====
  406. #pragma --------------------------------------------------------------------------------------------
  407. - (void)downloadThumbnailSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  408. {
  409. // Check Active Account
  410. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  411. return;
  412. if (errorCode == 0) {
  413. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  414. if ([self indexPathIsValid:indexPath]) {
  415. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadataNet.fileID fileNameView:metadataNet.fileNameView]])
  416. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  417. }
  418. }
  419. }
  420. - (void)triggerProgressTask:(NSNotification *)notification
  421. {
  422. //NSDictionary *dict = notification.userInfo;
  423. //float progress = [[dict valueForKey:@"progress"] floatValue];
  424. }
  425. #pragma --------------------------------------------------------------------------------------------
  426. #pragma mark ==== Change Start directory ====
  427. #pragma --------------------------------------------------------------------------------------------
  428. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  429. {
  430. NSString *oldStartDirectoryPhotosTab = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  431. if (![serverUrlTo isEqualToString:oldStartDirectoryPhotosTab]) {
  432. // Save Start Directory
  433. [[NCManageDatabase sharedInstance] setAccountStartDirectoryPhotosTab:serverUrlTo];
  434. // search PhotoVideo with new start directory
  435. [self searchPhotoVideo];
  436. }
  437. }
  438. - (void)selectStartDirectoryPhotosTab
  439. {
  440. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  441. CCMove *viewController = (CCMove *)navigationController.topViewController;
  442. viewController.delegate = self;
  443. viewController.move.title = NSLocalizedString(@"_select_dir_photos_tab_", nil);
  444. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  445. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  446. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  447. viewController.networkingOperationQueue = appDelegate.netQueue;
  448. viewController.hideCreateFolder = YES;
  449. // E2EE
  450. viewController.includeDirectoryE2EEncryption = NO;
  451. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  452. [self presentViewController:navigationController animated:YES completion:nil];
  453. }
  454. #pragma --------------------------------------------------------------------------------------------
  455. #pragma mark ==== Search Photo/Video ====
  456. #pragma --------------------------------------------------------------------------------------------
  457. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  458. {
  459. // Check Active Account
  460. if (![metadataNet.account isEqualToString:appDelegate.activeAccount]) {
  461. [self searchInProgress:NO];
  462. return;
  463. }
  464. if (errorCode == 0) {
  465. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  466. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  467. (void)[[NCManageDatabase sharedInstance] updateTableMetadatasContentTypeImageVideo:metadatas startDirectory:startDirectory activeUrl:appDelegate.activeUrl];
  468. dispatch_async(dispatch_get_main_queue(), ^{
  469. [self reloadDatasourceFromSearch:YES];
  470. });
  471. // Update date
  472. [[NCManageDatabase sharedInstance] setAccountDateSearchContentTypeImageVideo:[NSDate date]];
  473. // Save etag
  474. [_saveEtagForStartDirectory setObject:metadataNet.etag forKey:metadataNet.serverUrl];
  475. });
  476. } else {
  477. [self searchInProgress:NO];
  478. }
  479. }
  480. - (void)searchPhotoVideo
  481. {
  482. // test
  483. if (appDelegate.activeAccount.length == 0 || _isSearchMode || _isEditMode)
  484. return;
  485. // WAITING FOR d:creationdate
  486. //
  487. // tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  488. // account.dateSearchContentTypeImageVideo
  489. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  490. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:self metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  491. [ocNetworking readFile:nil serverUrl:startDirectory account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  492. if (![metadata.etag isEqualToString:[_saveEtagForStartDirectory objectForKey:startDirectory]] || _sectionDataSource.allRecordsDataSource.count == 0) {
  493. [[CCActions sharedInstance] search:startDirectory fileName:@"" etag:metadata.etag depth:@"infinity" date:[NSDate distantPast] contenType:@[@"image/%", @"video/%"] selector:selectorSearchContentType delegate:self];
  494. [self searchInProgress:YES];
  495. [self editingModeNO];
  496. } else {
  497. [self reloadDatasourceFromSearch:YES];
  498. }
  499. } failure:^(NSString *message, NSInteger errorCode) {
  500. [self reloadDatasourceFromSearch:YES];
  501. }];
  502. }
  503. #pragma --------------------------------------------------------------------------------------------
  504. #pragma mark ==== Datasource ====
  505. #pragma --------------------------------------------------------------------------------------------
  506. - (void)reloadDatasourceFromSearch:(BOOL)fromSearch
  507. {
  508. @synchronized(self) {
  509. // test
  510. if (appDelegate.activeAccount.length == 0) {
  511. [self searchInProgress:NO];
  512. return;
  513. }
  514. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  515. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  516. NSArray *metadatasDBImageVideo = [[NCManageDatabase sharedInstance] getTableMetadatasContentTypeImageVideo:startDirectory];
  517. CCSectionDataSourceMetadata *tempSectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatasDBImageVideo listProgressMetadata:nil groupByField:@"date" activeAccount:appDelegate.activeAccount];
  518. dispatch_async(dispatch_get_main_queue(), ^{
  519. // OPTIMIZED
  520. if (tempSectionDataSource.totalSize != _sectionDataSource.totalSize || tempSectionDataSource.files != _sectionDataSource.files) {
  521. _sectionDataSource = [tempSectionDataSource copy];
  522. [self.collectionView reloadData];
  523. }
  524. if (fromSearch) {
  525. [self searchInProgress:NO];
  526. }
  527. });
  528. });
  529. }
  530. }
  531. - (void)editingModeYES
  532. {
  533. [self.collectionView setAllowsMultipleSelection:true];
  534. _isEditMode = true;
  535. [self setUINavigationBarSelected];
  536. }
  537. - (void)editingModeNO
  538. {
  539. [self.collectionView setAllowsMultipleSelection:false];
  540. _isEditMode = false;
  541. [_selectedMetadatas removeAllObjects];
  542. [self setUINavigationBarDefault];
  543. }
  544. #pragma --------------------------------------------------------------------------------------------
  545. #pragma mark ==== Collection ====
  546. #pragma --------------------------------------------------------------------------------------------
  547. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  548. {
  549. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  550. }
  551. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  552. {
  553. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  554. }
  555. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  556. {
  557. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  558. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  559. return CGSizeMake(collectionView.frame.size.width / 5.1f, collectionView.frame.size.width / 5.1f);
  560. else
  561. return CGSizeMake(collectionView.frame.size.width / 7.1f, collectionView.frame.size.width / 7.1f);
  562. }
  563. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  564. {
  565. if ([_sectionDataSource.sections count] - 1 == section)
  566. return CGSizeMake(collectionView.frame.size.width, 50);
  567. return CGSizeZero;
  568. }
  569. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  570. {
  571. if (kind == UICollectionElementKindSectionHeader) {
  572. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  573. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  574. [self getGeoLocationForSection:indexPath.section];
  575. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  576. titleLabel.textColor = [UIColor blackColor];
  577. if (_sectionDataSource.sections.count > indexPath.section)
  578. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  579. return headerView;
  580. }
  581. if (kind == UICollectionElementKindSectionFooter) {
  582. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  583. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  584. titleLabel.textColor = [UIColor grayColor];
  585. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  586. return footerView;
  587. }
  588. return nil;
  589. }
  590. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  591. {
  592. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  593. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  594. UIVisualEffectView *effect = [cell viewWithTag:200];
  595. UIImageView *checked = [cell viewWithTag:300];
  596. checked.image = [UIImage imageNamed:@"checked"];
  597. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  598. if ([metadatasForKey count] > indexPath.row) {
  599. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  600. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  601. // Image
  602. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]) {
  603. // insert Image
  604. imageView.image = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  605. } else {
  606. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@", metadata.directoryID]];
  607. // Thumbnail not present
  608. if (directory.e2eEncrypted) {
  609. imageView.image = [UIImage imageNamed:@"file_photo_encrypted"];
  610. } else {
  611. imageView.image = [UIImage imageNamed:@"file_photo"];
  612. if (metadata.thumbnailExists)
  613. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  614. }
  615. }
  616. // Cheched
  617. if (cell.selected) {
  618. checked.hidden = NO;
  619. effect.hidden = NO;
  620. effect.alpha = 0.4;
  621. } else {
  622. checked.hidden = YES;
  623. effect.hidden = YES;
  624. }
  625. }
  626. return cell;
  627. }
  628. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  629. {
  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. if (_isEditMode) {
  635. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  636. } else {
  637. if ([self shouldPerformSegue])
  638. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  639. }
  640. }
  641. }
  642. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  643. {
  644. // test
  645. if (_isEditMode == NO)
  646. return;
  647. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  648. if ([metadatasForKey count] > indexPath.row) {
  649. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  650. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  651. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  652. }
  653. }
  654. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  655. {
  656. if (!indexPath)
  657. return NO;
  658. NSInteger section = indexPath.section;
  659. NSInteger row = indexPath.row;
  660. NSInteger lastSectionIndex = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
  661. if (section > lastSectionIndex || lastSectionIndex < 0)
  662. return NO;
  663. NSInteger rowCount = [self.collectionView numberOfItemsInSection:indexPath.section] - 1;
  664. if (rowCount < 0)
  665. return NO;
  666. return row <= rowCount;
  667. }
  668. #pragma --------------------------------------------------------------------------------------------
  669. #pragma mark ===== Navigation ====
  670. #pragma --------------------------------------------------------------------------------------------
  671. - (BOOL)shouldPerformSegue
  672. {
  673. // Test
  674. // Background ? exit
  675. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  676. return NO;
  677. // Not in first plain ? exit
  678. if (self.view.window == NO)
  679. return NO;
  680. // Collapsed but in first plain in detail exit
  681. if (self.splitViewController.isCollapsed)
  682. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  683. return NO;
  684. // ok perform segue
  685. return YES;
  686. }
  687. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  688. {
  689. id controller = segue.destinationViewController;
  690. if ([controller isKindOfClass:[UINavigationController class]]) {
  691. UINavigationController *navigationController = controller;
  692. self.detailViewController = (CCDetail *)navigationController.topViewController;
  693. } else {
  694. self.detailViewController = segue.destinationViewController;
  695. }
  696. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  697. for (NSString *fileID in _sectionDataSource.allEtag) {
  698. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  699. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  700. [allRecordsDataSourceImagesVideos addObject:metadata];
  701. }
  702. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  703. self.detailViewController.metadataDetail = _metadata;
  704. self.detailViewController.dateFilterQuery = _metadata.date;
  705. [self.detailViewController setTitle:_metadata.fileName];
  706. }
  707. @end