NCMedia.swift 43 KB

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