CCPhotos.m 36 KB

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