NCMedia.swift 44 KB

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