CCPhotos.m 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. //
  2. // CCPhotos.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 29/07/15.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCPhotos.h"
  24. #import "AppDelegate.h"
  25. #import "CCManageAutoUpload.h"
  26. #import "TOScrollBar.h"
  27. #import "NCBridgeSwift.h"
  28. @interface CCPhotos () <CCActionsDeleteDelegate, CCActionsDownloadThumbnailDelegate>
  29. {
  30. AppDelegate *appDelegate;
  31. tableMetadata *_metadata;
  32. NSMutableArray *_queueMetadatas;
  33. NSMutableArray *_selectedMetadatas;
  34. NSUInteger _numSelectedMetadatas;
  35. CCSectionDataSourceMetadata *_sectionDataSource;
  36. CCHud *_hud;
  37. TOScrollBar *_scrollBar;
  38. NSMutableDictionary *_saveEtagForStartDirectory;
  39. }
  40. @end
  41. @implementation CCPhotos
  42. #pragma --------------------------------------------------------------------------------------------
  43. #pragma mark ===== Init =====
  44. #pragma --------------------------------------------------------------------------------------------
  45. - (id)initWithCoder:(NSCoder *)aDecoder
  46. {
  47. if (self = [super initWithCoder:aDecoder]) {
  48. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  49. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  50. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  51. appDelegate.activePhotos = self;
  52. }
  53. return self;
  54. }
  55. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  56. {
  57. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  58. if (self) {
  59. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  60. }
  61. return self;
  62. }
  63. #pragma --------------------------------------------------------------------------------------------
  64. #pragma mark ===== View =====
  65. #pragma --------------------------------------------------------------------------------------------
  66. - (void)viewDidLoad
  67. {
  68. [super viewDidLoad];
  69. _queueMetadatas = [NSMutableArray new];
  70. _selectedMetadatas = [NSMutableArray new];
  71. _saveEtagForStartDirectory = [NSMutableDictionary new];
  72. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  73. // empty Data Source
  74. self.collectionView.emptyDataSetDelegate = self;
  75. self.collectionView.emptyDataSetSource = self;
  76. // scroll bar
  77. _scrollBar = [TOScrollBar new];
  78. [self.collectionView to_addScrollBar:_scrollBar];
  79. _scrollBar.handleTintColor = [NCBrandColor sharedInstance].brand;
  80. _scrollBar.handleWidth = 20;
  81. _scrollBar.handleMinimiumHeight = 20;
  82. _scrollBar.trackWidth = 0;
  83. _scrollBar.edgeInset = 12;
  84. }
  85. // Apparirà
  86. - (void)viewWillAppear:(BOOL)animated
  87. {
  88. [super viewWillAppear:animated];
  89. // Color
  90. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  91. [appDelegate aspectTabBar:self.tabBarController.tabBar hidden:NO];
  92. // Plus Button
  93. [appDelegate plusButtonVisibile:true];
  94. if(!_isSearchMode && !_isEditMode)
  95. [self reloadDatasourceFromSearch:NO];
  96. }
  97. - (void)viewSafeAreaInsetsDidChange
  98. {
  99. [super viewSafeAreaInsetsDidChange];
  100. self.collectionView.contentInset = self.view.safeAreaInsets;
  101. }
  102. - (void)changeTheming
  103. {
  104. if (self.isViewLoaded && self.view.window)
  105. [appDelegate changeTheming:self];
  106. _scrollBar.handleTintColor = [NCBrandColor sharedInstance].brand;
  107. if(!_isSearchMode && !_isEditMode)
  108. [self.collectionView reloadData];
  109. }
  110. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  111. {
  112. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  113. // Before rotation
  114. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  115. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  116. // Portrait
  117. } else {
  118. // Landscape
  119. }
  120. }];
  121. }
  122. #pragma --------------------------------------------------------------------------------------------
  123. #pragma mark ===== Gestione Grafica Window =====
  124. #pragma --------------------------------------------------------------------------------------------
  125. - (void)setUINavigationBarDefault
  126. {
  127. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  128. // curront folder search
  129. NSString *directory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  130. NSString *folder = [directory stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl] withString:@""];
  131. // Title
  132. self.navigationItem.titleView = nil;
  133. if (folder.length == 0) {
  134. self.navigationItem.title = NSLocalizedString(@"_photo_camera_", nil);
  135. } else {
  136. self.navigationItem.title = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"_photo_camera_", nil), [folder substringFromIndex:1]];
  137. }
  138. if (_isSearchMode) {
  139. [CCGraphics addImageToTitle:self.navigationItem.title colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"load"] color:[NCBrandColor sharedInstance].brandText] navigationItem:self.navigationItem];
  140. [self.collectionView reloadData];
  141. return;
  142. }
  143. // Button Item
  144. UIImage *icon;
  145. icon = [UIImage imageNamed:@"select"];
  146. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(editingModeYES)];
  147. icon = [UIImage imageNamed:@"folderPhotos"];
  148. UIBarButtonItem *buttonStartDirectoryPhotosTab = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(selectStartDirectoryPhotosTab)];
  149. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  150. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  151. } else {
  152. self.navigationItem.rightBarButtonItems = nil;
  153. }
  154. self.navigationItem.leftBarButtonItems = [[NSArray alloc] initWithObjects:buttonStartDirectoryPhotosTab, nil];
  155. [self.collectionView reloadData];
  156. }
  157. - (void)setUINavigationBarSelected
  158. {
  159. UIImage *icon;
  160. icon = [UIImage imageNamed:@"delete"];
  161. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  162. icon = [UIImage imageNamed:@"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].graySoft];
  228. }
  229. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  230. {
  231. NSString *text;
  232. if (_isSearchMode) {
  233. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_search_in_progress_", nil)];
  234. } else {
  235. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  236. }
  237. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  238. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  239. }
  240. /*
  241. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  242. {
  243. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  244. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  245. paragraph.alignment = NSTextAlignmentCenter;
  246. NSString *text;
  247. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  248. if (account.autoUpload)
  249. text = [NSString stringWithFormat:@"%@", @"\n\n\n\n"];
  250. else
  251. text = [NSString stringWithFormat:@"\n%@\n", NSLocalizedString(@"_tutorial_autoupload_view_", nil)];
  252. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  253. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  254. }
  255. - (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
  256. {
  257. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  258. if (!account.autoUpload) {
  259. UIImage *buttonImage = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"button1000x200"] color:[NCBrandColor sharedInstance].brandElement];
  260. return [CCGraphics drawText:NSLocalizedString(@"_activate_autoupload_", nil) inImage:buttonImage colorText:[UIColor whiteColor] sizeOfFont:26];
  261. } else return nil;
  262. }
  263. - (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
  264. {
  265. CCManageAutoUpload *viewController = [[CCManageAutoUpload alloc] initWithNibName:nil bundle:nil];
  266. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  267. [navigationController setModalPresentationStyle:UIModalPresentationFullScreen];
  268. [self presentViewController:navigationController animated:YES completion:nil];
  269. }
  270. */
  271. #pragma --------------------------------------------------------------------------------------------
  272. #pragma mark ===== openSelectedFiles =====
  273. #pragma--------------------------------------------------------------------------------------------
  274. - (void)openSelectedFiles
  275. {
  276. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  277. for (tableMetadata *metadata in _selectedMetadatas) {
  278. NSString *fileNamePath = [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. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:self metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  492. [ocNetworking readFile:nil serverUrl:startDirectory account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  493. if (![metadata.etag isEqualToString:[_saveEtagForStartDirectory objectForKey:startDirectory]]) {
  494. [[CCActions sharedInstance] search:startDirectory fileName:@"" etag:metadata.etag depth:@"infinity" date:[NSDate distantPast] contenType:@[@"image/%", @"video/%"] selector:selectorSearchContentType delegate:self];
  495. [self searchInProgress:YES];
  496. [self editingModeNO];
  497. } else {
  498. [self reloadDatasourceFromSearch:YES];
  499. }
  500. } failure:^(NSString *message, NSInteger errorCode) {
  501. [self reloadDatasourceFromSearch:YES];
  502. }];
  503. }
  504. #pragma --------------------------------------------------------------------------------------------
  505. #pragma mark ==== Datasource ====
  506. #pragma --------------------------------------------------------------------------------------------
  507. - (void)reloadDatasourceFromSearch:(BOOL)fromSearch
  508. {
  509. @synchronized(self) {
  510. // test
  511. if (appDelegate.activeAccount.length == 0) {
  512. [self searchInProgress:NO];
  513. return;
  514. }
  515. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  516. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryPhotosTab:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  517. NSArray *metadatasDBImageVideo = [[NCManageDatabase sharedInstance] getTableMetadatasContentTypeImageVideo:startDirectory activeUrl:appDelegate.activeUrl];
  518. CCSectionDataSourceMetadata *tempSectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatasDBImageVideo listProgressMetadata:nil groupByField:@"date" activeAccount:appDelegate.activeAccount];
  519. dispatch_async(dispatch_get_main_queue(), ^{
  520. // OPTIMIZED
  521. if (tempSectionDataSource.totalSize != _sectionDataSource.totalSize || tempSectionDataSource.files != _sectionDataSource.files) {
  522. _sectionDataSource = [tempSectionDataSource copy];
  523. [self.collectionView reloadData];
  524. }
  525. if (fromSearch) {
  526. [self searchInProgress:NO];
  527. }
  528. });
  529. });
  530. }
  531. }
  532. - (void)editingModeYES
  533. {
  534. [self.collectionView setAllowsMultipleSelection:true];
  535. _isEditMode = true;
  536. [self setUINavigationBarSelected];
  537. }
  538. - (void)editingModeNO
  539. {
  540. [self.collectionView setAllowsMultipleSelection:false];
  541. _isEditMode = false;
  542. [_selectedMetadatas removeAllObjects];
  543. [self setUINavigationBarDefault];
  544. }
  545. #pragma --------------------------------------------------------------------------------------------
  546. #pragma mark ==== Collection ====
  547. #pragma --------------------------------------------------------------------------------------------
  548. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  549. {
  550. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  551. }
  552. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  553. {
  554. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  555. }
  556. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  557. {
  558. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  559. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  560. return CGSizeMake(collectionView.frame.size.width / 5.1f, collectionView.frame.size.width / 5.1f);
  561. else
  562. return CGSizeMake(collectionView.frame.size.width / 7.1f, collectionView.frame.size.width / 7.1f);
  563. }
  564. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  565. {
  566. if ([_sectionDataSource.sections count] - 1 == section)
  567. return CGSizeMake(collectionView.frame.size.width, 50);
  568. return CGSizeZero;
  569. }
  570. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  571. {
  572. if (kind == UICollectionElementKindSectionHeader) {
  573. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  574. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  575. [self getGeoLocationForSection:indexPath.section];
  576. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  577. titleLabel.textColor = [UIColor blackColor];
  578. if (_sectionDataSource.sections.count > indexPath.section)
  579. titleLabel.text = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  580. return headerView;
  581. }
  582. if (kind == UICollectionElementKindSectionFooter) {
  583. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  584. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  585. titleLabel.textColor = [UIColor grayColor];
  586. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)_sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)_sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  587. return footerView;
  588. }
  589. return nil;
  590. }
  591. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  592. {
  593. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  594. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  595. UIVisualEffectView *effect = [cell viewWithTag:200];
  596. UIImageView *checked = [cell viewWithTag:300];
  597. checked.image = [UIImage imageNamed:@"checked"];
  598. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  599. if ([metadatasForKey count] > indexPath.row) {
  600. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  601. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  602. // Image
  603. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]]) {
  604. // insert Image
  605. imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]];
  606. } else {
  607. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@", appDelegate.activeAccount, metadata.directoryID]];
  608. // Thumbnail not present
  609. if (directory.e2eEncrypted) {
  610. imageView.image = [UIImage imageNamed:@"file_photo_encrypted"];
  611. } else {
  612. imageView.image = [UIImage imageNamed:@"file_photo"];
  613. if (metadata.thumbnailExists)
  614. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  615. }
  616. }
  617. // Cheched
  618. if (cell.selected) {
  619. checked.hidden = NO;
  620. effect.hidden = NO;
  621. effect.alpha = 0.4;
  622. } else {
  623. checked.hidden = YES;
  624. effect.hidden = YES;
  625. }
  626. }
  627. return cell;
  628. }
  629. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  630. {
  631. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  632. if ([metadatasForKey count] > indexPath.row) {
  633. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  634. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  635. if (_isEditMode) {
  636. [self cellSelect:YES indexPath:indexPath metadata:_metadata];
  637. } else {
  638. if ([self shouldPerformSegue])
  639. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  640. }
  641. }
  642. }
  643. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  644. {
  645. // test
  646. if (_isEditMode == NO)
  647. return;
  648. NSArray *metadatasForKey = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  649. if ([metadatasForKey count] > indexPath.row) {
  650. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  651. _metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  652. [self cellSelect:NO indexPath:indexPath metadata:_metadata];
  653. }
  654. }
  655. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  656. {
  657. if (!indexPath)
  658. return NO;
  659. NSInteger section = indexPath.section;
  660. NSInteger row = indexPath.row;
  661. NSInteger lastSectionIndex = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
  662. if (section > lastSectionIndex || lastSectionIndex < 0)
  663. return NO;
  664. NSInteger rowCount = [self.collectionView numberOfItemsInSection:indexPath.section] - 1;
  665. if (rowCount < 0)
  666. return NO;
  667. return row <= rowCount;
  668. }
  669. #pragma --------------------------------------------------------------------------------------------
  670. #pragma mark ===== Navigation ====
  671. #pragma --------------------------------------------------------------------------------------------
  672. - (BOOL)shouldPerformSegue
  673. {
  674. // Test
  675. // Background ? exit
  676. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  677. return NO;
  678. // Not in first plain ? exit
  679. if (self.view.window == NO)
  680. return NO;
  681. // Collapsed but in first plain in detail exit
  682. if (self.splitViewController.isCollapsed)
  683. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  684. return NO;
  685. // ok perform segue
  686. return YES;
  687. }
  688. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  689. {
  690. id controller = segue.destinationViewController;
  691. if ([controller isKindOfClass:[UINavigationController class]]) {
  692. UINavigationController *navigationController = controller;
  693. self.detailViewController = (CCDetail *)navigationController.topViewController;
  694. } else {
  695. self.detailViewController = segue.destinationViewController;
  696. }
  697. NSMutableArray *allRecordsDataSourceImagesVideos = [[NSMutableArray alloc] init];
  698. for (NSString *fileID in _sectionDataSource.allEtag) {
  699. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  700. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  701. [allRecordsDataSourceImagesVideos addObject:metadata];
  702. }
  703. self.detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  704. self.detailViewController.metadataDetail = _metadata;
  705. self.detailViewController.dateFilterQuery = _metadata.date;
  706. [self.detailViewController setTitle:_metadata.fileName];
  707. }
  708. @end