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, 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 = 5
  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. private var listOcIdReadFileForMedia: [String] = []
  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(reloadDataSource), name: NSNotification.Name(rawValue: k_notificationCenter_reloadMediaDataSource), object: nil)
  57. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: NSNotification.Name(rawValue: k_notificationCenter_applicationWillEnterForeground), object: nil)
  58. }
  59. override func viewDidLoad() {
  60. super.viewDidLoad()
  61. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  62. collectionView.alwaysBounceVertical = true
  63. collectionView.contentInset = UIEdgeInsets(top: 75, left: 0, bottom: 50, right: 0);
  64. gridLayout = NCGridMediaLayout()
  65. gridLayout.itemForLine = CGFloat(min(CCUtility.getMediaWidthImage(), 5))
  66. gridLayout.sectionHeadersPinToVisibleBounds = true
  67. collectionView.collectionViewLayout = gridLayout
  68. // empty Data Source
  69. collectionView.emptyDataSetDelegate = self
  70. collectionView.emptyDataSetSource = self
  71. // 3D Touch peek and pop
  72. if traitCollection.forceTouchCapability == .available {
  73. registerForPreviewing(with: self, sourceView: view)
  74. }
  75. // Notification
  76. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  77. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_mediaFileNotFound), object: nil)
  78. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  79. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  80. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  81. mediaCommandView = Bundle.main.loadNibNamed("NCMediaCommandView", owner: self, options: nil)?.first as? NCMediaCommandView
  82. self.view.addSubview(mediaCommandView!)
  83. mediaCommandView?.mediaView = self
  84. mediaCommandView?.zoomInButton.isEnabled = !(self.gridLayout.itemForLine == 1)
  85. mediaCommandView?.zoomOutButton.isEnabled = !(self.gridLayout.itemForLine == self.kMaxImageGrid - 1)
  86. mediaCommandView?.collapseControlButtonView(true)
  87. mediaCommandView?.translatesAutoresizingMaskIntoConstraints = false
  88. mediaCommandView?.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  89. mediaCommandView?.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  90. mediaCommandView?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  91. mediaCommandView?.heightAnchor.constraint(equalToConstant: 150).isActive = true
  92. self.updateMediaControlVisibility()
  93. collectionView.prefetchDataSource = self
  94. changeTheming()
  95. }
  96. override func viewWillAppear(_ animated: Bool) {
  97. super.viewWillAppear(animated)
  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. actions.append(
  262. NCMenuAction(
  263. title: NSLocalizedString("_delete_", comment: ""),
  264. icon: CCGraphics.changeThemingColorImage(UIImage(named: "trash"), width: 50, height: 50, color: .red),
  265. action: { menuAction in
  266. self.isEditMode = false
  267. for ocId in self.selectocId {
  268. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  269. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, onlyLocal: false) { (errorCode, errorDescription) in
  270. if errorCode != 0 {
  271. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  272. }
  273. }
  274. }
  275. }
  276. }
  277. )
  278. )
  279. }
  280. mainMenuViewController.actions = actions
  281. let menuPanelController = NCMenuPanelController()
  282. menuPanelController.parentPresenter = self
  283. menuPanelController.delegate = mainMenuViewController
  284. menuPanelController.set(contentViewController: mainMenuViewController)
  285. menuPanelController.track(scrollView: mainMenuViewController.tableView)
  286. self.present(menuPanelController, animated: true, completion: nil)
  287. }
  288. // MARK: Select Path
  289. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, array: [Any], buttonType: String, overwrite: Bool) {
  290. if serverUrl != nil {
  291. let path = CCUtility.returnPathfromServerUrl(serverUrl, urlBase: appDelegate.urlBase, account: appDelegate.account) ?? ""
  292. NCManageDatabase.sharedInstance.setAccountMediaPath(path, account: appDelegate.account)
  293. reloadDataSourceWithCompletion { (_) in
  294. self.searchNewPhotoVideo()
  295. }
  296. }
  297. }
  298. //MARK: - NotificationCenter
  299. @objc func changeTheming() {
  300. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  301. cacheImages.cellLivePhotoImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "livePhoto"), width: 100, height: 100, color: .white)
  302. cacheImages.cellPlayImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "play"), width: 100, height: 100, color: .white)
  303. cacheImages.cellFavouriteImage = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), width: 100, height: 100, color: NCBrandColor.sharedInstance.yellowFavorite)
  304. self.navigationController?.setNavigationBarHidden(true, animated: false)
  305. }
  306. @objc func deleteFile(_ notification: NSNotification) {
  307. if self.view?.window == nil { return }
  308. if let userInfo = notification.userInfo as NSDictionary? {
  309. if let metadata = userInfo["metadata"] as? tableMetadata {
  310. if metadata.account == appDelegate.account {
  311. let indexes = self.metadatas.indices.filter { self.metadatas[$0].ocId == metadata.ocId }
  312. let metadatas = self.metadatas.filter { $0.ocId != metadata.ocId }
  313. self.metadatas = metadatas
  314. if self.metadatas.count == 0 {
  315. collectionView?.reloadData()
  316. } else if let row = indexes.first {
  317. let indexPath = IndexPath(row: row, section: 0)
  318. collectionView?.deleteItems(at: [indexPath])
  319. }
  320. self.updateMediaControlVisibility()
  321. }
  322. }
  323. }
  324. }
  325. @objc func moveFile(_ notification: NSNotification) {
  326. if self.view?.window == nil { return }
  327. if let userInfo = notification.userInfo as NSDictionary? {
  328. if let metadata = userInfo["metadata"] as? tableMetadata {
  329. if metadata.account == appDelegate.account {
  330. self.reloadDataSource()
  331. }
  332. }
  333. }
  334. }
  335. @objc func renameFile(_ notification: NSNotification) {
  336. if self.view?.window == nil { return }
  337. if let userInfo = notification.userInfo as NSDictionary? {
  338. if let metadata = userInfo["metadata"] as? tableMetadata {
  339. if metadata.account == appDelegate.account {
  340. self.reloadDataSource()
  341. }
  342. }
  343. }
  344. }
  345. // MARK: DZNEmpty
  346. func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
  347. return 0
  348. }
  349. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  350. return NCBrandColor.sharedInstance.backgroundView
  351. }
  352. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  353. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: .gray)
  354. }
  355. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  356. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  357. if oldInProgress || newInProgress {
  358. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  359. }
  360. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.gray]
  361. return NSAttributedString.init(string: text, attributes: attributes)
  362. }
  363. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  364. return true
  365. }
  366. // MARK: SEGUE
  367. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  368. if let segueNavigationController = segue.destination as? UINavigationController {
  369. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  370. segueViewController.metadata = metadataTouch
  371. segueViewController.metadatas = metadatas
  372. segueViewController.mediaFilterImage = true
  373. segueViewController.layoutKey = k_layout_view_media
  374. }
  375. }
  376. }
  377. }
  378. // MARK: - 3D Touch peek and pop
  379. extension NCMedia: UIViewControllerPreviewingDelegate {
  380. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  381. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  382. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  383. let metadata = metadatas[indexPath.row]
  384. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  385. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  386. previewingContext.sourceRect = cell.frame
  387. viewController.metadata = metadata
  388. viewController.imageFile = cell.imageItem.image
  389. viewController.showOpenIn = true
  390. viewController.showShare = false
  391. viewController.showOpenQuickLook = false
  392. return viewController
  393. }
  394. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  395. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  396. collectionView(collectionView, didSelectItemAt: indexPath)
  397. }
  398. }
  399. // MARK: - Collection View
  400. extension NCMedia: UICollectionViewDelegate {
  401. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  402. let metadata = metadatas[indexPath.row]
  403. metadataTouch = metadata
  404. if isEditMode {
  405. if let index = selectocId.firstIndex(of: metadata.ocId) {
  406. selectocId.remove(at: index)
  407. } else {
  408. selectocId.append(metadata.ocId)
  409. }
  410. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  411. collectionView.reloadItems(at: [indexPath])
  412. }
  413. return
  414. }
  415. performSegue(withIdentifier: "segueDetail", sender: self)
  416. }
  417. }
  418. extension NCMedia: UICollectionViewDataSourcePrefetching {
  419. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  420. //print("[LOG] n. " + String(indexPaths.count))
  421. }
  422. }
  423. extension NCMedia: UICollectionViewDataSource {
  424. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  425. CATransaction.begin()
  426. CATransaction.setCompletionBlock(closure)
  427. collectionView?.reloadData()
  428. CATransaction.commit()
  429. }
  430. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  431. return metadatas.count
  432. }
  433. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  434. if indexPath.row < self.metadatas.count {
  435. let metadata = self.metadatas[indexPath.row]
  436. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  437. if !listOcIdReadFileForMedia.contains(metadata.ocId) {
  438. NCOperationQueue.shared.readFileForMedia(metadata: metadata)
  439. listOcIdReadFileForMedia.append(metadata.ocId)
  440. }
  441. }
  442. }
  443. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  444. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
  445. let metadata = metadatas[indexPath.row]
  446. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  447. NCOperationQueue.shared.cancelReadFileForMedia(metadata: metadata)
  448. }
  449. }
  450. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  451. let metadata = metadatas[indexPath.row]
  452. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  453. self.cellHeigth = cell.frame.size.height
  454. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  455. cell.imageItem.backgroundColor = nil
  456. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  457. } else if(!metadata.hasPreview) {
  458. cell.imageItem.backgroundColor = nil
  459. if metadata.iconName.count > 0 {
  460. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  461. } else {
  462. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  463. }
  464. }
  465. cell.date = metadata.date as Date
  466. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  467. cell.imageStatus.image = cacheImages.cellPlayImage
  468. } else if metadata.livePhoto && livePhoto {
  469. cell.imageStatus.image = cacheImages.cellLivePhotoImage
  470. }
  471. if isEditMode {
  472. cell.imageSelect.isHidden = false
  473. if selectocId.contains(metadata.ocId) {
  474. cell.imageSelect.image = CCGraphics.scale(UIImage.init(named: "checkedYes"), to: CGSize(width: 50, height: 50), isAspectRation: true)
  475. cell.imageVisualEffect.isHidden = false
  476. cell.imageVisualEffect.alpha = 0.4
  477. } else {
  478. cell.imageSelect.isHidden = true
  479. cell.imageVisualEffect.isHidden = true
  480. }
  481. } else {
  482. cell.imageSelect.isHidden = true
  483. cell.imageVisualEffect.isHidden = true
  484. }
  485. return cell
  486. }
  487. }
  488. extension NCMedia: UICollectionViewDelegateFlowLayout {
  489. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  490. return CGSize(width: collectionView.frame.width, height: 0)
  491. }
  492. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  493. return CGSize(width: collectionView.frame.width, height: 0)
  494. }
  495. }
  496. // MARK: - NC API & Algorithm
  497. extension NCMedia {
  498. @objc func reloadDataSource() {
  499. self.reloadDataSourceWithCompletion { (_) in }
  500. }
  501. @objc func reloadDataSourceWithCompletion(_ completion: @escaping (_ metadatas: [tableMetadata]) -> Void) {
  502. if (appDelegate.account == nil || appDelegate.account.count == 0 || appDelegate.maintenanceMode == true) { return }
  503. if account != appDelegate.account {
  504. self.metadatas = []
  505. account = appDelegate.account
  506. collectionView?.reloadData()
  507. }
  508. livePhoto = CCUtility.getLivePhoto()
  509. if let tableAccount = NCManageDatabase.sharedInstance.getAccountActive() {
  510. self.mediaPath = tableAccount.mediaPath
  511. }
  512. let startServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) + mediaPath
  513. 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)
  514. if filterTypeFileImage {
  515. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, k_metadataTypeFile_video)
  516. } else if filterTypeFileVideo {
  517. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, k_metadataTypeFile_image)
  518. } else {
  519. predicate = predicateDefault
  520. }
  521. guard var predicateForGetMetadatasMedia = predicate else { return }
  522. if livePhoto {
  523. let predicateLivePhoto = NSPredicate(format: "!(ext == 'mov' AND livePhoto == true)")
  524. predicateForGetMetadatasMedia = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateForGetMetadatasMedia, predicateLivePhoto])
  525. }
  526. DispatchQueue.global().async {
  527. self.metadatas = NCManageDatabase.sharedInstance.getMetadatasMedia(predicate: predicateForGetMetadatasMedia, sort: CCUtility.getMediaSortDate())
  528. DispatchQueue.main.sync {
  529. self.reloadDataThenPerform {
  530. self.updateMediaControlVisibility()
  531. self.mediaCommandTitle()
  532. completion(self.metadatas)
  533. }
  534. }
  535. }
  536. }
  537. func updateMediaControlVisibility() {
  538. if self.metadatas.count == 0 {
  539. if !self.filterTypeFileImage && !self.filterTypeFileVideo {
  540. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  541. self.mediaCommandView?.isHidden = false
  542. } else {
  543. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  544. self.mediaCommandView?.isHidden = false
  545. }
  546. } else {
  547. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  548. self.mediaCommandView?.isHidden = false
  549. }
  550. }
  551. private func searchOldPhotoVideo(value: Int = -30, limit: Int = 300) {
  552. if oldInProgress { return }
  553. else { oldInProgress = true }
  554. collectionView.reloadData()
  555. var lessDate = Date()
  556. if predicateDefault != nil {
  557. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: predicateDefault!, sorted: "date", ascending: true) {
  558. lessDate = metadata.date as Date
  559. }
  560. }
  561. var greaterDate: Date
  562. if value == -999 {
  563. greaterDate = Date.distantPast
  564. } else {
  565. greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
  566. }
  567. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  568. NCUtility.shared.startActivityIndicator(view: self.view, bottom: height + 50)
  569. NCCommunication.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), timeout: 120) { (account, files, errorCode, errorDescription) in
  570. self.oldInProgress = false
  571. NCUtility.shared.stopActivityIndicator()
  572. self.collectionView.reloadData()
  573. if errorCode == 0 && account == self.appDelegate.account {
  574. if files.count > 0 {
  575. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: self.appDelegate.account) { (_, _, metadatas) in
  576. let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  577. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateDate, self.predicateDefault!])
  578. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicateResult)
  579. let metadatasChanged = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  580. if metadatasChanged.metadatasUpdate.count == 0 {
  581. self.researchOldPhotoVideo(value: value, limit: limit, withElseReloadDataSource: true)
  582. } else {
  583. self.reloadDataSource()
  584. }
  585. }
  586. } else {
  587. self.researchOldPhotoVideo(value: value, limit: limit, withElseReloadDataSource: false)
  588. }
  589. }
  590. }
  591. }
  592. private func researchOldPhotoVideo(value: Int , limit: Int, withElseReloadDataSource: Bool) {
  593. if value == -30 {
  594. searchOldPhotoVideo(value: -90)
  595. } else if value == -90 {
  596. searchOldPhotoVideo(value: -180)
  597. } else if value == -180 {
  598. searchOldPhotoVideo(value: -999)
  599. } else if value == -999 && limit > 0 {
  600. searchOldPhotoVideo(value: -999, limit: 0)
  601. } else {
  602. if withElseReloadDataSource {
  603. reloadDataSource()
  604. }
  605. }
  606. }
  607. @objc func searchNewPhotoVideo(limit: Int = 300) {
  608. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  609. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  610. newInProgress = true
  611. reloadDataThenPerform {
  612. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  613. if let cell = visibleCells.first as? NCGridMediaCell {
  614. if cell.date != nil {
  615. if cell.date != self.metadatas.first?.date as Date? {
  616. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  617. }
  618. }
  619. }
  620. if let cell = visibleCells.last as? NCGridMediaCell {
  621. if cell.date != nil {
  622. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  623. }
  624. }
  625. }
  626. 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
  627. self.newInProgress = false
  628. if errorCode == 0 && account == self.appDelegate.account && files.count > 0 {
  629. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
  630. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  631. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate, self.predicate!])
  632. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicateResult)
  633. let updateMetadatas = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  634. if updateMetadatas.metadatasUpdate.count > 0 {
  635. self.reloadDataSource()
  636. }
  637. }
  638. } else if errorCode == 0 && files.count == 0 && limit > 0 {
  639. self.searchNewPhotoVideo(limit: 0)
  640. } else if errorCode == 0 && files.count == 0 && self.metadatas.count == 0 {
  641. self.searchOldPhotoVideo()
  642. }
  643. }
  644. }
  645. }
  646. private func downloadThumbnail() {
  647. guard let collectionView = self.collectionView else { return }
  648. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  649. for indexPath in collectionView.indexPathsForVisibleItems {
  650. let metadata = self.metadatas[indexPath.row]
  651. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  652. }
  653. }
  654. }
  655. }
  656. // MARK: - ScrollView
  657. extension NCMedia: UIScrollViewDelegate {
  658. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  659. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
  660. mediaCommandTitle()
  661. lastContentOffsetY = scrollView.contentOffset.y
  662. }
  663. }
  664. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  665. mediaCommandView?.collapseControlButtonView(true)
  666. }
  667. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  668. if !decelerate {
  669. self.searchNewPhotoVideo()
  670. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  671. searchOldPhotoVideo()
  672. }
  673. }
  674. }
  675. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  676. self.searchNewPhotoVideo()
  677. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  678. searchOldPhotoVideo()
  679. }
  680. }
  681. }
  682. // MARK: - Media Command View
  683. class NCMediaCommandView: UIView {
  684. @IBOutlet weak var moreView: UIVisualEffectView!
  685. @IBOutlet weak var gridSwitchButton: UIButton!
  686. @IBOutlet weak var separatorView: UIView!
  687. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  688. @IBOutlet weak var zoomInButton: UIButton!
  689. @IBOutlet weak var zoomOutButton: UIButton!
  690. @IBOutlet weak var moreButton: UIButton!
  691. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  692. @IBOutlet weak var title : UILabel!
  693. var mediaView:NCMedia?
  694. private let gradient: CAGradientLayer = CAGradientLayer()
  695. override func awakeFromNib() {
  696. moreView.layer.cornerRadius = 20
  697. moreView.layer.masksToBounds = true
  698. controlButtonView.layer.cornerRadius = 20
  699. controlButtonView.layer.masksToBounds = true
  700. gradient.frame = bounds
  701. gradient.startPoint = CGPoint(x: 0, y: 0.50)
  702. gradient.endPoint = CGPoint(x: 0, y: 0.9)
  703. gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
  704. layer.insertSublayer(gradient, at: 0)
  705. moreButton.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: .white), for: .normal)
  706. title.text = ""
  707. }
  708. func toggleEmptyView(isEmpty: Bool) {
  709. if isEmpty {
  710. UIView.animate(withDuration: 0.3) {
  711. self.moreView.effect = UIBlurEffect(style: .dark)
  712. self.gradient.isHidden = true
  713. self.controlButtonView.isHidden = true
  714. }
  715. } else {
  716. UIView.animate(withDuration: 0.3) {
  717. self.moreView.effect = UIBlurEffect(style: .regular)
  718. self.gradient.isHidden = false
  719. self.controlButtonView.isHidden = false
  720. }
  721. }
  722. }
  723. @IBAction func moreButtonPressed(_ sender: UIButton) {
  724. mediaView?.openMenuButtonMore(sender)
  725. }
  726. @IBAction func zoomInPressed(_ sender: UIButton) {
  727. mediaView?.zoomInGrid()
  728. }
  729. @IBAction func zoomOutPressed(_ sender: UIButton) {
  730. mediaView?.zoomOutGrid()
  731. }
  732. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  733. self.collapseControlButtonView(false)
  734. }
  735. func collapseControlButtonView(_ collapse: Bool) {
  736. if (collapse) {
  737. self.buttonControlWidthConstraint.constant = 40
  738. UIView.animate(withDuration: 0.25) {
  739. self.zoomOutButton.isHidden = true
  740. self.zoomInButton.isHidden = true
  741. self.separatorView.isHidden = true
  742. self.gridSwitchButton.isHidden = false
  743. self.layoutIfNeeded()
  744. }
  745. } else {
  746. self.buttonControlWidthConstraint.constant = 80
  747. UIView.animate(withDuration: 0.25) {
  748. self.zoomOutButton.isHidden = false
  749. self.zoomInButton.isHidden = false
  750. self.separatorView.isHidden = false
  751. self.gridSwitchButton.isHidden = true
  752. self.layoutIfNeeded()
  753. }
  754. }
  755. }
  756. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  757. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  758. }
  759. override func layoutSublayers(of layer: CALayer) {
  760. super.layoutSublayers(of: layer)
  761. gradient.frame = bounds
  762. }
  763. }
  764. // MARK: - Media Grid Layout
  765. class NCGridMediaLayout: UICollectionViewFlowLayout {
  766. var marginLeftRight: CGFloat = 6
  767. var itemForLine: CGFloat = 3
  768. override init() {
  769. super.init()
  770. sectionHeadersPinToVisibleBounds = false
  771. minimumInteritemSpacing = 0
  772. minimumLineSpacing = marginLeftRight
  773. self.scrollDirection = .vertical
  774. self.sectionInset = UIEdgeInsets(top: 0, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  775. }
  776. required init?(coder aDecoder: NSCoder) {
  777. fatalError("init(coder:) has not been implemented")
  778. }
  779. override var itemSize: CGSize {
  780. get {
  781. if let collectionView = collectionView {
  782. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  783. let itemHeight: CGFloat = itemWidth
  784. return CGSize(width: itemWidth, height: itemHeight)
  785. }
  786. // Default fallback
  787. return CGSize(width: 100, height: 100)
  788. }
  789. set {
  790. super.itemSize = newValue
  791. }
  792. }
  793. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  794. return proposedContentOffset
  795. }
  796. }