NCMedia.swift 42 KB

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