NCMedia.swift 43 KB

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