NCMedia.swift 43 KB

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