NCMedia.swift 44 KB

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