NCMedia.swift 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. //
  2. // NCMedia.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/02/2019.
  6. // Copyright © 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 Foundation
  24. import NCCommunication
  25. class NCMedia: UIViewController, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, NCSelectDelegate {
  26. @IBOutlet weak var collectionView : UICollectionView!
  27. private var mediaCommandView: NCMediaCommandView?
  28. private var gridLayout: NCGridMediaLayout!
  29. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  30. public var metadatas: [tableMetadata] = []
  31. private var metadataPush: tableMetadata?
  32. private var predicate: NSPredicate?
  33. private var isEditMode = false
  34. private var selectocId: [String] = []
  35. private var filterTypeFileImage = false;
  36. private var filterTypeFileVideo = false;
  37. private let kMaxImageGrid: CGFloat = 5
  38. private var cellHeigth: CGFloat = 0
  39. private var oldInProgress = false
  40. private var newInProgress = false
  41. private var lastContentOffsetY: CGFloat = 0
  42. private var mediaPath = ""
  43. struct cacheImages {
  44. static var cellPlayImage = UIImage()
  45. static var cellFavouriteImage = UIImage()
  46. }
  47. // MARK: - View Life Cycle
  48. required init?(coder aDecoder: NSCoder) {
  49. super.init(coder: aDecoder)
  50. appDelegate.activeMedia = self
  51. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: k_notificationCenter_initializeMain), object: nil)
  52. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: k_notificationCenter_reloadMediaDataSource), object: nil)
  53. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: NSNotification.Name(rawValue: k_notificationCenter_applicationWillEnterForeground), object: nil)
  54. }
  55. override func viewDidLoad() {
  56. super.viewDidLoad()
  57. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  58. collectionView.alwaysBounceVertical = true
  59. collectionView.contentInset = UIEdgeInsets(top: 75, left: 0, bottom: 50, right: 0);
  60. gridLayout = NCGridMediaLayout()
  61. gridLayout.itemPerLine = CGFloat(min(CCUtility.getMediaWidthImage(), 5))
  62. gridLayout.sectionHeadersPinToVisibleBounds = true
  63. collectionView.collectionViewLayout = gridLayout
  64. // empty Data Source
  65. collectionView.emptyDataSetDelegate = self
  66. collectionView.emptyDataSetSource = self
  67. // 3D Touch peek and pop
  68. if traitCollection.forceTouchCapability == .available {
  69. registerForPreviewing(with: self, sourceView: view)
  70. }
  71. // Notification
  72. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  73. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  74. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  75. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  76. mediaCommandView = Bundle.main.loadNibNamed("NCMediaCommandView", owner: self, options: nil)?.first as? NCMediaCommandView
  77. self.view.addSubview(mediaCommandView!)
  78. mediaCommandView?.mediaView = self
  79. mediaCommandView?.zoomInButton.isEnabled = !(self.gridLayout.itemPerLine == 1)
  80. mediaCommandView?.zoomOutButton.isEnabled = !(self.gridLayout.itemPerLine == self.kMaxImageGrid - 1)
  81. mediaCommandView?.collapseControlButtonView(true)
  82. mediaCommandView?.translatesAutoresizingMaskIntoConstraints = false
  83. mediaCommandView?.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  84. mediaCommandView?.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  85. mediaCommandView?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  86. mediaCommandView?.heightAnchor.constraint(equalToConstant: 150).isActive = true
  87. self.updateMediaControlVisibility()
  88. changeTheming()
  89. }
  90. override func viewWillAppear(_ animated: Bool) {
  91. super.viewWillAppear(animated)
  92. }
  93. override func viewDidAppear(_ animated: Bool) {
  94. super.viewDidAppear(animated)
  95. reloadDataSourceWithCompletion {
  96. self.searchNewPhotoVideo()
  97. }
  98. }
  99. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  100. super.viewWillTransition(to: size, with: coordinator)
  101. coordinator.animate(alongsideTransition: nil) { _ in
  102. self.reloadDataThenPerform { }
  103. }
  104. }
  105. override var preferredStatusBarStyle: UIStatusBarStyle {
  106. return .lightContent
  107. }
  108. //MARK: - Notification
  109. @objc func applicationWillEnterForeground() {
  110. if self.view.window != nil {
  111. self.viewDidAppear(false)
  112. }
  113. }
  114. //MARK: - Command
  115. func mediaCommandTitle() {
  116. mediaCommandView?.title.text = ""
  117. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  118. if let cell = visibleCells.first as? NCGridMediaCell {
  119. if cell.date != nil {
  120. mediaCommandView?.title.text = CCUtility.getTitleSectionDate(cell.date)
  121. }
  122. }
  123. }
  124. }
  125. @objc func zoomOutGrid() {
  126. UIView.animate(withDuration: 0.0, animations: {
  127. if(self.gridLayout.itemPerLine + 1 < self.kMaxImageGrid) {
  128. self.gridLayout.itemPerLine += 1
  129. self.mediaCommandView?.zoomInButton.isEnabled = true
  130. }
  131. if(self.gridLayout.itemPerLine == self.kMaxImageGrid - 1) {
  132. self.mediaCommandView?.zoomOutButton.isEnabled = false
  133. }
  134. self.collectionView.collectionViewLayout.invalidateLayout()
  135. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  136. })
  137. }
  138. @objc func zoomInGrid() {
  139. UIView.animate(withDuration: 0.0, animations: {
  140. if(self.gridLayout.itemPerLine - 1 > 0) {
  141. self.gridLayout.itemPerLine -= 1
  142. self.mediaCommandView?.zoomOutButton.isEnabled = true
  143. }
  144. if(self.gridLayout.itemPerLine == 1) {
  145. self.mediaCommandView?.zoomInButton.isEnabled = false
  146. }
  147. self.collectionView.collectionViewLayout.invalidateLayout()
  148. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  149. })
  150. }
  151. @objc func openMenuButtonMore(_ sender: Any) {
  152. let mainMenuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateViewController(withIdentifier: "NCMainMenuTableViewController") as! NCMainMenuTableViewController
  153. var actions: [NCMenuAction] = []
  154. if !isEditMode {
  155. if metadatas.count > 0 {
  156. actions.append(
  157. NCMenuAction(
  158. title: NSLocalizedString("_select_", comment: ""),
  159. icon: CCGraphics.changeThemingColorImage(UIImage(named: "selectFull"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  160. action: { menuAction in
  161. self.isEditMode = true
  162. }
  163. )
  164. )
  165. }
  166. actions.append(
  167. NCMenuAction(
  168. title: NSLocalizedString(filterTypeFileImage ? "_media_viewimage_show_" : "_media_viewimage_hide_", comment: ""),
  169. icon: CCGraphics.changeThemingColorImage(UIImage(named: filterTypeFileImage ? "imageno" : "imageyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  170. action: { menuAction in
  171. self.filterTypeFileImage = !self.filterTypeFileImage
  172. self.filterTypeFileVideo = false
  173. self.reloadDataSource()
  174. }
  175. )
  176. )
  177. actions.append(
  178. NCMenuAction(
  179. title: NSLocalizedString(filterTypeFileVideo ? "_media_viewvideo_show_" : "_media_viewvideo_hide_", comment: ""),
  180. icon: CCGraphics.changeThemingColorImage(UIImage(named: filterTypeFileVideo ? "videono" : "videoyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  181. action: { menuAction in
  182. self.filterTypeFileVideo = !self.filterTypeFileVideo
  183. self.filterTypeFileImage = false
  184. self.reloadDataSource()
  185. }
  186. )
  187. )
  188. actions.append(
  189. NCMenuAction(
  190. title: NSLocalizedString("_select_media_folder_", comment: ""),
  191. icon: CCGraphics.changeThemingColorImage(UIImage(named: "folderAutomaticUpload"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  192. action: { menuAction in
  193. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  194. let viewController = navigationController.topViewController as! NCSelect
  195. viewController.delegate = self
  196. viewController.hideButtonCreateFolder = true
  197. viewController.includeDirectoryE2EEncryption = false
  198. viewController.includeImages = false
  199. viewController.layoutViewSelect = k_layout_view_move
  200. viewController.selectFile = false
  201. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  202. viewController.type = "mediaFolder"
  203. viewController.heightToolBarTop = 50
  204. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  205. self.present(navigationController, animated: true, completion: nil)
  206. }
  207. )
  208. )
  209. actions.append(
  210. NCMenuAction(
  211. title: NSLocalizedString("_media_by_modified_date_", comment: ""),
  212. icon: CCGraphics.changeThemingColorImage(UIImage(named: "sortModifiedDate"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  213. selected: CCUtility.getMediaSortDate() == "date",
  214. on: true,
  215. action: { menuAction in
  216. CCUtility.setMediaSortDate("date")
  217. self.reloadDataSource()
  218. }
  219. )
  220. )
  221. actions.append(
  222. NCMenuAction(
  223. title: NSLocalizedString("_media_by_created_date_", comment: ""),
  224. icon: CCGraphics.changeThemingColorImage(UIImage(named: "sortCreatedDate"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  225. selected: CCUtility.getMediaSortDate() == "creationDate",
  226. on: true,
  227. action: { menuAction in
  228. CCUtility.setMediaSortDate("creationDate")
  229. self.reloadDataSource()
  230. }
  231. )
  232. )
  233. actions.append(
  234. NCMenuAction(
  235. title: NSLocalizedString("_media_by_upload_date_", comment: ""),
  236. icon: CCGraphics.changeThemingColorImage(UIImage(named: "sortUploadDate"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  237. selected: CCUtility.getMediaSortDate() == "uploadDate",
  238. on: true,
  239. action: { menuAction in
  240. CCUtility.setMediaSortDate("uploadDate")
  241. self.reloadDataSource()
  242. }
  243. )
  244. )
  245. } else {
  246. actions.append(
  247. NCMenuAction(
  248. title: NSLocalizedString("_cancel_", comment: ""),
  249. icon: CCGraphics.changeThemingColorImage(UIImage(named: "cancel"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  250. action: { menuAction in
  251. self.isEditMode = false
  252. self.selectocId.removeAll()
  253. self.reloadDataThenPerform { }
  254. }
  255. )
  256. )
  257. actions.append(
  258. NCMenuAction(
  259. title: NSLocalizedString("_delete_", comment: ""),
  260. icon: CCGraphics.changeThemingColorImage(UIImage(named: "trash"), width: 50, height: 50, color: .red),
  261. action: { menuAction in
  262. self.isEditMode = false
  263. for ocId in self.selectocId {
  264. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) {
  265. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.activeAccount, url: self.appDelegate.activeUrl) { (errorCode, errorDescription) in }
  266. }
  267. }
  268. }
  269. )
  270. )
  271. }
  272. mainMenuViewController.actions = actions
  273. let menuPanelController = NCMenuPanelController()
  274. menuPanelController.parentPresenter = self
  275. menuPanelController.delegate = mainMenuViewController
  276. menuPanelController.set(contentViewController: mainMenuViewController)
  277. menuPanelController.track(scrollView: mainMenuViewController.tableView)
  278. self.present(menuPanelController, animated: true, completion: nil)
  279. }
  280. // MARK: Select Path
  281. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, buttonType: String, overwrite: Bool) {
  282. if serverUrl != nil {
  283. let path = CCUtility.returnPathfromServerUrl(serverUrl, activeUrl: appDelegate.activeUrl) ?? ""
  284. NCManageDatabase.sharedInstance.setAccountMediaPath(path, account: appDelegate.activeAccount)
  285. reloadDataSourceWithCompletion {
  286. self.searchNewPhotoVideo()
  287. }
  288. }
  289. }
  290. //MARK: - NotificationCenter
  291. @objc func changeTheming() {
  292. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  293. cacheImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  294. cacheImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  295. self.navigationController?.setNavigationBarHidden(true, animated: false)
  296. }
  297. @objc func deleteFile(_ notification: NSNotification) {
  298. if let userInfo = notification.userInfo as NSDictionary? {
  299. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  300. if metadata.account == appDelegate.activeAccount {
  301. let indexes = self.metadatas.indices.filter { self.metadatas[$0].ocId == metadata.ocId }
  302. let metadatas = self.metadatas.filter { $0.ocId != metadata.ocId }
  303. self.metadatas = metadatas
  304. if self.metadatas.count == 0 {
  305. collectionView?.reloadData()
  306. } else if let row = indexes.first {
  307. let indexPath = IndexPath(row: row, section: 0)
  308. collectionView?.deleteItems(at: [indexPath])
  309. }
  310. self.updateMediaControlVisibility()
  311. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  312. let userInfo: [String : Any] = ["metadata": metadata, "type": "delete"]
  313. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  314. }
  315. }
  316. }
  317. }
  318. }
  319. @objc func moveFile(_ notification: NSNotification) {
  320. if let userInfo = notification.userInfo as NSDictionary? {
  321. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  322. if metadata.account == appDelegate.activeAccount {
  323. self.reloadDataSourceWithCompletion() {
  324. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  325. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "move"]
  326. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  327. }
  328. }
  329. }
  330. }
  331. }
  332. }
  333. @objc func renameFile(_ notification: NSNotification) {
  334. if let userInfo = notification.userInfo as NSDictionary? {
  335. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  336. if metadata.account == appDelegate.activeAccount {
  337. self.reloadDataSourceWithCompletion() {
  338. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  339. let userInfo: [String : Any] = ["metadata": metadata, "type": "rename"]
  340. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  341. }
  342. }
  343. }
  344. }
  345. }
  346. }
  347. // MARK: DZNEmpty
  348. func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
  349. return 0
  350. }
  351. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  352. return NCBrandColor.sharedInstance.backgroundView
  353. }
  354. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  355. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  356. }
  357. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  358. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  359. if oldInProgress || newInProgress {
  360. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  361. }
  362. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  363. return NSAttributedString.init(string: text, attributes: attributes)
  364. }
  365. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  366. return true
  367. }
  368. // MARK: SEGUE
  369. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  370. if let segueNavigationController = segue.destination as? UINavigationController {
  371. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  372. segueViewController.metadata = metadataPush
  373. segueViewController.metadatas = metadatas
  374. segueViewController.mediaFilterImage = true
  375. }
  376. }
  377. }
  378. }
  379. // MARK: - 3D Touch peek and pop
  380. extension NCMedia: UIViewControllerPreviewingDelegate {
  381. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  382. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  383. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  384. let metadata = metadatas[indexPath.row]
  385. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  386. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  387. previewingContext.sourceRect = cell.frame
  388. viewController.metadata = metadata
  389. viewController.imageFile = cell.imageItem.image
  390. viewController.showOpenIn = true
  391. viewController.showShare = false
  392. viewController.showOpenQuickLook = false
  393. return viewController
  394. }
  395. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  396. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  397. collectionView(collectionView, didSelectItemAt: indexPath)
  398. }
  399. }
  400. // MARK: - Collection View
  401. extension NCMedia: UICollectionViewDelegate {
  402. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  403. let metadata = metadatas[indexPath.row]
  404. metadataPush = metadata
  405. if isEditMode {
  406. if let index = selectocId.firstIndex(of: metadata.ocId) {
  407. selectocId.remove(at: index)
  408. } else {
  409. selectocId.append(metadata.ocId)
  410. }
  411. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  412. collectionView.reloadItems(at: [indexPath])
  413. }
  414. return
  415. }
  416. performSegue(withIdentifier: "segueDetail", sender: self)
  417. }
  418. }
  419. extension NCMedia: UICollectionViewDataSource {
  420. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  421. CATransaction.begin()
  422. CATransaction.setCompletionBlock(closure)
  423. collectionView?.reloadData()
  424. CATransaction.commit()
  425. }
  426. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  427. return metadatas.count
  428. }
  429. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  430. if indexPath.row < self.metadatas.count {
  431. let metadata = self.metadatas[indexPath.row]
  432. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  433. NCOperationQueue.shared.readFileForMedia(metadata: metadata)
  434. }
  435. }
  436. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  437. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
  438. let metadata = metadatas[indexPath.row]
  439. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  440. NCOperationQueue.shared.cancelReadFileForMedia(metadata: metadata)
  441. }
  442. }
  443. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  444. let metadata = metadatas[indexPath.row]
  445. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  446. self.cellHeigth = cell.frame.size.height
  447. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  448. cell.imageItem.backgroundColor = nil
  449. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  450. } else if(!metadata.hasPreview) {
  451. cell.imageItem.backgroundColor = nil
  452. if metadata.iconName.count > 0 {
  453. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  454. } else {
  455. cell.imageItem.image = UIImage.init(named: "file")
  456. }
  457. }
  458. cell.date = metadata.date as Date
  459. // image status
  460. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  461. cell.imageStatus.image = cacheImages.cellPlayImage
  462. }
  463. // image Local
  464. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  465. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  466. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  467. else { cell.imageLocal.image = UIImage.init(named: "local") }
  468. }
  469. // image Favorite
  470. if metadata.favorite {
  471. cell.imageFavorite.image = cacheImages.cellFavouriteImage
  472. }
  473. if isEditMode {
  474. cell.imageSelect.isHidden = false
  475. if selectocId.contains(metadata.ocId) {
  476. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  477. cell.imageVisualEffect.isHidden = false
  478. cell.imageVisualEffect.alpha = 0.4
  479. } else {
  480. cell.imageSelect.isHidden = true
  481. cell.imageVisualEffect.isHidden = true
  482. }
  483. } else {
  484. cell.imageSelect.isHidden = true
  485. cell.imageVisualEffect.isHidden = true
  486. }
  487. return cell
  488. }
  489. }
  490. extension NCMedia: UICollectionViewDelegateFlowLayout {
  491. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  492. return CGSize(width: collectionView.frame.width, height: 0)
  493. }
  494. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  495. return CGSize(width: collectionView.frame.width, height: 0)
  496. }
  497. }
  498. // MARK: - NC API & Algorithm
  499. extension NCMedia {
  500. @objc func reloadDataSource() {
  501. self.reloadDataSourceWithCompletion { }
  502. }
  503. private func reloadDataSourceWithCompletion(_ completion: @escaping () -> Void) {
  504. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) { return }
  505. if let tableAccount = NCManageDatabase.sharedInstance.getAccountActive() {
  506. self.mediaPath = tableAccount.mediaPath
  507. }
  508. let startServerUrl = CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) + mediaPath
  509. if filterTypeFileImage {
  510. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.activeAccount, startServerUrl, k_metadataTypeFile_video)
  511. } else if filterTypeFileVideo {
  512. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.activeAccount, startServerUrl, k_metadataTypeFile_image)
  513. } else {
  514. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND (typeFile == %@ OR typeFile == %@) AND NOT (session CONTAINS[c] 'upload')", appDelegate.activeAccount, startServerUrl, k_metadataTypeFile_image, k_metadataTypeFile_video)
  515. }
  516. NCManageDatabase.sharedInstance.getMetadatasMedia(predicate: predicate!, sort: CCUtility.getMediaSortDate()) { (metadatas) in
  517. DispatchQueue.main.sync {
  518. self.metadatas = metadatas
  519. self.reloadDataThenPerform {
  520. self.updateMediaControlVisibility()
  521. self.mediaCommandTitle()
  522. completion()
  523. }
  524. }
  525. }
  526. }
  527. func updateMediaControlVisibility() {
  528. if self.metadatas.count == 0 {
  529. if !self.filterTypeFileImage && !self.filterTypeFileVideo {
  530. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  531. self.mediaCommandView?.isHidden = false
  532. } else {
  533. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  534. self.mediaCommandView?.isHidden = false
  535. }
  536. } else {
  537. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  538. self.mediaCommandView?.isHidden = false
  539. }
  540. }
  541. private func searchOldPhotoVideo(value: Int = -30) {
  542. if oldInProgress { return }
  543. else { oldInProgress = true }
  544. collectionView.reloadData()
  545. var lessDate = Date()
  546. var greaterDate: Date
  547. if metadatas.count > 0 {
  548. lessDate = metadatas.last!.date as Date
  549. }
  550. if value == -999 {
  551. greaterDate = Date.distantPast
  552. } else {
  553. greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
  554. }
  555. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  556. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: height + 50)
  557. NCCommunication.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/" ,showHiddenFiles: CCUtility.getShowHiddenFiles(), user: appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  558. self.oldInProgress = false
  559. NCUtility.sharedInstance.stopActivityIndicator()
  560. self.collectionView.reloadData()
  561. if errorCode == 0 && account == self.appDelegate.activeAccount {
  562. if files.count > 0 {
  563. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  564. self.reloadDataSource()
  565. } else {
  566. if value == -30 {
  567. self.searchOldPhotoVideo(value: -90)
  568. } else if value == -90 {
  569. self.searchOldPhotoVideo(value: -180)
  570. } else if value == -180 {
  571. self.searchOldPhotoVideo(value: -999)
  572. }
  573. }
  574. }
  575. }
  576. }
  577. @objc func searchNewPhotoVideo() {
  578. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  579. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  580. newInProgress = true
  581. reloadDataThenPerform {
  582. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  583. if let cell = visibleCells.first as? NCGridMediaCell {
  584. if cell.date != nil {
  585. if cell.date != self.metadatas.first?.date as Date? {
  586. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  587. }
  588. }
  589. }
  590. if let cell = visibleCells.last as? NCGridMediaCell {
  591. if cell.date != nil {
  592. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  593. }
  594. }
  595. }
  596. NCCommunication.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/" ,showHiddenFiles: CCUtility.getShowHiddenFiles(), user: self.appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  597. self.newInProgress = false
  598. if errorCode == 0 && account == self.appDelegate.activeAccount && files.count > 0 {
  599. DispatchQueue.global().async {
  600. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  601. let newPredicate = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate, self.predicate!])
  602. let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: newPredicate)
  603. if metadatas.count > 0 {
  604. let etagsMetadatas = Array(metadatas.map { $0.etag })
  605. let etagsFiles = Array(files.map { $0.etag })
  606. for etag in etagsFiles {
  607. if !etagsMetadatas.contains(etag) {
  608. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  609. self.reloadDataSource()
  610. break;
  611. }
  612. }
  613. } else {
  614. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  615. self.reloadDataSource()
  616. }
  617. }
  618. } else if errorCode == 0 && files.count == 0 && self.metadatas.count == 0 {
  619. self.searchOldPhotoVideo()
  620. }
  621. }
  622. }
  623. }
  624. private func downloadThumbnail() {
  625. guard let collectionView = self.collectionView else { return }
  626. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  627. for indexPath in collectionView.indexPathsForVisibleItems {
  628. let metadata = self.metadatas[indexPath.row]
  629. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  630. }
  631. }
  632. }
  633. }
  634. // MARK: - ScrollView
  635. extension NCMedia: UIScrollViewDelegate {
  636. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  637. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
  638. mediaCommandTitle()
  639. lastContentOffsetY = scrollView.contentOffset.y
  640. }
  641. }
  642. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  643. mediaCommandView?.collapseControlButtonView(true)
  644. }
  645. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  646. if !decelerate {
  647. self.searchNewPhotoVideo()
  648. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  649. searchOldPhotoVideo()
  650. }
  651. }
  652. }
  653. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  654. self.searchNewPhotoVideo()
  655. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  656. searchOldPhotoVideo()
  657. }
  658. }
  659. }
  660. // MARK: - Media Command View
  661. class NCMediaCommandView: UIView {
  662. @IBOutlet weak var moreView: UIVisualEffectView!
  663. @IBOutlet weak var gridSwitchButton: UIButton!
  664. @IBOutlet weak var separatorView: UIView!
  665. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  666. @IBOutlet weak var zoomInButton: UIButton!
  667. @IBOutlet weak var zoomOutButton: UIButton!
  668. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  669. @IBOutlet weak var title : UILabel!
  670. var mediaView:NCMedia?
  671. private let gradient: CAGradientLayer = CAGradientLayer()
  672. override func awakeFromNib() {
  673. moreView.layer.cornerRadius = 20
  674. moreView.layer.masksToBounds = true
  675. controlButtonView.layer.cornerRadius = 20
  676. controlButtonView.layer.masksToBounds = true
  677. gradient.frame = bounds
  678. gradient.startPoint = CGPoint(x: 0, y: 0.50)
  679. gradient.endPoint = CGPoint(x: 0, y: 0.9)
  680. gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
  681. layer.insertSublayer(gradient, at: 0)
  682. title.text = ""
  683. }
  684. func toggleEmptyView(isEmpty: Bool) {
  685. if isEmpty {
  686. UIView.animate(withDuration: 0.3) {
  687. self.moreView.effect = UIBlurEffect(style: .dark)
  688. self.gradient.isHidden = true
  689. self.controlButtonView.isHidden = true
  690. }
  691. } else {
  692. UIView.animate(withDuration: 0.3) {
  693. self.moreView.effect = UIBlurEffect(style: .regular)
  694. self.gradient.isHidden = false
  695. self.controlButtonView.isHidden = false
  696. }
  697. }
  698. }
  699. @IBAction func moreButtonPressed(_ sender: UIButton) {
  700. mediaView?.openMenuButtonMore(sender)
  701. }
  702. @IBAction func zoomInPressed(_ sender: UIButton) {
  703. mediaView?.zoomInGrid()
  704. }
  705. @IBAction func zoomOutPressed(_ sender: UIButton) {
  706. mediaView?.zoomOutGrid()
  707. }
  708. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  709. self.collapseControlButtonView(false)
  710. }
  711. func collapseControlButtonView(_ collapse: Bool) {
  712. if (collapse) {
  713. self.buttonControlWidthConstraint.constant = 40
  714. UIView.animate(withDuration: 0.25) {
  715. self.zoomOutButton.isHidden = true
  716. self.zoomInButton.isHidden = true
  717. self.separatorView.isHidden = true
  718. self.gridSwitchButton.isHidden = false
  719. self.layoutIfNeeded()
  720. }
  721. } else {
  722. self.buttonControlWidthConstraint.constant = 80
  723. UIView.animate(withDuration: 0.25) {
  724. self.zoomOutButton.isHidden = false
  725. self.zoomInButton.isHidden = false
  726. self.separatorView.isHidden = false
  727. self.gridSwitchButton.isHidden = true
  728. self.layoutIfNeeded()
  729. }
  730. }
  731. }
  732. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  733. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  734. }
  735. override func layoutSublayers(of layer: CALayer) {
  736. super.layoutSublayers(of: layer)
  737. gradient.frame = bounds
  738. }
  739. }