CCPhotos.m 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. //
  2. // CCPhotos.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 29/07/15.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCPhotos.h"
  24. #import "AppDelegate.h"
  25. #import "CCManageAutoUpload.h"
  26. #import "TOScrollBar.h"
  27. #import "NCBridgeSwift.h"
  28. @interface CCPhotos () <CCActionsDeleteDelegate, CCActionsDownloadThumbnailDelegate>
  29. {
  30. AppDelegate *appDelegate;
  31. tableMetadata *_metadata;
  32. NSMutableArray *_queueMetadatas;
  33. NSMutableArray *_selectedMetadatas;
  34. NSUInteger _numSelectedMetadatas;
  35. CCSectionDataSourceMetadata *_sectionDataSource;
  36. CCHud *_hud;
  37. TOScrollBar *_scrollBar;
  38. NSMutableDictionary *_saveEtagForStartDirectory;
  39. }
  40. @end
  41. @implementation CCPhotos
  42. #pragma --------------------------------------------------------------------------------------------
  43. #pragma mark ===== Init =====
  44. #pragma --------------------------------------------------------------------------------------------
  45. - (id)initWithCoder:(NSCoder *)aDecoder
  46. {
  47. if (self = [super initWithCoder:aDecoder]) {
  48. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  49. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  50. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  51. appDelegate.activePhotos = self;
  52. }
  53. return self;
  54. }
  55. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  56. {
  57. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  58. if (self) {
  59. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  60. }
  61. return self;
  62. }
  63. #pragma --------------------------------------------------------------------------------------------
  64. #pragma mark ===== View =====
  65. #pragma --------------------------------------------------------------------------------------------
  66. - (void)viewDidLoad
  67. {
  68. [super viewDidLoad];
  69. _queueMetadatas = [NSMutableArray new];
  70. _selectedMetadatas = [NSMutableArray new];
  71. _saveEtagForStartDirectory = [NSMutableDictionary new];
  72. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  73. // empty Data Source
  74. self.collectionView.emptyDataSetDelegate = self;
  75. self.collectionView.emptyDataSetSource = self;
  76. // scroll bar
  77. _scrollBar = [TOScrollBar new];
  78. [self.collectionView to_addScrollBar:_scrollBar];
  79. _scrollBar.handleTintColor = [NCBrandColor sharedInstance].brand;
  80. _scrollBar.handleWidth = 20;
  81. _scrollBar.handleMinimiumHeight = 20;
  82. _scrollBar.trackWidth = 0;
  83. _scrollBar.edgeInset = 12;
  84. }
  85. // Apparirà
  86. - (void)viewWillAppear:(BOOL)animated
  87. {
  88. [super viewWillAppear:animated];
  89. // Color
  90. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  91. [appDelegate aspectTabBar:self.tabBarController.tabBar hidden:NO];
  92. // Plus Button
  93. [appDelegate plusButtonVisibile:true];
  94. if(!_isSearchMode && !_isEditMode)
  95. [self reloadDatasourceFromSearch:NO];
  96. }
  97. - (void)viewSafeAreaInsetsDidChange
  98. {
  99. [super viewSafeAreaInsetsDidChange];
  100. self.collectionView.contentInset = self.view.safeAreaInsets;
  101. }
  102. - (void)changeTheming
  103. {
  104. if (self.isViewLoaded && self.view.window)
  105. [appDelegate changeTheming:self];
  106. _scrollBar.handleTintColor = [NCBrandColor sharedInstance].brand;
  107. if(!_isSearchMode && !_isEditMode)
  108. [self.collectionView reloadData];
  109. }
  110. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  111. {
  112. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  113. // Before rotation
  114. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  115. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  116. // Portrait
  117. } else {
  118. // Landscape
  119. }
  120. }];
  121. }
  122. #pragma --------------------------------------------------------------------------------------------
  123. #pragma mark ===== Gestione Grafica Window =====
  124. #pragma --------------------------------------------------------------------------------------------
  125. - (void)setUINavigationBarDefault
  126. {
  127. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  128. // curront folder search
  129. NSString *directory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  130. NSString *folder = [directory stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl] withString:@""];
  131. // Title
  132. self.navigationItem.titleView = nil;
  133. if (folder.length == 0) {
  134. self.navigationItem.title = NSLocalizedString(@"_photo_camera_", nil);
  135. } else {
  136. self.navigationItem.title = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"_photo_camera_", nil), [folder substringFromIndex:1]];
  137. }
  138. if (_isSearchMode) {
  139. [CCGraphics addImageToTitle:self.navigationItem.title colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"loadingTitle"] color:[NCBrandColor sharedInstance].brandText] navigationItem:self.navigationItem];
  140. [self.collectionView reloadData];
  141. return;
  142. }
  143. // Button Item
  144. UIImage *icon;
  145. icon = [UIImage imageNamed:@"seleziona"];
  146. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(editingModeYES)];
  147. icon = [UIImage imageNamed:@"startDirectoryPhotosTab"];
  148. UIBarButtonItem *buttonStartDirectoryPhotosTab = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(selectStartDirectoryPhotosTab)];
  149. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  150. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  151. } else {
  152. self.navigationItem.rightBarButtonItems = nil;
  153. }
  154. self.navigationItem.leftBarButtonItems = [[NSArray alloc] initWithObjects:buttonStartDirectoryPhotosTab, nil];
  155. [self.collectionView reloadData];
  156. }
  157. - (void)setUINavigationBarSelected
  158. {
  159. UIImage *icon;
  160. icon = [UIImage imageNamed:@"deleteSelectedFiles"];
  161. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  162. icon = [UIImage imageNamed:@"openSelectedFiles"];
  163. UIBarButtonItem *buttonOpenWith = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(openSelectedFiles)];
  164. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(editingModeNO)];
  165. self.navigationItem.leftBarButtonItem = leftButton;
  166. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonDelete, buttonOpenWith, nil];
  167. // Title
  168. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  169. [self.collectionView reloadData];
  170. }
  171. - (void)cellSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath metadata:(tableMetadata *)metadata
  172. {
  173. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  174. UIVisualEffectView *effect = [cell viewWithTag:200];
  175. UIImageView *checked = [cell viewWithTag:300];
  176. if (select) {
  177. effect.hidden = NO;
  178. effect.alpha = 0.4;
  179. checked.hidden = NO;
  180. [_selectedMetadatas addObject:metadata];
  181. } else {
  182. effect.hidden = YES;
  183. checked.hidden = YES;
  184. [_selectedMetadatas removeObject:metadata];
  185. }
  186. // Title
  187. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[_selectedMetadatas count], (unsigned long)[_sectionDataSource.allRecordsDataSource count]];
  188. }
  189. - (void)scrollToTop
  190. {
  191. [self.collectionView setContentOffset:CGPointMake(0, - self.collectionView.contentInset.top) animated:NO];
  192. }
  193. - (void)getGeoLocationForSection:(NSInteger)section
  194. {
  195. NSString *addLocation = @"";
  196. NSArray *fileIDsForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]];
  197. for (NSString *fileID in fileIDsForKey) {
  198. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  199. if ([localFile.exifLatitude floatValue] > 0 || [localFile.exifLongitude floatValue] > 0) {
  200. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  201. addLocation = [NSString stringWithFormat:@"%@, %@", addLocation, location];
  202. }
  203. }
  204. }
  205. - (void)searchInProgress:(BOOL)search
  206. {
  207. if (search) {
  208. _isSearchMode = YES;
  209. [self.navigationItem.leftBarButtonItems[0] setEnabled:NO];
  210. [self.navigationItem.rightBarButtonItems[0] setEnabled:NO];
  211. } else {
  212. _isSearchMode = NO;
  213. [self.navigationItem.leftBarButtonItems[0] setEnabled:YES];
  214. [self.navigationItem.rightBarButtonItems[0] setEnabled:YES];
  215. }
  216. [self setUINavigationBarDefault];
  217. }
  218. #pragma --------------------------------------------------------------------------------------------
  219. #pragma mark ==== DZNEmptyDataSetSource Methods ====
  220. #pragma --------------------------------------------------------------------------------------------
  221. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  222. {
  223. return [NCBrandColor sharedInstance].backgroundView;
  224. }
  225. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  226. {
  227. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"photosNoRecord"] color:[NCBrandColor sharedInstance].brandElement];
  228. }
  229. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  230. {
  231. NSString *text;
  232. if (_isSearchMode) {
  233. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_search_in_progress_", nil)];
  234. } else {
  235. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  236. }
  237. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  238. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  239. }
  240. /*
  241. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  242. {
  243. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  244. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  245. paragraph.alignment = NSTextAlignmentCenter;
  246. NSString *text;
  247. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  248. if (account.autoUpload)
  249. text = [NSString stringWithFormat:@"%@", @"\n\n\n\n"];
  250. else
  251. text = [NSString stringWithFormat:@"\n%@\n", NSLocalizedString(@"_tutorial_autoupload_view_", nil)];
  252. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  253. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  254. }
  255. - (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
  256. {
  257. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  258. if (!account.autoUpload) {
  259. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"button1000x200"] color:[NCBrandColor sharedInstance].brandElement];
  260. return [CCGraphics drawText:NSLocalizedString(@"_activate_autoupload_", nil) inImage:buttonImage colorText:[UIColor whiteColor] sizeOfFont:26];
  261. } else return nil;
  262. }
  263. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  264. {
  265. CCManageAutoUpload *viewController = [[CCManageAutoUpload alloc] initWithNibName:nil bundle:nil];
  266. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  267. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  268. [self presentViewController:navigationController animated:YES completion:nil];
  269. }
  270. */
  271. #pragma --------------------------------------------------------------------------------------------
  272. #pragma mark ===== openSelectedFiles =====
  273. #pragma--------------------------------------------------------------------------------------------
  274. - (void)openSelectedFiles
  275. {
  276. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  277. for (tableMetadata *metadata in _selectedMetadatas) {
  278. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileName];
  279. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID] toPath:fileNamePath error:nil];
  280. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath]) {
  281. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  282. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  283. [dataToShare addObject:data];
  284. }
  285. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  286. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  287. }
  288. }
  289. }
  290. if ([dataToShare count] > 0) {
  291. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  292. // iPad
  293. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  294. self.navigationItem.leftBarButtonItem.enabled = NO;
  295. self.navigationItem.rightBarButtonItem.enabled = NO;
  296. [self presentViewController:activityViewController animated:YES completion:^{
  297. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  298. self.navigationItem.leftBarButtonItem.enabled = YES;
  299. self.navigationItem.rightBarButtonItem.enabled = YES;
  300. [self editingModeNO];
  301. if (completed) {
  302. [self.collectionView reloadData];
  303. }
  304. }];
  305. }];
  306. }
  307. }
  308. #pragma --------------------------------------------------------------------------------------------
  309. #pragma mark ===== Download =====
  310. #pragma--------------------------------------------------------------------------------------------
  311. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  312. {
  313. if (errorCode == 0) {
  314. NSIndexPath *indexPath;
  315. BOOL existsIcon = NO;
  316. if (fileID) {
  317. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, fileID]];
  318. indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  319. }
  320. if ([self indexPathIsValid:indexPath] && existsIcon) {
  321. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  322. if (cell) {
  323. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  324. UIVisualEffectView *effect = [cell viewWithTag:200];
  325. UIImageView *checked = [cell viewWithTag:300];
  326. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, fileID]];
  327. effect.hidden = YES;
  328. checked.hidden = YES;
  329. }
  330. }
  331. } else {
  332. [appDelegate messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  333. }
  334. }
  335. #pragma --------------------------------------------------------------------------------------------
  336. #pragma mark ===== Delete =====
  337. #pragma--------------------------------------------------------------------------------------------
  338. /* TEST
  339. - (void)deleteFileOrFolder
  340. {
  341. tableMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  342. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  343. [_hud visibleHudTitle:@"c" mode:MBProgressHUDModeIndeterminate color:nil];
  344. [_oc deleteFileOrFolder:metadata.fileName serverUrl:serverUrl success:^{
  345. [_selectedMetadatas removeObjectAtIndex:0];
  346. if ([_selectedMetadatas count] > 0) {
  347. [self performSelectorOnMainThread:@selector(deleteFileOrFolder) withObject:nil waitUntilDone:0];
  348. } else {
  349. [_hud hideHud];
  350. [self editingModeNO];
  351. [self reloadDatasourceFromSearch:NO];
  352. }
  353. } failure:^(NSString *message, NSInteger errorCode) {
  354. [_hud hideHud];
  355. [self editingModeNO];
  356. [self reloadDatasourceFromSearch:NO];
  357. }];
  358. }
  359. */
  360. - (void)deleteFileOrFolderSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  361. {
  362. [_queueMetadatas removeObject:metadataNet.selector];
  363. if ([_queueMetadatas count] == 0) {
  364. [_hud hideHud];
  365. if ([_selectedMetadatas count] > 0) {
  366. [_selectedMetadatas removeObjectAtIndex:0];
  367. if ([_selectedMetadatas count] > 0) {
  368. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  369. } else {
  370. [self reloadDatasourceFromSearch:NO];
  371. [self editingModeNO];
  372. }
  373. } else {
  374. [self reloadDatasourceFromSearch:NO];
  375. }
  376. }
  377. }
  378. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  379. {
  380. [_queueMetadatas addObject:selectorDelete];
  381. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self hud:_hud hudTitled:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile]];
  382. }
  383. - (void)deleteSelectedFiles
  384. {
  385. [_queueMetadatas removeAllObjects];
  386. _numSelectedMetadatas = [_selectedMetadatas count];
  387. if ([_selectedMetadatas count] == 0)
  388. return;
  389. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  390. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  391. style:UIAlertActionStyleDestructive
  392. handler:^(UIAlertAction *action) {
  393. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  394. }]];
  395. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  396. style:UIAlertActionStyleCancel
  397. handler:^(UIAlertAction *action) {
  398. [alertController dismissViewControllerAnimated:YES completion:nil];
  399. }]];
  400. alertController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
  401. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  402. [alertController.view layoutIfNeeded];
  403. [self presentViewController:alertController animated:YES completion:NULL];
  404. }
  405. #pragma --------------------------------------------------------------------------------------------
  406. #pragma mark ==== Download Thumbnail Delegate ====
  407. #pragma --------------------------------------------------------------------------------------------
  408. - (void)downloadThumbnailSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  409. {
  410. // Check Active Account
  411. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  412. return;
  413. if (errorCode == 0) {
  414. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  415. if ([self indexPathIsValid:indexPath]) {
  416. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadataNet.fileID]])
  417. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  418. }
  419. }
  420. }
  421. - (void)triggerProgressTask:(NSNotification *)notification
  422. {
  423. //NSDictionary *dict = notification.userInfo;
  424. //float progress = [[dict valueForKey:@"progress"] floatValue];
  425. }
  426. #pragma --------------------------------------------------------------------------------------------
  427. #pragma mark ==== Change Start directory ====
  428. #pragma --------------------------------------------------------------------------------------------
  429. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  430. {
  431. NSString *oldStartDirectoryPhotosTab = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  432. if (![serverUrlTo isEqualToString:oldStartDirectoryPhotosTab]) {
  433. // Save Start Directory
  434. [[NCManageDatabase sharedInstance] setAccountStartDirectoryPhotosTab:serverUrlTo];
  435. // search PhotoVideo with new start directory
  436. [self searchPhotoVideo];
  437. }
  438. }
  439. - (void)selectStartDirectoryPhotosTab
  440. {
  441. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  442. CCMove *viewController = (CCMove *)navigationController.topViewController;
  443. viewController.delegate = self;
  444. viewController.move.title = NSLocalizedString(@"_select_dir_photos_tab_", nil);
  445. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  446. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  447. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  448. viewController.networkingOperationQueue = appDelegate.netQueue;
  449. viewController.hideCreateFolder = YES;
  450. // E2EE
  451. viewController.includeDirectoryE2EEncryption = NO;
  452. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  453. [self presentViewController:navigationController animated:YES completion:nil];
  454. }
  455. #pragma --------------------------------------------------------------------------------------------
  456. #pragma mark ==== Search Photo/Video ====
  457. #pragma --------------------------------------------------------------------------------------------
  458. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  459. {
  460. // Check Active Account
  461. if (![metadataNet.account isEqualToString:appDelegate.activeAccount]) {
  462. [self searchInProgress:NO];
  463. return;
  464. }
  465. if (errorCode == 0) {
  466. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  467. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  468. (void)[[NCManageDatabase sharedInstance] updateTableMetadatasContentTypeImageVideo:metadatas startDirectory:startDirectory activeUrl:appDelegate.activeUrl];
  469. dispatch_async(dispatch_get_main_queue(), ^{
  470. [self reloadDatasourceFromSearch:YES];
  471. });
  472. // Update date
  473. [[NCManageDatabase sharedInstance] setAccountDateSearchContentTypeImageVideo:[NSDate date]];
  474. // Save etag
  475. [_saveEtagForStartDirectory setObject:metadataNet.etag forKey:metadataNet.serverUrl];
  476. });
  477. } else {
  478. [self searchInProgress:NO];
  479. }
  480. }
  481. - (void)searchPhotoVideo
  482. {
  483. // test
  484. if (appDelegate.activeAccount.length == 0 || _isSearchMode || _isEditMode)
  485. return;
  486. // WAITING FOR d:creationdate
  487. //
  488. // tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  489. // account.dateSearchContentTypeImageVideo
  490. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  491. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  492. NSArray *items;
  493. NSError *error = [[NCNetworkingSync sharedManager] readFile:startDirectory user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword items:&items];
  494. if (error == nil && items.count > 0) {
  495. OCFileDto *fileStartDirectory = items[0];
  496. if (![fileStartDirectory.etag isEqualToString:[_saveEtagForStartDirectory objectForKey:startDirectory]]) {
  497. dispatch_async(dispatch_get_main_queue(), ^{
  498. [[CCActions sharedInstance] search:startDirectory fileName:@"" etag:fileStartDirectory.etag depth:@"infinity" date:[NSDate distantPast] contenType:@[@"image/%", @"video/%"] selector:selectorSearchContentType delegate:self];
  499. [self searchInProgress:YES];
  500. [self editingModeNO];
  501. });
  502. } else {
  503. [self reloadDatasourceFromSearch:YES];
  504. }
  505. } else {
  506. [self reloadDatasourceFromSearch:YES];
  507. }
  508. });
  509. }
  510. #pragma --------------------------------------------------------------------------------------------
  511. #pragma mark ==== Datasource ====
  512. #pragma --------------------------------------------------------------------------------------------
  513. - (void)reloadDatasourceFromSearch:(BOOL)fromSearch
  514. {
  515. @synchronized(self) {
  516. // test
  517. if (appDelegate.activeAccount.length == 0) {
  518. [self searchInProgress:NO];
  519. return;
  520. }
  521. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  522. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  523. NSArray *metadatasDBImageVideo = [[NCManageDatabase sharedInstance] getTableMetadatasContentTypeImageVideo:startDirectory activeUrl:appDelegate.activeUrl];
  524. CCSectionDataSourceMetadata *tempSectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatasDBImageVideo listProgressMetadata:nil groupByField:@"date" activeAccount:appDelegate.activeAccount];
  525. dispatch_async(dispatch_get_main_queue(), ^{
  526. // OPTIMIZED
  527. if (tempSectionDataSource.totalSize != _sectionDataSource.totalSize || tempSectionDataSource.files != _sectionDataSource.files) {
  528. _sectionDataSource = [tempSectionDataSource copy];
  529. [self.collectionView reloadData];
  530. }
  531. if (fromSearch) {
  532. [self searchInProgress:NO];
  533. }
  534. });
  535. });
  536. }
  537. }
  538. - (void)editingModeYES
  539. {
  540. [self.collectionView setAllowsMultipleSelection:true];
  541. _isEditMode = true;
  542. [self setUINavigationBarSelected];
  543. }
  544. - (void)editingModeNO
  545. {
  546. [self.collectionView setAllowsMultipleSelection:false];
  547. _isEditMode = false;
  548. [_selectedMetadatas removeAllObjects];
  549. [self setUINavigationBarDefault];
  550. }
  551. #pragma --------------------------------------------------------------------------------------------
  552. #pragma mark ==== Collection ====
  553. #pragma --------------------------------------------------------------------------------------------
  554. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  555. {
  556. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  557. }
  558. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  559. {
  560. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  561. }
  562. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  563. {
  564. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  565. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  566. return CGSizeMake(collectionView.frame.size.width / 5.1f, collectionView.frame.size.width / 5.1f);
  567. else
  568. return CGSizeMake(collectionView.frame.size.width / 7.1f, collectionView.frame.size.width / 7.1f);
  569. }
  570. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  571. {
  572. if ([_sectionDataSource.sections count] - 1 == section)
  573. return CGSizeMake(collectionView.frame.size.width, 50);
  574. return CGSizeZero;
  575. }
  576. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  577. {
  578. if (kind == UICollectionElementKindSectionHeader) {
  579. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  580. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  581. [self getGeoLocationForSection:indexPath.section];
  582. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  583. titleLabel.textColor = [UIColor blackColor];
  584. if (_sectionDataSource.sections.count > indexPath.section)
  585. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  586. return headerView;
  587. }
  588. if (kind == UICollectionElementKindSectionFooter) {
  589. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  590. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  591. titleLabel.textColor = [UIColor grayColor];
  592. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  593. return footerView;
  594. }
  595. return nil;
  596. }
  597. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  598. {
  599. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  600. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  601. UIVisualEffectView *effect = [cell viewWithTag:200];
  602. UIImageView *checked = [cell viewWithTag:300];
  603. checked.image = [UIImage imageNamed:@"checked"];
  604. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  605. if ([metadatasForKey count] > indexPath.row) {
  606. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  607. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  608. // Image
  609. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]]) {
  610. // insert Image
  611. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]];
  612. } else {
  613. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", appDelegate.activeAccount, metadata.directoryID]];
  614. // Thumbnail not present
  615. if (directory.e2eEncrypted) {
  616. imageView.image = [UIImage imageNamed:@"file_photo_encrypted"];
  617. } else {
  618. imageView.image = [UIImage imageNamed:@"file_photo"];
  619. if (metadata.thumbnailExists)
  620. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  621. }
  622. }
  623. // Cheched
  624. if (cell.selected) {
  625. checked.hidden = NO;
  626. effect.hidden = NO;
  627. effect.alpha = 0.4;
  628. } else {
  629. checked.hidden = YES;
  630. effect.hidden = YES;
  631. }
  632. }
  633. return cell;
  634. }
  635. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  636. {
  637. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  638. if ([metadatasForKey count] > indexPath.row) {
  639. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  640. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  641. if (_isEditMode) {
  642. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  643. } else {
  644. if ([self shouldPerformSegue])
  645. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  646. }
  647. }
  648. }
  649. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  650. {
  651. // test
  652. if (_isEditMode == NO)
  653. return;
  654. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  655. if ([metadatasForKey count] > indexPath.row) {
  656. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  657. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  658. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  659. }
  660. }
  661. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  662. {
  663. if (!indexPath)
  664. return NO;
  665. NSInteger section = indexPath.section;
  666. NSInteger row = indexPath.row;
  667. NSInteger lastSectionIndex = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
  668. if (section > lastSectionIndex || lastSectionIndex < 0)
  669. return NO;
  670. NSInteger rowCount = [self.collectionView numberOfItemsInSection:indexPath.section] - 1;
  671. if (rowCount < 0)
  672. return NO;
  673. return row <= rowCount;
  674. }
  675. #pragma --------------------------------------------------------------------------------------------
  676. #pragma mark ===== Navigation ====
  677. #pragma --------------------------------------------------------------------------------------------
  678. - (BOOL)shouldPerformSegue
  679. {
  680. // Test
  681. // Background ? exit
  682. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  683. return NO;
  684. // Not in first plain ? exit
  685. if (self.view.window == NO)
  686. return NO;
  687. // Collapsed but in first plain in detail exit
  688. if (self.splitViewController.isCollapsed)
  689. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  690. return NO;
  691. // ok perform segue
  692. return YES;
  693. }
  694. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  695. {
  696. id controller = segue.destinationViewController;
  697. if ([controller isKindOfClass:[UINavigationController class]]) {
  698. UINavigationController *navigationController = controller;
  699. self.detailViewController = (CCDetail *)navigationController.topViewController;
  700. } else {
  701. self.detailViewController = segue.destinationViewController;
  702. }
  703. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  704. for (NSString *fileID in _sectionDataSource.allEtag) {
  705. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  706. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  707. [allRecordsDataSourceImagesVideos addObject:metadata];
  708. }
  709. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  710. self.detailViewController.metadataDetail = _metadata;
  711. self.detailViewController.dateFilterQuery = _metadata.date;
  712. [self.detailViewController setTitle:_metadata.fileName];
  713. }
  714. @end