NCMedia.swift 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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. private var listOcIdReadFileForMedia: [String] = []
  48. struct cacheImages {
  49. static var cellLivePhotoImage = UIImage()
  50. static var cellPlayImage = UIImage()
  51. static var cellFavouriteImage = UIImage()
  52. }
  53. // MARK: - View Life Cycle
  54. required init?(coder aDecoder: NSCoder) {
  55. super.init(coder: aDecoder)
  56. appDelegate.activeMedia = self
  57. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: k_notificationCenter_reloadMediaDataSource), object: nil)
  58. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: NSNotification.Name(rawValue: k_notificationCenter_applicationWillEnterForeground), object: nil)
  59. }
  60. override func viewDidLoad() {
  61. super.viewDidLoad()
  62. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  63. collectionView.alwaysBounceVertical = true
  64. collectionView.contentInset = UIEdgeInsets(top: 75, left: 0, bottom: 50, right: 0);
  65. gridLayout = NCGridMediaLayout()
  66. gridLayout.itemPerLine = CGFloat(min(CCUtility.getMediaWidthImage(), 5))
  67. gridLayout.sectionHeadersPinToVisibleBounds = true
  68. collectionView.collectionViewLayout = gridLayout
  69. // empty Data Source
  70. collectionView.emptyDataSetDelegate = self
  71. collectionView.emptyDataSetSource = self
  72. // 3D Touch peek and pop
  73. if traitCollection.forceTouchCapability == .available {
  74. registerForPreviewing(with: self, sourceView: view)
  75. }
  76. // Notification
  77. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), 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.itemPerLine == 1)
  85. mediaCommandView?.zoomOutButton.isEnabled = !(self.gridLayout.itemPerLine == 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. reloadDataSourceWithCompletion {
  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.itemPerLine + 1 < self.kMaxImageGrid) {
  134. self.gridLayout.itemPerLine += 1
  135. self.mediaCommandView?.zoomInButton.isEnabled = true
  136. }
  137. if(self.gridLayout.itemPerLine == self.kMaxImageGrid - 1) {
  138. self.mediaCommandView?.zoomOutButton.isEnabled = false
  139. }
  140. self.collectionView.collectionViewLayout.invalidateLayout()
  141. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  142. })
  143. }
  144. @objc func zoomInGrid() {
  145. UIView.animate(withDuration: 0.0, animations: {
  146. if(self.gridLayout.itemPerLine - 1 > 0) {
  147. self.gridLayout.itemPerLine -= 1
  148. self.mediaCommandView?.zoomOutButton.isEnabled = true
  149. }
  150. if(self.gridLayout.itemPerLine == 1) {
  151. self.mediaCommandView?.zoomInButton.isEnabled = false
  152. }
  153. self.collectionView.collectionViewLayout.invalidateLayout()
  154. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemPerLine))
  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.layoutViewSelect = 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.getMetadata(predicate: NSPredicate(format: "ocId == %@", ocId)) {
  271. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase) { (errorCode, errorDescription) in }
  272. }
  273. }
  274. }
  275. )
  276. )
  277. }
  278. mainMenuViewController.actions = actions
  279. let menuPanelController = NCMenuPanelController()
  280. menuPanelController.parentPresenter = self
  281. menuPanelController.delegate = mainMenuViewController
  282. menuPanelController.set(contentViewController: mainMenuViewController)
  283. menuPanelController.track(scrollView: mainMenuViewController.tableView)
  284. self.present(menuPanelController, animated: true, completion: nil)
  285. }
  286. // MARK: Select Path
  287. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, buttonType: String, overwrite: Bool) {
  288. if serverUrl != nil {
  289. let path = CCUtility.returnPathfromServerUrl(serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account) ?? ""
  290. NCManageDatabase.sharedInstance.setAccountMediaPath(path, account: appDelegate.account)
  291. reloadDataSourceWithCompletion {
  292. self.searchNewPhotoVideo()
  293. }
  294. }
  295. }
  296. //MARK: - NotificationCenter
  297. @objc func changeTheming() {
  298. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  299. cacheImages.cellLivePhotoImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "livePhoto"), width: 100, height: 100, color: .white)
  300. cacheImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  301. cacheImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  302. self.navigationController?.setNavigationBarHidden(true, animated: false)
  303. }
  304. @objc func deleteFile(_ notification: NSNotification) {
  305. if self.view?.window == nil { return }
  306. if let userInfo = notification.userInfo as NSDictionary? {
  307. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  308. if metadata.account == appDelegate.account {
  309. let indexes = self.metadatas.indices.filter { self.metadatas[$0].ocId == metadata.ocId }
  310. let metadatas = self.metadatas.filter { $0.ocId != metadata.ocId }
  311. self.metadatas = metadatas
  312. if self.metadatas.count == 0 {
  313. collectionView?.reloadData()
  314. } else if let row = indexes.first {
  315. let indexPath = IndexPath(row: row, section: 0)
  316. collectionView?.deleteItems(at: [indexPath])
  317. }
  318. self.updateMediaControlVisibility()
  319. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  320. let userInfo: [String : Any] = ["metadata": metadata, "type": "delete"]
  321. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  322. }
  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, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  331. if metadata.account == appDelegate.account {
  332. self.reloadDataSourceWithCompletion() {
  333. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  334. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "move"]
  335. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  336. }
  337. }
  338. }
  339. }
  340. }
  341. }
  342. @objc func renameFile(_ notification: NSNotification) {
  343. if self.view?.window == nil { return }
  344. if let userInfo = notification.userInfo as NSDictionary? {
  345. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  346. if metadata.account == appDelegate.account {
  347. self.reloadDataSourceWithCompletion() {
  348. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  349. let userInfo: [String : Any] = ["metadata": metadata, "type": "rename"]
  350. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_synchronizationMedia, userInfo: userInfo)
  351. }
  352. }
  353. }
  354. }
  355. }
  356. }
  357. // MARK: DZNEmpty
  358. func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
  359. return 0
  360. }
  361. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  362. return NCBrandColor.sharedInstance.backgroundView
  363. }
  364. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  365. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  366. }
  367. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  368. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  369. if oldInProgress || newInProgress {
  370. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  371. }
  372. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  373. return NSAttributedString.init(string: text, attributes: attributes)
  374. }
  375. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  376. return true
  377. }
  378. // MARK: SEGUE
  379. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  380. if let segueNavigationController = segue.destination as? UINavigationController {
  381. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  382. segueViewController.metadata = metadataPush
  383. segueViewController.metadatas = metadatas
  384. segueViewController.mediaFilterImage = true
  385. }
  386. }
  387. }
  388. }
  389. // MARK: - 3D Touch peek and pop
  390. extension NCMedia: UIViewControllerPreviewingDelegate {
  391. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  392. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  393. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  394. let metadata = metadatas[indexPath.row]
  395. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  396. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  397. previewingContext.sourceRect = cell.frame
  398. viewController.metadata = metadata
  399. viewController.imageFile = cell.imageItem.image
  400. viewController.showOpenIn = true
  401. viewController.showShare = false
  402. viewController.showOpenQuickLook = false
  403. return viewController
  404. }
  405. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  406. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  407. collectionView(collectionView, didSelectItemAt: indexPath)
  408. }
  409. }
  410. // MARK: - Collection View
  411. extension NCMedia: UICollectionViewDelegate {
  412. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  413. let metadata = metadatas[indexPath.row]
  414. metadataPush = metadata
  415. if isEditMode {
  416. if let index = selectocId.firstIndex(of: metadata.ocId) {
  417. selectocId.remove(at: index)
  418. } else {
  419. selectocId.append(metadata.ocId)
  420. }
  421. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  422. collectionView.reloadItems(at: [indexPath])
  423. }
  424. return
  425. }
  426. performSegue(withIdentifier: "segueDetail", sender: self)
  427. }
  428. }
  429. extension NCMedia: UICollectionViewDataSourcePrefetching {
  430. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  431. print("[LOG] n. " + String(indexPaths.count))
  432. }
  433. }
  434. extension NCMedia: UICollectionViewDataSource {
  435. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  436. CATransaction.begin()
  437. CATransaction.setCompletionBlock(closure)
  438. collectionView?.reloadData()
  439. CATransaction.commit()
  440. }
  441. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  442. return metadatas.count
  443. }
  444. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  445. if indexPath.row < self.metadatas.count {
  446. let metadata = self.metadatas[indexPath.row]
  447. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  448. if !listOcIdReadFileForMedia.contains(metadata.ocId) {
  449. NCOperationQueue.shared.readFileForMedia(metadata: metadata)
  450. listOcIdReadFileForMedia.append(metadata.ocId)
  451. }
  452. }
  453. }
  454. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  455. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
  456. let metadata = metadatas[indexPath.row]
  457. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  458. NCOperationQueue.shared.cancelReadFileForMedia(metadata: metadata)
  459. }
  460. }
  461. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  462. let metadata = metadatas[indexPath.row]
  463. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  464. self.cellHeigth = cell.frame.size.height
  465. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  466. cell.imageItem.backgroundColor = nil
  467. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  468. } else if(!metadata.hasPreview) {
  469. cell.imageItem.backgroundColor = nil
  470. if metadata.iconName.count > 0 {
  471. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  472. } else {
  473. cell.imageItem.image = UIImage.init(named: "file")
  474. }
  475. }
  476. cell.date = metadata.date as Date
  477. // image status
  478. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  479. cell.imageStatus.image = cacheImages.cellPlayImage
  480. } else if metadata.livePhoto && livePhoto {
  481. cell.imageStatus.image = cacheImages.cellLivePhotoImage
  482. }
  483. // image Local
  484. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  485. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  486. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  487. else { cell.imageLocal.image = UIImage.init(named: "local") }
  488. }
  489. // image Favorite
  490. if metadata.favorite {
  491. cell.imageFavorite.image = cacheImages.cellFavouriteImage
  492. }
  493. if isEditMode {
  494. cell.imageSelect.isHidden = false
  495. if selectocId.contains(metadata.ocId) {
  496. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  497. cell.imageVisualEffect.isHidden = false
  498. cell.imageVisualEffect.alpha = 0.4
  499. } else {
  500. cell.imageSelect.isHidden = true
  501. cell.imageVisualEffect.isHidden = true
  502. }
  503. } else {
  504. cell.imageSelect.isHidden = true
  505. cell.imageVisualEffect.isHidden = true
  506. }
  507. return cell
  508. }
  509. }
  510. extension NCMedia: UICollectionViewDelegateFlowLayout {
  511. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  512. return CGSize(width: collectionView.frame.width, height: 0)
  513. }
  514. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  515. return CGSize(width: collectionView.frame.width, height: 0)
  516. }
  517. }
  518. // MARK: - NC API & Algorithm
  519. extension NCMedia {
  520. @objc func reloadDataSource() {
  521. self.reloadDataSourceWithCompletion { }
  522. }
  523. @objc func reloadDataSourceWithCompletion(_ completion: @escaping () -> Void) {
  524. if (appDelegate.account == nil || appDelegate.account.count == 0 || appDelegate.maintenanceMode == true) { return }
  525. if account != appDelegate.account {
  526. self.metadatas = []
  527. account = appDelegate.account
  528. collectionView?.reloadData()
  529. }
  530. livePhoto = CCUtility.getLivePhoto()
  531. if let tableAccount = NCManageDatabase.sharedInstance.getAccountActive() {
  532. self.mediaPath = tableAccount.mediaPath
  533. }
  534. let startServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) + mediaPath
  535. 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)
  536. if filterTypeFileImage {
  537. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, k_metadataTypeFile_video)
  538. } else if filterTypeFileVideo {
  539. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, k_metadataTypeFile_image)
  540. } else {
  541. predicate = predicateDefault
  542. }
  543. guard var predicateForGetMetadatasMedia = predicate else { return }
  544. if livePhoto {
  545. let predicateLivePhoto = NSPredicate(format: "!(ext == 'mov' AND livePhoto == true)")
  546. predicateForGetMetadatasMedia = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateForGetMetadatasMedia, predicateLivePhoto])
  547. }
  548. DispatchQueue.global().async {
  549. self.metadatas = NCManageDatabase.sharedInstance.getMetadatasMedia(predicate: predicateForGetMetadatasMedia, sort: CCUtility.getMediaSortDate())
  550. DispatchQueue.main.sync {
  551. self.reloadDataThenPerform {
  552. self.updateMediaControlVisibility()
  553. self.mediaCommandTitle()
  554. completion()
  555. }
  556. }
  557. }
  558. }
  559. func updateMediaControlVisibility() {
  560. if self.metadatas.count == 0 {
  561. if !self.filterTypeFileImage && !self.filterTypeFileVideo {
  562. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  563. self.mediaCommandView?.isHidden = false
  564. } else {
  565. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  566. self.mediaCommandView?.isHidden = false
  567. }
  568. } else {
  569. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  570. self.mediaCommandView?.isHidden = false
  571. }
  572. }
  573. private func searchOldPhotoVideo(value: Int = -30) {
  574. if oldInProgress { return }
  575. else { oldInProgress = true }
  576. collectionView.reloadData()
  577. var lessDate = Date()
  578. if predicateDefault != nil {
  579. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: predicateDefault!, sorted: "date", ascending: true) {
  580. lessDate = metadata.date as Date
  581. }
  582. }
  583. var greaterDate: Date
  584. if value == -999 {
  585. greaterDate = Date.distantPast
  586. } else {
  587. greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
  588. }
  589. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  590. NCUtility.shared.startActivityIndicator(view: self.view, bottom: height + 50)
  591. NCCommunication.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: 0, showHiddenFiles: CCUtility.getShowHiddenFiles(), user: appDelegate.user) { (account, files, errorCode, errorDescription) in
  592. self.oldInProgress = false
  593. NCUtility.shared.stopActivityIndicator()
  594. self.collectionView.reloadData()
  595. if errorCode == 0 && account == self.appDelegate.account {
  596. if files.count > 0 {
  597. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: self.appDelegate.account) { (_, _, metadatas) in
  598. let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  599. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateDate, self.predicateDefault!])
  600. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicateResult)
  601. let metadatasChanged = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult)
  602. if metadatasChanged.count < self.limit {
  603. if value == -30 {
  604. self.searchOldPhotoVideo(value: -90)
  605. } else if value == -90 {
  606. self.searchOldPhotoVideo(value: -180)
  607. } else if value == -180 {
  608. self.searchOldPhotoVideo(value: -999)
  609. } else {
  610. self.reloadDataSource()
  611. }
  612. } else {
  613. self.reloadDataSource()
  614. }
  615. }
  616. } else {
  617. if value == -30 {
  618. self.searchOldPhotoVideo(value: -90)
  619. } else if value == -90 {
  620. self.searchOldPhotoVideo(value: -180)
  621. } else if value == -180 {
  622. self.searchOldPhotoVideo(value: -999)
  623. }
  624. }
  625. }
  626. }
  627. }
  628. @objc func searchNewPhotoVideo() {
  629. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  630. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  631. newInProgress = true
  632. reloadDataThenPerform {
  633. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  634. if let cell = visibleCells.first as? NCGridMediaCell {
  635. if cell.date != nil {
  636. if cell.date != self.metadatas.first?.date as Date? {
  637. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  638. }
  639. }
  640. }
  641. if let cell = visibleCells.last as? NCGridMediaCell {
  642. if cell.date != nil {
  643. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  644. }
  645. }
  646. }
  647. NCCommunication.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: 0, showHiddenFiles: CCUtility.getShowHiddenFiles(), user: self.appDelegate.user) { (account, files, errorCode, errorDescription) in
  648. self.newInProgress = false
  649. if errorCode == 0 && account == self.appDelegate.account && files.count > 0 {
  650. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
  651. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  652. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate, self.predicate!])
  653. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicateResult)
  654. let updateMetadatas = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult)
  655. if updateMetadatas.count > 0 {
  656. self.reloadDataSource()
  657. }
  658. }
  659. } else if errorCode == 0 && files.count == 0 && self.metadatas.count == 0 {
  660. self.searchOldPhotoVideo()
  661. }
  662. }
  663. }
  664. }
  665. private func downloadThumbnail() {
  666. guard let collectionView = self.collectionView else { return }
  667. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  668. for indexPath in collectionView.indexPathsForVisibleItems {
  669. let metadata = self.metadatas[indexPath.row]
  670. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  671. }
  672. }
  673. }
  674. }
  675. // MARK: - ScrollView
  676. extension NCMedia: UIScrollViewDelegate {
  677. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  678. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
  679. mediaCommandTitle()
  680. lastContentOffsetY = scrollView.contentOffset.y
  681. }
  682. }
  683. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  684. mediaCommandView?.collapseControlButtonView(true)
  685. }
  686. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  687. if !decelerate {
  688. self.searchNewPhotoVideo()
  689. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  690. searchOldPhotoVideo()
  691. }
  692. }
  693. }
  694. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  695. self.searchNewPhotoVideo()
  696. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  697. searchOldPhotoVideo()
  698. }
  699. }
  700. }
  701. // MARK: - Media Command View
  702. class NCMediaCommandView: UIView {
  703. @IBOutlet weak var moreView: UIVisualEffectView!
  704. @IBOutlet weak var gridSwitchButton: UIButton!
  705. @IBOutlet weak var separatorView: UIView!
  706. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  707. @IBOutlet weak var zoomInButton: UIButton!
  708. @IBOutlet weak var zoomOutButton: 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. title.text = ""
  724. }
  725. func toggleEmptyView(isEmpty: Bool) {
  726. if isEmpty {
  727. UIView.animate(withDuration: 0.3) {
  728. self.moreView.effect = UIBlurEffect(style: .dark)
  729. self.gradient.isHidden = true
  730. self.controlButtonView.isHidden = true
  731. }
  732. } else {
  733. UIView.animate(withDuration: 0.3) {
  734. self.moreView.effect = UIBlurEffect(style: .regular)
  735. self.gradient.isHidden = false
  736. self.controlButtonView.isHidden = false
  737. }
  738. }
  739. }
  740. @IBAction func moreButtonPressed(_ sender: UIButton) {
  741. mediaView?.openMenuButtonMore(sender)
  742. }
  743. @IBAction func zoomInPressed(_ sender: UIButton) {
  744. mediaView?.zoomInGrid()
  745. }
  746. @IBAction func zoomOutPressed(_ sender: UIButton) {
  747. mediaView?.zoomOutGrid()
  748. }
  749. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  750. self.collapseControlButtonView(false)
  751. }
  752. func collapseControlButtonView(_ collapse: Bool) {
  753. if (collapse) {
  754. self.buttonControlWidthConstraint.constant = 40
  755. UIView.animate(withDuration: 0.25) {
  756. self.zoomOutButton.isHidden = true
  757. self.zoomInButton.isHidden = true
  758. self.separatorView.isHidden = true
  759. self.gridSwitchButton.isHidden = false
  760. self.layoutIfNeeded()
  761. }
  762. } else {
  763. self.buttonControlWidthConstraint.constant = 80
  764. UIView.animate(withDuration: 0.25) {
  765. self.zoomOutButton.isHidden = false
  766. self.zoomInButton.isHidden = false
  767. self.separatorView.isHidden = false
  768. self.gridSwitchButton.isHidden = true
  769. self.layoutIfNeeded()
  770. }
  771. }
  772. }
  773. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  774. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  775. }
  776. override func layoutSublayers(of layer: CALayer) {
  777. super.layoutSublayers(of: layer)
  778. gradient.frame = bounds
  779. }
  780. }