NCMedia.swift 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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, DropdownMenuDelegate, 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 limit: Int = 100
  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(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.itemPerLine = 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.itemPerLine == 1)
  84. mediaCommandView?.zoomOutButton.isEnabled = !(self.gridLayout.itemPerLine == 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. reloadDataSourceWithCompletion {
  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.itemPerLine + 1 < self.kMaxImageGrid) {
  133. self.gridLayout.itemPerLine += 1
  134. self.mediaCommandView?.zoomInButton.isEnabled = true
  135. }
  136. if(self.gridLayout.itemPerLine == self.kMaxImageGrid - 1) {
  137. self.mediaCommandView?.zoomOutButton.isEnabled = false
  138. }
  139. self.collectionView.collectionViewLayout.invalidateLayout()
  140. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  141. })
  142. }
  143. @objc func zoomInGrid() {
  144. UIView.animate(withDuration: 0.0, animations: {
  145. if(self.gridLayout.itemPerLine - 1 > 0) {
  146. self.gridLayout.itemPerLine -= 1
  147. self.mediaCommandView?.zoomOutButton.isEnabled = true
  148. }
  149. if(self.gridLayout.itemPerLine == 1) {
  150. self.mediaCommandView?.zoomInButton.isEnabled = false
  151. }
  152. self.collectionView.collectionViewLayout.invalidateLayout()
  153. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  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.layoutViewSelect = 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.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) {
  270. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.activeAccount, url: self.appDelegate.activeUrl) { (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, buttonType: String, overwrite: Bool) {
  287. if serverUrl != nil {
  288. let path = CCUtility.returnPathfromServerUrl(serverUrl, activeUrl: appDelegate.activeUrl) ?? ""
  289. NCManageDatabase.sharedInstance.setAccountMediaPath(path, account: appDelegate.activeAccount)
  290. reloadDataSourceWithCompletion {
  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.activeAccount {
  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. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  319. let userInfo: [String : Any] = ["metadata": metadata, "type": "delete"]
  320. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  321. }
  322. }
  323. }
  324. }
  325. }
  326. @objc func moveFile(_ notification: NSNotification) {
  327. if self.view?.window == nil { return }
  328. if let userInfo = notification.userInfo as NSDictionary? {
  329. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  330. if metadata.account == appDelegate.activeAccount {
  331. self.reloadDataSourceWithCompletion() {
  332. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  333. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "move"]
  334. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  335. }
  336. }
  337. }
  338. }
  339. }
  340. }
  341. @objc func renameFile(_ notification: NSNotification) {
  342. if self.view?.window == nil { return }
  343. if let userInfo = notification.userInfo as NSDictionary? {
  344. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  345. if metadata.account == appDelegate.activeAccount {
  346. self.reloadDataSourceWithCompletion() {
  347. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  348. let userInfo: [String : Any] = ["metadata": metadata, "type": "rename"]
  349. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  350. }
  351. }
  352. }
  353. }
  354. }
  355. }
  356. // MARK: DZNEmpty
  357. func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
  358. return 0
  359. }
  360. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  361. return NCBrandColor.sharedInstance.backgroundView
  362. }
  363. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  364. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  365. }
  366. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  367. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  368. if oldInProgress || newInProgress {
  369. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  370. }
  371. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  372. return NSAttributedString.init(string: text, attributes: attributes)
  373. }
  374. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  375. return true
  376. }
  377. // MARK: SEGUE
  378. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  379. if let segueNavigationController = segue.destination as? UINavigationController {
  380. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  381. segueViewController.metadata = metadataPush
  382. segueViewController.metadatas = metadatas
  383. segueViewController.mediaFilterImage = true
  384. }
  385. }
  386. }
  387. }
  388. // MARK: - 3D Touch peek and pop
  389. extension NCMedia: UIViewControllerPreviewingDelegate {
  390. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  391. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  392. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  393. let metadata = metadatas[indexPath.row]
  394. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  395. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  396. previewingContext.sourceRect = cell.frame
  397. viewController.metadata = metadata
  398. viewController.imageFile = cell.imageItem.image
  399. viewController.showOpenIn = true
  400. viewController.showShare = false
  401. viewController.showOpenQuickLook = false
  402. return viewController
  403. }
  404. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  405. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  406. collectionView(collectionView, didSelectItemAt: indexPath)
  407. }
  408. }
  409. // MARK: - Collection View
  410. extension NCMedia: UICollectionViewDelegate {
  411. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  412. let metadata = metadatas[indexPath.row]
  413. metadataPush = metadata
  414. if isEditMode {
  415. if let index = selectocId.firstIndex(of: metadata.ocId) {
  416. selectocId.remove(at: index)
  417. } else {
  418. selectocId.append(metadata.ocId)
  419. }
  420. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  421. collectionView.reloadItems(at: [indexPath])
  422. }
  423. return
  424. }
  425. performSegue(withIdentifier: "segueDetail", sender: self)
  426. }
  427. }
  428. extension NCMedia: UICollectionViewDataSourcePrefetching {
  429. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  430. print("[LOG] n. " + String(indexPaths.count))
  431. }
  432. }
  433. extension NCMedia: UICollectionViewDataSource {
  434. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  435. CATransaction.begin()
  436. CATransaction.setCompletionBlock(closure)
  437. collectionView?.reloadData()
  438. CATransaction.commit()
  439. }
  440. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  441. return metadatas.count
  442. }
  443. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  444. if indexPath.row < self.metadatas.count {
  445. let metadata = self.metadatas[indexPath.row]
  446. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  447. NCOperationQueue.shared.readFileForMedia(metadata: metadata)
  448. }
  449. }
  450. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  451. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
  452. let metadata = metadatas[indexPath.row]
  453. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  454. NCOperationQueue.shared.cancelReadFileForMedia(metadata: metadata)
  455. }
  456. }
  457. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  458. let metadata = metadatas[indexPath.row]
  459. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  460. self.cellHeigth = cell.frame.size.height
  461. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  462. cell.imageItem.backgroundColor = nil
  463. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  464. } else if(!metadata.hasPreview) {
  465. cell.imageItem.backgroundColor = nil
  466. if metadata.iconName.count > 0 {
  467. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  468. } else {
  469. cell.imageItem.image = UIImage.init(named: "file")
  470. }
  471. }
  472. cell.date = metadata.date as Date
  473. // image status
  474. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  475. cell.imageStatus.image = cacheImages.cellPlayImage
  476. } else if metadata.livePhoto && livePhoto {
  477. cell.imageStatus.image = cacheImages.cellLivePhotoImage
  478. }
  479. // image Local
  480. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  481. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  482. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  483. else { cell.imageLocal.image = UIImage.init(named: "local") }
  484. }
  485. // image Favorite
  486. if metadata.favorite {
  487. cell.imageFavorite.image = cacheImages.cellFavouriteImage
  488. }
  489. if isEditMode {
  490. cell.imageSelect.isHidden = false
  491. if selectocId.contains(metadata.ocId) {
  492. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  493. cell.imageVisualEffect.isHidden = false
  494. cell.imageVisualEffect.alpha = 0.4
  495. } else {
  496. cell.imageSelect.isHidden = true
  497. cell.imageVisualEffect.isHidden = true
  498. }
  499. } else {
  500. cell.imageSelect.isHidden = true
  501. cell.imageVisualEffect.isHidden = true
  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 { }
  518. }
  519. private func reloadDataSourceWithCompletion(_ completion: @escaping () -> Void) {
  520. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) { return }
  521. if account != appDelegate.activeAccount {
  522. self.metadatas = []
  523. account = appDelegate.activeAccount
  524. collectionView?.reloadData()
  525. }
  526. livePhoto = CCUtility.getLivePhoto()
  527. if let tableAccount = NCManageDatabase.sharedInstance.getAccountActive() {
  528. self.mediaPath = tableAccount.mediaPath
  529. }
  530. let startServerUrl = CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) + mediaPath
  531. predicateDefault = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND (typeFile == %@ OR typeFile == %@) AND NOT (session CONTAINS[c] 'upload')", appDelegate.activeAccount, 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.activeAccount, 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.activeAccount, startServerUrl, k_metadataTypeFile_image)
  536. } else {
  537. predicate = predicateDefault
  538. }
  539. if livePhoto {
  540. let predicateLivePhoto = NSPredicate(format: "!(ext == 'mov' AND livePhoto == true)")
  541. predicate = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate!, predicateLivePhoto])
  542. }
  543. NCManageDatabase.sharedInstance.getMetadatasMedia(predicate: predicate!, sort: CCUtility.getMediaSortDate()) { (metadatas) in
  544. DispatchQueue.main.sync {
  545. self.metadatas = metadatas
  546. self.reloadDataThenPerform {
  547. self.updateMediaControlVisibility()
  548. self.mediaCommandTitle()
  549. completion()
  550. }
  551. }
  552. }
  553. }
  554. func updateMediaControlVisibility() {
  555. if self.metadatas.count == 0 {
  556. if !self.filterTypeFileImage && !self.filterTypeFileVideo {
  557. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  558. self.mediaCommandView?.isHidden = false
  559. } else {
  560. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  561. self.mediaCommandView?.isHidden = false
  562. }
  563. } else {
  564. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  565. self.mediaCommandView?.isHidden = false
  566. }
  567. }
  568. private func searchOldPhotoVideo(value: Int = -30) {
  569. if oldInProgress { return }
  570. else { oldInProgress = true }
  571. collectionView.reloadData()
  572. var lessDate = Date()
  573. if predicateDefault != nil {
  574. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: predicateDefault!, sorted: "date", ascending: true) {
  575. lessDate = metadata.date as Date
  576. }
  577. }
  578. var greaterDate: Date
  579. if value == -999 {
  580. greaterDate = Date.distantPast
  581. } else {
  582. greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
  583. }
  584. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  585. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: height + 50)
  586. NCCommunication.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), user: appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  587. self.oldInProgress = false
  588. NCUtility.sharedInstance.stopActivityIndicator()
  589. self.collectionView.reloadData()
  590. if errorCode == 0 && account == self.appDelegate.activeAccount {
  591. if files.count > 0 {
  592. let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  593. let predicate = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateDate, self.predicateDefault!])
  594. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicate)
  595. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: self.appDelegate.activeAccount) { (_, _, metadatas) in
  596. let metadatasChanged = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult)
  597. if metadatasChanged.count < self.limit {
  598. if value == -30 {
  599. self.searchOldPhotoVideo(value: -90)
  600. } else if value == -90 {
  601. self.searchOldPhotoVideo(value: -180)
  602. } else if value == -180 {
  603. self.searchOldPhotoVideo(value: -999)
  604. } else {
  605. self.reloadDataSource()
  606. }
  607. } else {
  608. self.reloadDataSource()
  609. }
  610. }
  611. } else {
  612. if value == -30 {
  613. self.searchOldPhotoVideo(value: -90)
  614. } else if value == -90 {
  615. self.searchOldPhotoVideo(value: -180)
  616. } else if value == -180 {
  617. self.searchOldPhotoVideo(value: -999)
  618. }
  619. }
  620. }
  621. }
  622. }
  623. @objc func searchNewPhotoVideo() {
  624. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  625. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  626. newInProgress = true
  627. reloadDataThenPerform {
  628. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  629. if let cell = visibleCells.first as? NCGridMediaCell {
  630. if cell.date != nil {
  631. if cell.date != self.metadatas.first?.date as Date? {
  632. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  633. }
  634. }
  635. }
  636. if let cell = visibleCells.last as? NCGridMediaCell {
  637. if cell.date != nil {
  638. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  639. }
  640. }
  641. }
  642. NCCommunication.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: 0, showHiddenFiles: CCUtility.getShowHiddenFiles(), user: self.appDelegate.activeUser) { (account, files, errorCode, errorDescription) in
  643. self.newInProgress = false
  644. if errorCode == 0 && account == self.appDelegate.activeAccount && files.count > 0 {
  645. DispatchQueue.global().async {
  646. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  647. let newPredicate = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate, self.predicate!])
  648. let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: newPredicate)
  649. if metadatas.count > 0 {
  650. let etagsMetadatas = Array(metadatas.map { $0.etag })
  651. let etagsFiles = Array(files.map { $0.etag })
  652. for etag in etagsFiles {
  653. if !etagsMetadatas.contains(etag) {
  654. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  655. self.reloadDataSource()
  656. break;
  657. }
  658. }
  659. } else {
  660. NCManageDatabase.sharedInstance.addMetadatas(files: files, account: self.appDelegate.activeAccount)
  661. self.reloadDataSource()
  662. }
  663. }
  664. } else if errorCode == 0 && files.count == 0 && self.metadatas.count == 0 {
  665. self.searchOldPhotoVideo()
  666. }
  667. }
  668. }
  669. }
  670. private func downloadThumbnail() {
  671. guard let collectionView = self.collectionView else { return }
  672. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  673. for indexPath in collectionView.indexPathsForVisibleItems {
  674. let metadata = self.metadatas[indexPath.row]
  675. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, activeUrl: self.appDelegate.activeUrl, view: self.collectionView as Any, indexPath: indexPath)
  676. }
  677. }
  678. }
  679. }
  680. // MARK: - ScrollView
  681. extension NCMedia: UIScrollViewDelegate {
  682. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  683. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
  684. mediaCommandTitle()
  685. lastContentOffsetY = scrollView.contentOffset.y
  686. }
  687. }
  688. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  689. mediaCommandView?.collapseControlButtonView(true)
  690. }
  691. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  692. if !decelerate {
  693. self.searchNewPhotoVideo()
  694. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  695. searchOldPhotoVideo()
  696. }
  697. }
  698. }
  699. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  700. self.searchNewPhotoVideo()
  701. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  702. searchOldPhotoVideo()
  703. }
  704. }
  705. }
  706. // MARK: - Media Command View
  707. class NCMediaCommandView: UIView {
  708. @IBOutlet weak var moreView: UIVisualEffectView!
  709. @IBOutlet weak var gridSwitchButton: UIButton!
  710. @IBOutlet weak var separatorView: UIView!
  711. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  712. @IBOutlet weak var zoomInButton: UIButton!
  713. @IBOutlet weak var zoomOutButton: UIButton!
  714. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  715. @IBOutlet weak var title : UILabel!
  716. var mediaView:NCMedia?
  717. private let gradient: CAGradientLayer = CAGradientLayer()
  718. override func awakeFromNib() {
  719. moreView.layer.cornerRadius = 20
  720. moreView.layer.masksToBounds = true
  721. controlButtonView.layer.cornerRadius = 20
  722. controlButtonView.layer.masksToBounds = true
  723. gradient.frame = bounds
  724. gradient.startPoint = CGPoint(x: 0, y: 0.50)
  725. gradient.endPoint = CGPoint(x: 0, y: 0.9)
  726. gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
  727. layer.insertSublayer(gradient, at: 0)
  728. title.text = ""
  729. }
  730. func toggleEmptyView(isEmpty: Bool) {
  731. if isEmpty {
  732. UIView.animate(withDuration: 0.3) {
  733. self.moreView.effect = UIBlurEffect(style: .dark)
  734. self.gradient.isHidden = true
  735. self.controlButtonView.isHidden = true
  736. }
  737. } else {
  738. UIView.animate(withDuration: 0.3) {
  739. self.moreView.effect = UIBlurEffect(style: .regular)
  740. self.gradient.isHidden = false
  741. self.controlButtonView.isHidden = false
  742. }
  743. }
  744. }
  745. @IBAction func moreButtonPressed(_ sender: UIButton) {
  746. mediaView?.openMenuButtonMore(sender)
  747. }
  748. @IBAction func zoomInPressed(_ sender: UIButton) {
  749. mediaView?.zoomInGrid()
  750. }
  751. @IBAction func zoomOutPressed(_ sender: UIButton) {
  752. mediaView?.zoomOutGrid()
  753. }
  754. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  755. self.collapseControlButtonView(false)
  756. }
  757. func collapseControlButtonView(_ collapse: Bool) {
  758. if (collapse) {
  759. self.buttonControlWidthConstraint.constant = 40
  760. UIView.animate(withDuration: 0.25) {
  761. self.zoomOutButton.isHidden = true
  762. self.zoomInButton.isHidden = true
  763. self.separatorView.isHidden = true
  764. self.gridSwitchButton.isHidden = false
  765. self.layoutIfNeeded()
  766. }
  767. } else {
  768. self.buttonControlWidthConstraint.constant = 80
  769. UIView.animate(withDuration: 0.25) {
  770. self.zoomOutButton.isHidden = false
  771. self.zoomInButton.isHidden = false
  772. self.separatorView.isHidden = false
  773. self.gridSwitchButton.isHidden = true
  774. self.layoutIfNeeded()
  775. }
  776. }
  777. }
  778. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  779. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  780. }
  781. override func layoutSublayers(of layer: CALayer) {
  782. super.layoutSublayers(of: layer)
  783. gradient.frame = bounds
  784. }
  785. }