NCMedia.swift 42 KB

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