NCMedia.swift 42 KB

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