CCMedia.m 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. //
  2. // CCMedia.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 "CCMedia.h"
  24. #import "AppDelegate.h"
  25. #import "CCManageAutoUpload.h"
  26. #import "TOScrollBar.h"
  27. #import "NCBridgeSwift.h"
  28. @interface CCMedia ()
  29. {
  30. AppDelegate *appDelegate;
  31. NSMutableArray *selectedMetadatas;
  32. CCSectionDataSourceMetadata *sectionDataSource;
  33. NSString *saveDirectoryID, *saveServerUrl;
  34. BOOL filterTypeFileImage;
  35. BOOL filterTypeFileVideo;
  36. BOOL isSearchMode;
  37. BOOL isEditMode;
  38. TOScrollBar *scrollBar;
  39. NSMutableDictionary *saveEtagForStartDirectory;
  40. // Fix Crash Thumbnail + collectionView ReloadData ?
  41. NSInteger counterThumbnail;
  42. BOOL collectionViewReloadDataInProgress;
  43. }
  44. @end
  45. @implementation CCMedia
  46. #pragma --------------------------------------------------------------------------------------------
  47. #pragma mark ===== Init =====
  48. #pragma --------------------------------------------------------------------------------------------
  49. - (id)initWithCoder:(NSCoder *)aDecoder
  50. {
  51. if (self = [super initWithCoder:aDecoder]) {
  52. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  53. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  54. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  55. appDelegate.activeMedia = self;
  56. }
  57. return self;
  58. }
  59. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  60. {
  61. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  62. if (self) {
  63. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  64. }
  65. return self;
  66. }
  67. #pragma --------------------------------------------------------------------------------------------
  68. #pragma mark ===== View =====
  69. #pragma --------------------------------------------------------------------------------------------
  70. - (void)viewDidLoad
  71. {
  72. [super viewDidLoad];
  73. saveEtagForStartDirectory = [NSMutableDictionary new];
  74. selectedMetadatas = [NSMutableArray new];
  75. self.addMetadatasFromUpload = [NSMutableArray new];
  76. // empty Data Source
  77. self.collectionView.emptyDataSetDelegate = self;
  78. self.collectionView.emptyDataSetSource = self;
  79. // scroll bar
  80. scrollBar = [TOScrollBar new];
  81. [self.collectionView to_addScrollBar:scrollBar];
  82. scrollBar.handleTintColor = [NCBrandColor sharedInstance].brand;
  83. scrollBar.handleWidth = 20;
  84. scrollBar.handleMinimiumHeight = 20;
  85. scrollBar.trackWidth = 0;
  86. scrollBar.edgeInset = 12;
  87. // Query data source
  88. [self queryDatasourceWithReloadData:YES];
  89. }
  90. - (void)viewWillAppear:(BOOL)animated
  91. {
  92. [super viewWillAppear:animated];
  93. // Color
  94. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  95. [appDelegate aspectTabBar:self.tabBarController.tabBar hidden:NO];
  96. // Plus Button
  97. [appDelegate plusButtonVisibile:true];
  98. }
  99. - (void)viewDidAppear:(BOOL)animated
  100. {
  101. [super viewDidAppear:animated];
  102. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  103. [self reloadDatasource:nil action:k_action_NULL];
  104. });
  105. }
  106. - (void)viewSafeAreaInsetsDidChange
  107. {
  108. [super viewSafeAreaInsetsDidChange];
  109. self.collectionView.contentInset = self.view.safeAreaInsets;
  110. }
  111. - (void)changeTheming
  112. {
  113. if (self.isViewLoaded && self.view.window)
  114. [appDelegate changeTheming:self];
  115. scrollBar.handleTintColor = [NCBrandColor sharedInstance].brand;
  116. [self.collectionView reloadData];
  117. }
  118. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  119. {
  120. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  121. // Before rotation
  122. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  123. 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))) {
  124. // Portrait
  125. } else {
  126. // Landscape
  127. }
  128. }];
  129. }
  130. #pragma --------------------------------------------------------------------------------------------
  131. #pragma mark ===== Gestione Grafica Window =====
  132. #pragma --------------------------------------------------------------------------------------------
  133. - (void)setUINavigationBarDefault
  134. {
  135. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  136. // curront folder search
  137. NSString *directory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryMediaTabView:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  138. NSString *home = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  139. NSString *folder = @"";
  140. if (home.length > 0) {
  141. folder = [directory stringByReplacingOccurrencesOfString:home withString:@""];
  142. }
  143. // Title
  144. NSString *title;
  145. if (folder.length == 0) {
  146. title = NSLocalizedString(@"_media_", nil);
  147. } else {
  148. title = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"_media_", nil), [folder substringFromIndex:1]];
  149. }
  150. self.navigationItem.titleView = nil;
  151. self.navigationItem.title = title;
  152. if (isSearchMode) {
  153. [CCGraphics addImageToTitle:title colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"load"] multiplier:2 color:[NCBrandColor sharedInstance].brandText] imageRight:YES navigationItem:self.navigationItem];
  154. }
  155. // Button Item RIGHT
  156. UIBarButtonItem *buttonSelect = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"select"] style:UIBarButtonItemStylePlain target:self action:@selector(editingModeYES)];
  157. if ([sectionDataSource.allRecordsDataSource count] > 0) {
  158. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonSelect, nil];
  159. } else {
  160. self.navigationItem.rightBarButtonItems = nil;
  161. }
  162. // Button Item LEFT
  163. UIBarButtonItem *buttonStartDirectoryPhotosTab = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"folderMedia"] style:UIBarButtonItemStylePlain target:self action:@selector(selectStartDirectoryPhotosTab)];
  164. UIBarButtonItem *buttonImageFilterYesPhotosTab = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"imageno"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonVideoFilterYes)];
  165. UIBarButtonItem *buttonImageFilterNoPhotosTab = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"imageyes"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonVideoFilterNo)];
  166. UIBarButtonItem *buttonVideoFilterYesPhotosTab = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"videono"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonImageFilterNo)];
  167. UIBarButtonItem *buttonVideoFilterNoPhotosTab = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"videoyes"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonImageFilterYes)];
  168. if (filterTypeFileImage && filterTypeFileVideo) {
  169. self.navigationItem.leftBarButtonItems = [[NSArray alloc] initWithObjects:buttonStartDirectoryPhotosTab, buttonImageFilterYesPhotosTab, buttonVideoFilterYesPhotosTab,nil];
  170. } else if (filterTypeFileImage) {
  171. self.navigationItem.leftBarButtonItems = [[NSArray alloc] initWithObjects:buttonStartDirectoryPhotosTab, buttonImageFilterYesPhotosTab, buttonVideoFilterNoPhotosTab,nil];
  172. } else if (filterTypeFileVideo) {
  173. self.navigationItem.leftBarButtonItems = [[NSArray alloc] initWithObjects:buttonStartDirectoryPhotosTab, buttonImageFilterNoPhotosTab, buttonVideoFilterYesPhotosTab,nil];
  174. } else {
  175. self.navigationItem.leftBarButtonItems = [[NSArray alloc] initWithObjects:buttonStartDirectoryPhotosTab, buttonImageFilterNoPhotosTab, buttonVideoFilterNoPhotosTab,nil];
  176. }
  177. }
  178. - (void)setUINavigationBarSelected
  179. {
  180. UIBarButtonItem *buttonDelete = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"delete"] style:UIBarButtonItemStylePlain target:self action:@selector(deleteSelectedFiles)];
  181. // UIBarButtonItem *buttonOpenIn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"openFile"] style:UIBarButtonItemStylePlain target:self action:@selector(openSelectedFiles)];
  182. UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(editingModeNO)];
  183. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:cancelButton, nil];
  184. self.navigationItem.leftBarButtonItems = [[NSArray alloc] initWithObjects:buttonDelete, nil];
  185. // Title
  186. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[selectedMetadatas count], (unsigned long)[sectionDataSource.allRecordsDataSource count]];
  187. }
  188. - (void)cellSelect:(BOOL)select indexPath:(NSIndexPath *)indexPath metadata:(tableMetadata *)metadata
  189. {
  190. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  191. UIVisualEffectView *effect = [cell viewWithTag:200];
  192. UIImageView *checked = [cell viewWithTag:300];
  193. if (select) {
  194. effect.hidden = NO;
  195. effect.alpha = 0.4;
  196. checked.hidden = NO;
  197. [selectedMetadatas addObject:metadata];
  198. } else {
  199. effect.hidden = YES;
  200. checked.hidden = YES;
  201. [selectedMetadatas removeObject:metadata];
  202. }
  203. // Title
  204. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)[selectedMetadatas count], (unsigned long)[sectionDataSource.allRecordsDataSource count]];
  205. }
  206. - (void)scrollToTop
  207. {
  208. [self.collectionView setContentOffset:CGPointMake(0, - self.collectionView.contentInset.top) animated:NO];
  209. }
  210. - (void)getGeoLocationForSection:(NSInteger)section
  211. {
  212. NSString *addLocation = @"";
  213. NSArray *fileIDsForKey = [sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]];
  214. for (NSString *fileID in fileIDsForKey) {
  215. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  216. if ([localFile.exifLatitude floatValue] > 0 || [localFile.exifLongitude floatValue] > 0) {
  217. NSString *location = [[NCManageDatabase sharedInstance] getLocationFromGeoLatitude:localFile.exifLatitude longitude:localFile.exifLongitude];
  218. addLocation = [NSString stringWithFormat:@"%@, %@", addLocation, location];
  219. }
  220. }
  221. }
  222. #pragma --------------------------------------------------------------------------------------------
  223. #pragma mark ==== DZNEmptyDataSetSource Methods ====
  224. #pragma --------------------------------------------------------------------------------------------
  225. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  226. {
  227. return [NCBrandColor sharedInstance].backgroundView;
  228. }
  229. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  230. {
  231. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"mediaNoRecord"] multiplier:2 color:[NCBrandColor sharedInstance].graySoft];
  232. }
  233. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  234. {
  235. NSString *text;
  236. if (isSearchMode) {
  237. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_search_in_progress_", nil)];
  238. } else {
  239. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_tutorial_photo_view_", nil)];
  240. }
  241. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  242. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  243. }
  244. /*
  245. #pragma --------------------------------------------------------------------------------------------
  246. #pragma mark ===== openSelectedFiles =====
  247. #pragma--------------------------------------------------------------------------------------------
  248. - (void)openSelectedFiles
  249. {
  250. NSMutableArray *dataToShare = [[NSMutableArray alloc] init];
  251. for (tableMetadata *metadata in selectedMetadatas) {
  252. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileName:metadata.fileNameView];
  253. if ([CCUtility fileProviderStorageExists:metadata.fileID fileName:metadata.fileNameView]) {
  254. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  255. NSData *data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:fileNamePath], 0.9)];
  256. [dataToShare addObject:data];
  257. }
  258. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  259. [dataToShare addObject:[NSURL fileURLWithPath:fileNamePath]];
  260. }
  261. }
  262. }
  263. if ([dataToShare count] > 0) {
  264. UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
  265. // iPad
  266. activityViewController.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.lastObject;
  267. self.navigationItem.leftBarButtonItem.enabled = NO;
  268. self.navigationItem.rightBarButtonItem.enabled = NO;
  269. [self presentViewController:activityViewController animated:YES completion:^{
  270. [activityViewController setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
  271. self.navigationItem.leftBarButtonItem.enabled = YES;
  272. self.navigationItem.rightBarButtonItem.enabled = YES;
  273. [self editingModeNO];
  274. if (completed) {
  275. [self.collectionView reloadData];
  276. }
  277. }];
  278. }];
  279. }
  280. }
  281. */
  282. #pragma --------------------------------------------------------------------------------------------
  283. #pragma mark ===== Download =====
  284. #pragma--------------------------------------------------------------------------------------------
  285. - (void)triggerProgressTask:(NSNotification *)notification
  286. {
  287. //NSDictionary *dict = notification.userInfo;
  288. //float progress = [[dict valueForKey:@"progress"] floatValue];
  289. }
  290. - (void)downloadFileSuccessFailure:(NSString *)fileName fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector errorMessage:(NSString *)errorMessage errorCode:(NSInteger)errorCode
  291. {
  292. if (errorCode == 0) {
  293. NSIndexPath *indexPath;
  294. BOOL existsIcon = NO;
  295. if (fileID) {
  296. existsIcon = [[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:fileID fileNameView:fileName]];
  297. indexPath = [sectionDataSource.fileIDIndexPath objectForKey:fileID];
  298. }
  299. if ([self indexPathIsValid:indexPath] && existsIcon) {
  300. UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
  301. if (cell) {
  302. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  303. UIVisualEffectView *effect = [cell viewWithTag:200];
  304. UIImageView *checked = [cell viewWithTag:300];
  305. imageView.image = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:fileID fileNameView:fileName]];
  306. effect.hidden = YES;
  307. checked.hidden = YES;
  308. }
  309. }
  310. } else {
  311. [appDelegate messageNotification:@"_download_selected_files_" description:@"_error_download_photobrowser_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  312. }
  313. }
  314. #pragma --------------------------------------------------------------------------------------------
  315. #pragma mark ===== Delete =====
  316. #pragma--------------------------------------------------------------------------------------------
  317. - (void)deleteFile:(NSArray *)metadatas e2ee:(BOOL)e2ee
  318. {
  319. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:metadatas e2ee:false serverUrl:@"" folderFileID:@"" completion:^(NSInteger errorCode, NSString *message) {
  320. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:nil fileID:nil action:k_action_NULL];
  321. }];
  322. [self editingModeNO];
  323. }
  324. - (void)deleteSelectedFiles
  325. {
  326. if ([selectedMetadatas count] == 0)
  327. return;
  328. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  329. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  330. style:UIAlertActionStyleDestructive
  331. handler:^(UIAlertAction *action) {
  332. [self deleteFile:selectedMetadatas e2ee:false];
  333. }]];
  334. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  335. style:UIAlertActionStyleCancel
  336. handler:^(UIAlertAction *action) {
  337. }]];
  338. alertController.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItems.firstObject;
  339. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  340. [alertController.view layoutIfNeeded];
  341. [self presentViewController:alertController animated:YES completion:NULL];
  342. }
  343. #pragma --------------------------------------------------------------------------------------------
  344. #pragma mark ==== Download Thumbnail ====
  345. #pragma --------------------------------------------------------------------------------------------
  346. - (void)downloadThumbnail:(tableMetadata *)metadata indexPath:(NSIndexPath *)indexPath
  347. {
  348. if (![saveDirectoryID isEqualToString:metadata.directoryID]) {
  349. saveDirectoryID = metadata.directoryID;
  350. saveServerUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  351. if (!saveServerUrl)
  352. return;
  353. }
  354. counterThumbnail++;
  355. CGFloat width = [[NCUtility sharedInstance] getScreenWidthForPreview];
  356. CGFloat height = [[NCUtility sharedInstance] getScreenHeightForPreview];
  357. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  358. [ocNetworking downloadPreviewWithMetadata:metadata serverUrl:saveServerUrl withWidth:width andHeight:height completion:^(NSString *message, NSInteger errorCode) {
  359. counterThumbnail--;
  360. if (errorCode == 0 && [[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]] && [self indexPathIsValid:indexPath] && !collectionViewReloadDataInProgress) {
  361. [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
  362. }
  363. }];
  364. }
  365. #pragma --------------------------------------------------------------------------------------------
  366. #pragma mark ==== Change Start directory ====
  367. #pragma --------------------------------------------------------------------------------------------
  368. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  369. {
  370. NSString *oldStartDirectoryMediaTabView = [[NCManageDatabase sharedInstance] getAccountStartDirectoryMediaTabView:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  371. if (![serverUrlTo isEqualToString:oldStartDirectoryMediaTabView]) {
  372. // Save Start Directory
  373. [[NCManageDatabase sharedInstance] setAccountStartDirectoryMediaTabView:serverUrlTo];
  374. // search PhotoVideo with new start directory
  375. [self searchPhotoVideo];
  376. }
  377. }
  378. - (void)selectStartDirectoryPhotosTab
  379. {
  380. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  381. CCMove *viewController = (CCMove *)navigationController.topViewController;
  382. viewController.delegate = self;
  383. viewController.move.title = NSLocalizedString(@"_select_dir_media_tab_", nil);
  384. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  385. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  386. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  387. viewController.networkingOperationQueue = appDelegate.netQueue;
  388. viewController.hideCreateFolder = YES;
  389. // E2EE
  390. viewController.includeDirectoryE2EEncryption = NO;
  391. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  392. [self presentViewController:navigationController animated:YES completion:nil];
  393. }
  394. #pragma --------------------------------------------------------------------------------------------
  395. #pragma mark ==== Filter Image Video====
  396. #pragma --------------------------------------------------------------------------------------------
  397. - (void)buttonImageFilterYes
  398. {
  399. filterTypeFileImage = !filterTypeFileImage;
  400. [self reloadDatasource:nil action:k_action_NULL];
  401. }
  402. - (void)buttonImageFilterNo
  403. {
  404. if (filterTypeFileVideo) {
  405. filterTypeFileVideo = NO;
  406. } else {
  407. filterTypeFileImage = !filterTypeFileImage;
  408. }
  409. [self reloadDatasource:nil action:k_action_NULL];
  410. }
  411. - (void)buttonVideoFilterYes
  412. {
  413. if (filterTypeFileImage) {
  414. filterTypeFileImage = NO;
  415. } else {
  416. filterTypeFileVideo = !filterTypeFileVideo;
  417. }
  418. [self reloadDatasource:nil action:k_action_NULL];
  419. }
  420. - (void)buttonVideoFilterNo
  421. {
  422. filterTypeFileVideo = !filterTypeFileVideo;
  423. [self reloadDatasource:nil action:k_action_NULL];
  424. }
  425. #pragma --------------------------------------------------------------------------------------------
  426. #pragma mark ==== Search Photo/Video ====
  427. #pragma --------------------------------------------------------------------------------------------
  428. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  429. {
  430. isSearchMode = NO;
  431. if (![metadataNet.account isEqualToString:appDelegate.activeAccount] || errorCode != 0) {
  432. [self reloadDatasource:nil action:k_action_NULL];
  433. } else {
  434. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  435. // Clear all Hardcoded new foto/video from CCNetworking
  436. [self.addMetadatasFromUpload removeAllObjects];
  437. [[NCManageDatabase sharedInstance] createTablePhotos:metadatas];
  438. dispatch_async(dispatch_get_main_queue(), ^{
  439. [self reloadDatasource:nil action:k_action_NULL];
  440. });
  441. // Update date
  442. [[NCManageDatabase sharedInstance] setAccountDateSearchContentTypeImageVideo:[NSDate date]];
  443. // Save etag
  444. [saveEtagForStartDirectory setObject:metadataNet.etag forKey:metadataNet.serverUrl];
  445. });
  446. }
  447. }
  448. - (void)searchPhotoVideo
  449. {
  450. // test
  451. if (appDelegate.activeAccount.length == 0 || isSearchMode)
  452. return;
  453. // WAITING FOR d:creationdate
  454. //
  455. // tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  456. // account.dateSearchContentTypeImageVideo
  457. NSString *startDirectory = [[NCManageDatabase sharedInstance] getAccountStartDirectoryMediaTabView:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]];
  458. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:self metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  459. [ocNetworking readFile:nil serverUrl:startDirectory account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  460. if (![metadata.etag isEqualToString:[saveEtagForStartDirectory objectForKey:startDirectory]] || sectionDataSource.allRecordsDataSource.count == 0) {
  461. isSearchMode = YES;
  462. [self editingModeNO];
  463. [[CCActions sharedInstance] search:startDirectory fileName:@"" etag:metadata.etag depth:@"infinity" date:[NSDate distantPast] contenType:@[@"image/%", @"video/%"] selector:selectorSearchContentType delegate:self];
  464. } else {
  465. [self reloadDatasource:nil action:k_action_NULL];
  466. }
  467. } failure:^(NSString *message, NSInteger errorCode) {
  468. }];
  469. }
  470. #pragma --------------------------------------------------------------------------------------------
  471. #pragma mark ==== Datasource ====
  472. #pragma --------------------------------------------------------------------------------------------
  473. - (void)reloadDatasource:(NSString *)fileID action:(NSInteger)action
  474. {
  475. // test
  476. if (appDelegate.activeAccount.length == 0 || self.view.window == nil) {
  477. return;
  478. }
  479. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  480. collectionViewReloadDataInProgress = YES;
  481. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO];
  482. dispatch_async(dispatch_get_main_queue(), ^{
  483. if (isEditMode)
  484. [self setUINavigationBarSelected];
  485. else
  486. [self setUINavigationBarDefault];
  487. sectionDataSource = sectionDataSourceTemp;
  488. [self.collectionView reloadData];
  489. [self.collectionView performBatchUpdates:^{} completion:^(BOOL finished) {
  490. collectionViewReloadDataInProgress = NO;
  491. }];
  492. });
  493. });
  494. }
  495. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData
  496. {
  497. // test
  498. if (appDelegate.activeAccount.length == 0) {
  499. return nil;
  500. }
  501. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  502. NSArray *metadatas = [[NCManageDatabase sharedInstance] getTablePhotosWithAddMetadatasFromUpload:self.addMetadatasFromUpload];
  503. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:@"date" filterFileID:appDelegate.filterFileID filterTypeFileImage:filterTypeFileImage filterTypeFileVideo:filterTypeFileVideo activeAccount:appDelegate.activeAccount];
  504. if (withReloadData) {
  505. sectionDataSource = sectionDataSourceTemp;
  506. [self.collectionView reloadData];
  507. }
  508. return sectionDataSourceTemp;
  509. }
  510. - (void)editingModeYES
  511. {
  512. [self.collectionView setAllowsMultipleSelection:true];
  513. isEditMode = true;
  514. [selectedMetadatas removeAllObjects];
  515. [self setUINavigationBarSelected];
  516. collectionViewReloadDataInProgress = YES;
  517. [self.collectionView reloadData];
  518. [self.collectionView performBatchUpdates:^{} completion:^(BOOL finished) {
  519. collectionViewReloadDataInProgress = NO;
  520. }];
  521. }
  522. - (void)editingModeNO
  523. {
  524. [self.collectionView setAllowsMultipleSelection:false];
  525. isEditMode = false;
  526. [selectedMetadatas removeAllObjects];
  527. [self setUINavigationBarDefault];
  528. collectionViewReloadDataInProgress = YES;
  529. [self.collectionView reloadData];
  530. [self.collectionView performBatchUpdates:^{} completion:^(BOOL finished) {
  531. collectionViewReloadDataInProgress = NO;
  532. }];
  533. }
  534. #pragma --------------------------------------------------------------------------------------------
  535. #pragma mark ==== Collection ====
  536. #pragma --------------------------------------------------------------------------------------------
  537. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  538. {
  539. return indexPath.section < [self numberOfSectionsInCollectionView:self.collectionView] && indexPath.row < [self collectionView:self.collectionView numberOfItemsInSection:indexPath.section];
  540. }
  541. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
  542. {
  543. return [[sectionDataSource.sectionArrayRow allKeys] count];
  544. }
  545. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
  546. {
  547. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  548. }
  549. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
  550. {
  551. UIInterfaceOrientation orientationOnLunch = [[UIApplication sharedApplication] statusBarOrientation];
  552. if (orientationOnLunch == UIInterfaceOrientationPortrait)
  553. return CGSizeMake(collectionView.frame.size.width / 5.1f, collectionView.frame.size.width / 5.1f);
  554. else
  555. return CGSizeMake(collectionView.frame.size.width / 7.1f, collectionView.frame.size.width / 7.1f);
  556. }
  557. -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
  558. {
  559. if ([sectionDataSource.sections count] - 1 == section)
  560. return CGSizeMake(collectionView.frame.size.width, 50);
  561. return CGSizeZero;
  562. }
  563. - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  564. {
  565. if (kind == UICollectionElementKindSectionHeader) {
  566. UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
  567. //headerView.backgroundColor = COLOR_GROUPBY_BAR_NO_BLUR;
  568. [self getGeoLocationForSection:indexPath.section];
  569. UILabel *titleLabel = (UILabel *)[headerView viewWithTag:100];
  570. titleLabel.textColor = [UIColor blackColor];
  571. if (sectionDataSource.sections.count > indexPath.section)
  572. titleLabel.text = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:indexPath.section]];
  573. return headerView;
  574. }
  575. if (kind == UICollectionElementKindSectionFooter) {
  576. UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
  577. UILabel *titleLabel = (UILabel *)[footerView viewWithTag:100];
  578. titleLabel.textColor = [UIColor grayColor];
  579. titleLabel.text = [NSString stringWithFormat:@"%lu %@, %lu %@", (long)sectionDataSource.image, NSLocalizedString(@"photo", nil), (long)sectionDataSource.video, NSLocalizedString(@"_video_", nil)];
  580. return footerView;
  581. }
  582. return nil;
  583. }
  584. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  585. {
  586. UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
  587. UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
  588. UIVisualEffectView *effect = [cell viewWithTag:200];
  589. UIImageView *checkedOverlay = [cell viewWithTag:300];
  590. checkedOverlay.image = [UIImage imageNamed:@"checked"];
  591. UIImageView *videoOverlay = [cell viewWithTag:400];
  592. videoOverlay.image = [UIImage imageNamed:@"VideoOverlay"];
  593. NSArray *metadatasForKey = [sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:indexPath.section]];
  594. if ([metadatasForKey count] > indexPath.row) {
  595. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  596. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  597. // Image
  598. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]]) {
  599. // insert Image
  600. imageView.image = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  601. } else {
  602. imageView.image = [UIImage imageNamed:@"file_photo"];
  603. if (metadata.thumbnailExists && ![CCUtility fileProviderStorageIconExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  604. [self downloadThumbnail:metadata indexPath:indexPath];
  605. }
  606. }
  607. // Cheched Overlay
  608. if (cell.selected) {
  609. checkedOverlay.hidden = NO;
  610. effect.hidden = NO;
  611. effect.alpha = 0.4;
  612. } else {
  613. checkedOverlay.hidden = YES;
  614. effect.hidden = YES;
  615. }
  616. // Video Overlay
  617. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  618. videoOverlay.hidden = NO;
  619. } else {
  620. videoOverlay.hidden = YES;
  621. }
  622. }
  623. return cell;
  624. }
  625. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  626. {
  627. NSArray *metadatasForKey = [sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:indexPath.section]];
  628. if ([metadatasForKey count] > indexPath.row) {
  629. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  630. self.metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  631. if (isEditMode) {
  632. [self cellSelect:YES indexPath:indexPath metadata:self.metadata];
  633. } else {
  634. if ([self shouldPerformSegue])
  635. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  636. }
  637. }
  638. }
  639. - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
  640. {
  641. // test
  642. if (isEditMode == NO)
  643. return;
  644. NSArray *metadatasForKey = [sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:indexPath.section]];
  645. if ([metadatasForKey count] > indexPath.row) {
  646. NSString *fileID = [metadatasForKey objectAtIndex:indexPath.row];
  647. self.metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  648. [self cellSelect:NO indexPath:indexPath metadata:self.metadata];
  649. }
  650. }
  651. #pragma --------------------------------------------------------------------------------------------
  652. #pragma mark ===== Navigation ====
  653. #pragma --------------------------------------------------------------------------------------------
  654. - (BOOL)shouldPerformSegue
  655. {
  656. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
  657. return NO;
  658. // Not in first plain ? exit
  659. if (self.view.window == NO)
  660. return NO;
  661. // Collapsed but in first plain in detail exit
  662. if (self.splitViewController.isCollapsed)
  663. if (self.detailViewController.isViewLoaded && self.detailViewController.view.window)
  664. return NO;
  665. // check if metadata is invalidated
  666. if ([[NCManageDatabase sharedInstance] isTableInvalidated:self.metadata]) {
  667. return NO;
  668. }
  669. // ok perform segue
  670. return YES;
  671. }
  672. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  673. {
  674. id controller = segue.destinationViewController;
  675. if ([controller isKindOfClass:[UINavigationController class]]) {
  676. UINavigationController *navigationController = controller;
  677. self.detailViewController = (CCDetail *)navigationController.topViewController;
  678. } else {
  679. self.detailViewController = segue.destinationViewController;
  680. }
  681. NSMutableArray *photoDataSource = [NSMutableArray new];
  682. for (NSString *fileID in sectionDataSource.allFileID) {
  683. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  684. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  685. [photoDataSource addObject:metadata];
  686. }
  687. self.detailViewController.photoDataSource = photoDataSource;
  688. self.detailViewController.metadataDetail = self.metadata;
  689. self.detailViewController.dateFilterQuery = self.metadata.date;
  690. [self.detailViewController setTitle:self.metadata.fileName];
  691. }
  692. @end