NCMedia.swift 43 KB

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