NCMedia.swift 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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_", comment: ""),
  287. icon: CCGraphics.changeThemingColorImage(UIImage(named: "trash"), width: 50, height: 50, color: .red),
  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 verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
  380. return 0
  381. }
  382. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  383. return NCBrandColor.sharedInstance.backgroundView
  384. }
  385. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  386. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: .gray)
  387. }
  388. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  389. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  390. if oldInProgress || newInProgress {
  391. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  392. }
  393. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.gray]
  394. return NSAttributedString.init(string: text, attributes: attributes)
  395. }
  396. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  397. return true
  398. }
  399. // MARK: SEGUE
  400. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  401. if let segueNavigationController = segue.destination as? UINavigationController {
  402. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  403. segueViewController.metadata = metadataTouch
  404. segueViewController.metadatas = metadatas
  405. segueViewController.mediaFilterImage = true
  406. segueViewController.layoutKey = k_layout_view_media
  407. }
  408. }
  409. }
  410. }
  411. // MARK: - 3D Touch peek and pop
  412. extension NCMedia: UIViewControllerPreviewingDelegate {
  413. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  414. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  415. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  416. let metadata = metadatas[indexPath.row]
  417. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  418. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  419. previewingContext.sourceRect = cell.frame
  420. viewController.metadata = metadata
  421. viewController.imageFile = cell.imageItem.image
  422. viewController.showOpenIn = true
  423. viewController.showShare = false
  424. viewController.showOpenQuickLook = false
  425. return viewController
  426. }
  427. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  428. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  429. collectionView(collectionView, didSelectItemAt: indexPath)
  430. }
  431. }
  432. // MARK: - Collection View
  433. extension NCMedia: UICollectionViewDelegate {
  434. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  435. let metadata = metadatas[indexPath.row]
  436. metadataTouch = metadata
  437. if isEditMode {
  438. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  439. selectOcId.remove(at: index)
  440. } else {
  441. selectOcId.append(metadata.ocId)
  442. }
  443. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  444. collectionView.reloadItems(at: [indexPath])
  445. }
  446. return
  447. }
  448. performSegue(withIdentifier: "segueDetail", sender: self)
  449. }
  450. }
  451. extension NCMedia: UICollectionViewDataSourcePrefetching {
  452. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  453. //print("[LOG] n. " + String(indexPaths.count))
  454. }
  455. }
  456. extension NCMedia: UICollectionViewDataSource {
  457. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  458. CATransaction.begin()
  459. CATransaction.setCompletionBlock(closure)
  460. collectionView?.reloadData()
  461. CATransaction.commit()
  462. }
  463. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  464. return metadatas.count
  465. }
  466. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  467. if indexPath.row < self.metadatas.count {
  468. let metadata = self.metadatas[indexPath.row]
  469. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  470. }
  471. }
  472. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  473. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
  474. let metadata = metadatas[indexPath.row]
  475. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  476. }
  477. }
  478. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  479. let metadata = metadatas[indexPath.row]
  480. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  481. self.cellHeigth = cell.frame.size.height
  482. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  483. cell.imageItem.backgroundColor = nil
  484. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  485. } else if(!metadata.hasPreview) {
  486. cell.imageItem.backgroundColor = nil
  487. if metadata.iconName.count > 0 {
  488. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  489. } else {
  490. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  491. }
  492. }
  493. cell.date = metadata.date as Date
  494. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  495. cell.imageStatus.image = cacheImages.cellPlayImage
  496. } else if metadata.livePhoto && livePhoto {
  497. cell.imageStatus.image = cacheImages.cellLivePhotoImage
  498. }
  499. if isEditMode {
  500. cell.selectMode(true)
  501. if selectOcId.contains(metadata.ocId) {
  502. cell.selected(true)
  503. } else {
  504. cell.selected(false)
  505. }
  506. } else {
  507. cell.selectMode(false)
  508. }
  509. return cell
  510. }
  511. }
  512. extension NCMedia: UICollectionViewDelegateFlowLayout {
  513. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  514. return CGSize(width: collectionView.frame.width, height: 0)
  515. }
  516. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  517. return CGSize(width: collectionView.frame.width, height: 0)
  518. }
  519. }
  520. // MARK: - NC API & Algorithm
  521. extension NCMedia {
  522. @objc func reloadDataSource() {
  523. self.reloadDataSourceWithCompletion { (_) in }
  524. }
  525. @objc func reloadDataSourceWithCompletion(_ completion: @escaping (_ metadatas: [tableMetadata]) -> Void) {
  526. if (appDelegate.account == nil || appDelegate.account.count == 0 || appDelegate.maintenanceMode == true) { return }
  527. if account != appDelegate.account {
  528. self.metadatas = []
  529. account = appDelegate.account
  530. collectionView?.reloadData()
  531. }
  532. livePhoto = CCUtility.getLivePhoto()
  533. if let tableAccount = NCManageDatabase.sharedInstance.getAccountActive() {
  534. self.mediaPath = tableAccount.mediaPath
  535. }
  536. let startServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) + mediaPath
  537. 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)
  538. if filterTypeFileImage {
  539. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, k_metadataTypeFile_video)
  540. } else if filterTypeFileVideo {
  541. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, k_metadataTypeFile_image)
  542. } else {
  543. predicate = predicateDefault
  544. }
  545. guard var predicateForGetMetadatasMedia = predicate else { return }
  546. if livePhoto {
  547. let predicateLivePhoto = NSPredicate(format: "!(ext == 'mov' AND livePhoto == true)")
  548. predicateForGetMetadatasMedia = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateForGetMetadatasMedia, predicateLivePhoto])
  549. }
  550. DispatchQueue.global().async {
  551. self.metadatas = NCManageDatabase.sharedInstance.getMetadatasMedia(predicate: predicateForGetMetadatasMedia, sort: CCUtility.getMediaSortDate())
  552. DispatchQueue.main.sync {
  553. self.reloadDataThenPerform {
  554. self.updateMediaControlVisibility()
  555. self.mediaCommandTitle()
  556. completion(self.metadatas)
  557. }
  558. }
  559. }
  560. }
  561. func updateMediaControlVisibility() {
  562. if self.metadatas.count == 0 {
  563. if !self.filterTypeFileImage && !self.filterTypeFileVideo {
  564. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  565. self.mediaCommandView?.isHidden = false
  566. } else {
  567. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  568. self.mediaCommandView?.isHidden = false
  569. }
  570. } else {
  571. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  572. self.mediaCommandView?.isHidden = false
  573. }
  574. }
  575. private func searchOldPhotoVideo(value: Int = -30, limit: Int = 300) {
  576. if oldInProgress { return }
  577. else { oldInProgress = true }
  578. collectionView.reloadData()
  579. var lessDate = Date()
  580. if predicateDefault != nil {
  581. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: predicateDefault!, sorted: "date", ascending: true) {
  582. lessDate = metadata.date as Date
  583. }
  584. }
  585. var greaterDate: Date
  586. if value == -999 {
  587. greaterDate = Date.distantPast
  588. } else {
  589. greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
  590. }
  591. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  592. NCUtility.shared.startActivityIndicator(view: self.view, bottom: height + 50)
  593. NCCommunication.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), timeout: 120) { (account, files, errorCode, errorDescription) in
  594. self.oldInProgress = false
  595. NCUtility.shared.stopActivityIndicator()
  596. self.collectionView.reloadData()
  597. if errorCode == 0 && account == self.appDelegate.account {
  598. if files.count > 0 {
  599. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: self.appDelegate.account) { (_, _, metadatas) in
  600. let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  601. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateDate, self.predicateDefault!])
  602. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicateResult)
  603. let metadatasChanged = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  604. if metadatasChanged.metadatasUpdate.count == 0 {
  605. self.researchOldPhotoVideo(value: value, limit: limit, withElseReloadDataSource: true)
  606. } else {
  607. self.reloadDataSource()
  608. }
  609. }
  610. } else {
  611. self.researchOldPhotoVideo(value: value, limit: limit, withElseReloadDataSource: false)
  612. }
  613. }
  614. }
  615. }
  616. private func researchOldPhotoVideo(value: Int , limit: Int, withElseReloadDataSource: Bool) {
  617. if value == -30 {
  618. searchOldPhotoVideo(value: -90)
  619. } else if value == -90 {
  620. searchOldPhotoVideo(value: -180)
  621. } else if value == -180 {
  622. searchOldPhotoVideo(value: -999)
  623. } else if value == -999 && limit > 0 {
  624. searchOldPhotoVideo(value: -999, limit: 0)
  625. } else {
  626. if withElseReloadDataSource {
  627. reloadDataSource()
  628. }
  629. }
  630. }
  631. @objc func searchNewPhotoVideo(limit: Int = 300) {
  632. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  633. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  634. newInProgress = true
  635. reloadDataThenPerform {
  636. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  637. if let cell = visibleCells.first as? NCGridMediaCell {
  638. if cell.date != nil {
  639. if cell.date != self.metadatas.first?.date as Date? {
  640. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  641. }
  642. }
  643. }
  644. if let cell = visibleCells.last as? NCGridMediaCell {
  645. if cell.date != nil {
  646. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  647. }
  648. }
  649. }
  650. 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
  651. self.newInProgress = false
  652. if errorCode == 0 && account == self.appDelegate.account && files.count > 0 {
  653. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
  654. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  655. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate, self.predicate!])
  656. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicateResult)
  657. let updateMetadatas = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  658. if updateMetadatas.metadatasUpdate.count > 0 {
  659. self.reloadDataSource()
  660. }
  661. }
  662. } else if errorCode == 0 && files.count == 0 && limit > 0 {
  663. self.searchNewPhotoVideo(limit: 0)
  664. } else if errorCode == 0 && files.count == 0 && self.metadatas.count == 0 {
  665. self.searchOldPhotoVideo()
  666. }
  667. }
  668. }
  669. }
  670. private func downloadThumbnail() {
  671. guard let collectionView = self.collectionView else { return }
  672. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  673. for indexPath in collectionView.indexPathsForVisibleItems {
  674. let metadata = self.metadatas[indexPath.row]
  675. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  676. }
  677. }
  678. }
  679. }
  680. // MARK: - ScrollView
  681. extension NCMedia: UIScrollViewDelegate {
  682. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  683. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
  684. mediaCommandTitle()
  685. lastContentOffsetY = scrollView.contentOffset.y
  686. }
  687. }
  688. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  689. mediaCommandView?.collapseControlButtonView(true)
  690. }
  691. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  692. if !decelerate {
  693. self.searchNewPhotoVideo()
  694. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  695. searchOldPhotoVideo()
  696. }
  697. }
  698. }
  699. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  700. self.searchNewPhotoVideo()
  701. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  702. searchOldPhotoVideo()
  703. }
  704. }
  705. }
  706. // MARK: - Media Command View
  707. class NCMediaCommandView: UIView {
  708. @IBOutlet weak var moreView: UIVisualEffectView!
  709. @IBOutlet weak var gridSwitchButton: UIButton!
  710. @IBOutlet weak var separatorView: UIView!
  711. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  712. @IBOutlet weak var zoomInButton: UIButton!
  713. @IBOutlet weak var zoomOutButton: UIButton!
  714. @IBOutlet weak var moreButton: UIButton!
  715. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  716. @IBOutlet weak var title : UILabel!
  717. var mediaView:NCMedia?
  718. private let gradient: CAGradientLayer = CAGradientLayer()
  719. override func awakeFromNib() {
  720. moreView.layer.cornerRadius = 20
  721. moreView.layer.masksToBounds = true
  722. controlButtonView.layer.cornerRadius = 20
  723. controlButtonView.layer.masksToBounds = true
  724. gradient.frame = bounds
  725. gradient.startPoint = CGPoint(x: 0, y: 0.50)
  726. gradient.endPoint = CGPoint(x: 0, y: 0.9)
  727. gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
  728. layer.insertSublayer(gradient, at: 0)
  729. moreButton.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: .white), for: .normal)
  730. title.text = ""
  731. }
  732. func toggleEmptyView(isEmpty: Bool) {
  733. if isEmpty {
  734. UIView.animate(withDuration: 0.3) {
  735. self.moreView.effect = UIBlurEffect(style: .dark)
  736. self.gradient.isHidden = true
  737. self.controlButtonView.isHidden = true
  738. }
  739. } else {
  740. UIView.animate(withDuration: 0.3) {
  741. self.moreView.effect = UIBlurEffect(style: .regular)
  742. self.gradient.isHidden = false
  743. self.controlButtonView.isHidden = false
  744. }
  745. }
  746. }
  747. @IBAction func moreButtonPressed(_ sender: UIButton) {
  748. mediaView?.openMenuButtonMore(sender)
  749. }
  750. @IBAction func zoomInPressed(_ sender: UIButton) {
  751. mediaView?.zoomInGrid()
  752. }
  753. @IBAction func zoomOutPressed(_ sender: UIButton) {
  754. mediaView?.zoomOutGrid()
  755. }
  756. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  757. self.collapseControlButtonView(false)
  758. }
  759. func collapseControlButtonView(_ collapse: Bool) {
  760. if (collapse) {
  761. self.buttonControlWidthConstraint.constant = 40
  762. UIView.animate(withDuration: 0.25) {
  763. self.zoomOutButton.isHidden = true
  764. self.zoomInButton.isHidden = true
  765. self.separatorView.isHidden = true
  766. self.gridSwitchButton.isHidden = false
  767. self.layoutIfNeeded()
  768. }
  769. } else {
  770. self.buttonControlWidthConstraint.constant = 80
  771. UIView.animate(withDuration: 0.25) {
  772. self.zoomOutButton.isHidden = false
  773. self.zoomInButton.isHidden = false
  774. self.separatorView.isHidden = false
  775. self.gridSwitchButton.isHidden = true
  776. self.layoutIfNeeded()
  777. }
  778. }
  779. }
  780. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  781. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  782. }
  783. override func layoutSublayers(of layer: CALayer) {
  784. super.layoutSublayers(of: layer)
  785. gradient.frame = bounds
  786. }
  787. }
  788. // MARK: - Media Grid Layout
  789. class NCGridMediaLayout: UICollectionViewFlowLayout {
  790. var marginLeftRight: CGFloat = 6
  791. var itemForLine: CGFloat = 3
  792. override init() {
  793. super.init()
  794. sectionHeadersPinToVisibleBounds = false
  795. minimumInteritemSpacing = 0
  796. minimumLineSpacing = marginLeftRight
  797. self.scrollDirection = .vertical
  798. self.sectionInset = UIEdgeInsets(top: 0, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  799. }
  800. required init?(coder aDecoder: NSCoder) {
  801. fatalError("init(coder:) has not been implemented")
  802. }
  803. override var itemSize: CGSize {
  804. get {
  805. if let collectionView = collectionView {
  806. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  807. let itemHeight: CGFloat = itemWidth
  808. return CGSize(width: itemWidth, height: itemHeight)
  809. }
  810. // Default fallback
  811. return CGSize(width: 100, height: 100)
  812. }
  813. set {
  814. super.itemSize = newValue
  815. }
  816. }
  817. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  818. return proposedContentOffset
  819. }
  820. }