CCPhotos.m 34 KB

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