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