NCMedia.swift 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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, let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  333. if metadata.account == appDelegate.account {
  334. let indexes = self.metadatas.indices.filter { self.metadatas[$0].ocId == metadata.ocId }
  335. let metadatas = self.metadatas.filter { $0.ocId != metadata.ocId }
  336. self.metadatas = metadatas
  337. if self.metadatas.count == 0 {
  338. collectionView?.reloadData()
  339. } else if let row = indexes.first {
  340. let indexPath = IndexPath(row: row, section: 0)
  341. collectionView?.deleteItems(at: [indexPath])
  342. }
  343. self.updateMediaControlVisibility()
  344. }
  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. collectionView?.deleteItems(at: [indexPath])
  361. }
  362. self.updateMediaControlVisibility()
  363. }
  364. }
  365. }
  366. }
  367. @objc func renameFile(_ notification: NSNotification) {
  368. if self.view?.window == nil { return }
  369. if let userInfo = notification.userInfo as NSDictionary? {
  370. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  371. if metadata.account == appDelegate.account {
  372. self.reloadDataSource()
  373. }
  374. }
  375. }
  376. }
  377. // MARK: - Empty
  378. func emptyDataSetView(_ view: NCEmptyView) {
  379. view.emptyImage.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: .gray)
  380. if oldInProgress || newInProgress {
  381. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  382. } else {
  383. view.emptyTitle.text = NSLocalizedString("_tutorial_photo_view_", comment: "")
  384. }
  385. view.emptyDescription.text = ""
  386. }
  387. // MARK: SEGUE
  388. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  389. if let segueNavigationController = segue.destination as? UINavigationController {
  390. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  391. segueViewController.metadata = metadataTouch
  392. segueViewController.metadatas = metadatas
  393. segueViewController.mediaFilterImage = true
  394. segueViewController.layoutKey = k_layout_view_media
  395. }
  396. }
  397. }
  398. }
  399. // MARK: - 3D Touch peek and pop
  400. extension NCMedia: UIViewControllerPreviewingDelegate {
  401. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  402. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  403. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  404. let metadata = metadatas[indexPath.row]
  405. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  406. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  407. previewingContext.sourceRect = cell.frame
  408. viewController.metadata = metadata
  409. viewController.imageFile = cell.imageItem.image
  410. viewController.showOpenIn = true
  411. viewController.showShare = false
  412. viewController.showOpenQuickLook = false
  413. return viewController
  414. }
  415. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  416. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  417. collectionView(collectionView, didSelectItemAt: indexPath)
  418. }
  419. }
  420. // MARK: - Collection View
  421. extension NCMedia: UICollectionViewDelegate {
  422. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  423. let metadata = metadatas[indexPath.row]
  424. metadataTouch = metadata
  425. if isEditMode {
  426. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  427. selectOcId.remove(at: index)
  428. } else {
  429. selectOcId.append(metadata.ocId)
  430. }
  431. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  432. collectionView.reloadItems(at: [indexPath])
  433. }
  434. return
  435. }
  436. performSegue(withIdentifier: "segueDetail", sender: self)
  437. }
  438. }
  439. extension NCMedia: UICollectionViewDataSourcePrefetching {
  440. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  441. //print("[LOG] n. " + String(indexPaths.count))
  442. }
  443. }
  444. extension NCMedia: UICollectionViewDataSource {
  445. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  446. CATransaction.begin()
  447. CATransaction.setCompletionBlock(closure)
  448. collectionView?.reloadData()
  449. CATransaction.commit()
  450. }
  451. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  452. emptyDataSet?.numberOfItemsInSection(metadatas.count, section: section)
  453. return metadatas.count
  454. }
  455. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  456. if indexPath.row < self.metadatas.count {
  457. let metadata = self.metadatas[indexPath.row]
  458. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  459. }
  460. }
  461. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  462. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
  463. let metadata = metadatas[indexPath.row]
  464. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  465. }
  466. }
  467. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  468. let metadata = metadatas[indexPath.row]
  469. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  470. self.cellHeigth = cell.frame.size.height
  471. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  472. cell.imageItem.backgroundColor = nil
  473. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  474. } else if(!metadata.hasPreview) {
  475. cell.imageItem.backgroundColor = nil
  476. if metadata.iconName.count > 0 {
  477. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  478. } else {
  479. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  480. }
  481. }
  482. cell.date = metadata.date as Date
  483. if metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  484. cell.imageStatus.image = cacheImages.cellPlayImage
  485. } else if metadata.livePhoto && livePhoto {
  486. cell.imageStatus.image = cacheImages.cellLivePhotoImage
  487. }
  488. if isEditMode {
  489. cell.selectMode(true)
  490. if selectOcId.contains(metadata.ocId) {
  491. cell.selected(true)
  492. } else {
  493. cell.selected(false)
  494. }
  495. } else {
  496. cell.selectMode(false)
  497. }
  498. return cell
  499. }
  500. }
  501. extension NCMedia: UICollectionViewDelegateFlowLayout {
  502. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  503. return CGSize(width: collectionView.frame.width, height: 0)
  504. }
  505. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  506. return CGSize(width: collectionView.frame.width, height: 0)
  507. }
  508. }
  509. // MARK: - NC API & Algorithm
  510. extension NCMedia {
  511. @objc func reloadDataSource() {
  512. self.reloadDataSourceWithCompletion { (_) in }
  513. }
  514. @objc func reloadDataSourceWithCompletion(_ completion: @escaping (_ metadatas: [tableMetadata]) -> Void) {
  515. if (appDelegate.account == nil || appDelegate.account.count == 0 || appDelegate.maintenanceMode == true) { return }
  516. if account != appDelegate.account {
  517. self.metadatas = []
  518. account = appDelegate.account
  519. collectionView?.reloadData()
  520. }
  521. livePhoto = CCUtility.getLivePhoto()
  522. if let tableAccount = NCManageDatabase.sharedInstance.getAccountActive() {
  523. self.mediaPath = tableAccount.mediaPath
  524. }
  525. let startServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) + mediaPath
  526. 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)
  527. if filterTypeFileImage {
  528. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, k_metadataTypeFile_video)
  529. } else if filterTypeFileVideo {
  530. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, k_metadataTypeFile_image)
  531. } else {
  532. predicate = predicateDefault
  533. }
  534. guard var predicateForGetMetadatasMedia = predicate else { return }
  535. if livePhoto {
  536. let predicateLivePhoto = NSPredicate(format: "!(ext == 'mov' AND livePhoto == true)")
  537. predicateForGetMetadatasMedia = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateForGetMetadatasMedia, predicateLivePhoto])
  538. }
  539. DispatchQueue.global().async {
  540. self.metadatas = NCManageDatabase.sharedInstance.getMetadatasMedia(predicate: predicateForGetMetadatasMedia, sort: CCUtility.getMediaSortDate())
  541. DispatchQueue.main.sync {
  542. self.reloadDataThenPerform {
  543. self.updateMediaControlVisibility()
  544. self.mediaCommandTitle()
  545. completion(self.metadatas)
  546. }
  547. }
  548. }
  549. }
  550. func updateMediaControlVisibility() {
  551. if self.metadatas.count == 0 {
  552. if !self.filterTypeFileImage && !self.filterTypeFileVideo {
  553. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  554. self.mediaCommandView?.isHidden = false
  555. } else {
  556. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  557. self.mediaCommandView?.isHidden = false
  558. }
  559. } else {
  560. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  561. self.mediaCommandView?.isHidden = false
  562. }
  563. }
  564. private func searchOldPhotoVideo(value: Int = -30, limit: Int = 300) {
  565. if oldInProgress { return }
  566. else { oldInProgress = true }
  567. collectionView.reloadData()
  568. var lessDate = Date()
  569. if predicateDefault != nil {
  570. if let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: predicateDefault!, sorted: "date", ascending: true) {
  571. lessDate = metadata.date as Date
  572. }
  573. }
  574. var greaterDate: Date
  575. if value == -999 {
  576. greaterDate = Date.distantPast
  577. } else {
  578. greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
  579. }
  580. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  581. NCUtility.shared.startActivityIndicator(view: self.view, bottom: height + 50)
  582. NCCommunication.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), timeout: 120) { (account, files, errorCode, errorDescription) in
  583. self.oldInProgress = false
  584. NCUtility.shared.stopActivityIndicator()
  585. self.collectionView.reloadData()
  586. if errorCode == 0 && account == self.appDelegate.account {
  587. if files.count > 0 {
  588. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: self.appDelegate.account) { (_, _, metadatas) in
  589. let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  590. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateDate, self.predicateDefault!])
  591. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicateResult)
  592. let metadatasChanged = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  593. if metadatasChanged.metadatasUpdate.count == 0 {
  594. self.researchOldPhotoVideo(value: value, limit: limit, withElseReloadDataSource: true)
  595. } else {
  596. self.reloadDataSource()
  597. }
  598. }
  599. } else {
  600. self.researchOldPhotoVideo(value: value, limit: limit, withElseReloadDataSource: false)
  601. }
  602. }
  603. }
  604. }
  605. private func researchOldPhotoVideo(value: Int , limit: Int, withElseReloadDataSource: Bool) {
  606. if value == -30 {
  607. searchOldPhotoVideo(value: -90)
  608. } else if value == -90 {
  609. searchOldPhotoVideo(value: -180)
  610. } else if value == -180 {
  611. searchOldPhotoVideo(value: -999)
  612. } else if value == -999 && limit > 0 {
  613. searchOldPhotoVideo(value: -999, limit: 0)
  614. } else {
  615. if withElseReloadDataSource {
  616. reloadDataSource()
  617. }
  618. }
  619. }
  620. @objc func searchNewPhotoVideo(limit: Int = 300) {
  621. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  622. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  623. newInProgress = true
  624. reloadDataThenPerform {
  625. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  626. if let cell = visibleCells.first as? NCGridMediaCell {
  627. if cell.date != nil {
  628. if cell.date != self.metadatas.first?.date as Date? {
  629. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  630. }
  631. }
  632. }
  633. if let cell = visibleCells.last as? NCGridMediaCell {
  634. if cell.date != nil {
  635. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  636. }
  637. }
  638. }
  639. 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
  640. self.newInProgress = false
  641. if errorCode == 0 && account == self.appDelegate.account && files.count > 0 {
  642. NCManageDatabase.sharedInstance.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
  643. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  644. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate, self.predicate!])
  645. let metadatasResult = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicateResult)
  646. let updateMetadatas = NCManageDatabase.sharedInstance.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  647. if updateMetadatas.metadatasUpdate.count > 0 {
  648. self.reloadDataSource()
  649. }
  650. }
  651. } else if errorCode == 0 && files.count == 0 && limit > 0 {
  652. self.searchNewPhotoVideo(limit: 0)
  653. } else if errorCode == 0 && files.count == 0 && self.metadatas.count == 0 {
  654. self.searchOldPhotoVideo()
  655. }
  656. }
  657. }
  658. }
  659. private func downloadThumbnail() {
  660. guard let collectionView = self.collectionView else { return }
  661. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  662. for indexPath in collectionView.indexPathsForVisibleItems {
  663. let metadata = self.metadatas[indexPath.row]
  664. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  665. }
  666. }
  667. }
  668. }
  669. // MARK: - ScrollView
  670. extension NCMedia: UIScrollViewDelegate {
  671. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  672. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
  673. mediaCommandTitle()
  674. lastContentOffsetY = scrollView.contentOffset.y
  675. }
  676. }
  677. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  678. mediaCommandView?.collapseControlButtonView(true)
  679. }
  680. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  681. if !decelerate {
  682. self.searchNewPhotoVideo()
  683. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  684. searchOldPhotoVideo()
  685. }
  686. }
  687. }
  688. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  689. self.searchNewPhotoVideo()
  690. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  691. searchOldPhotoVideo()
  692. }
  693. }
  694. }
  695. // MARK: - Media Command View
  696. class NCMediaCommandView: UIView {
  697. @IBOutlet weak var moreView: UIVisualEffectView!
  698. @IBOutlet weak var gridSwitchButton: UIButton!
  699. @IBOutlet weak var separatorView: UIView!
  700. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  701. @IBOutlet weak var zoomInButton: UIButton!
  702. @IBOutlet weak var zoomOutButton: UIButton!
  703. @IBOutlet weak var moreButton: UIButton!
  704. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  705. @IBOutlet weak var title : UILabel!
  706. var mediaView:NCMedia?
  707. private let gradient: CAGradientLayer = CAGradientLayer()
  708. override func awakeFromNib() {
  709. moreView.layer.cornerRadius = 20
  710. moreView.layer.masksToBounds = true
  711. controlButtonView.layer.cornerRadius = 20
  712. controlButtonView.layer.masksToBounds = true
  713. gradient.frame = bounds
  714. gradient.startPoint = CGPoint(x: 0, y: 0.50)
  715. gradient.endPoint = CGPoint(x: 0, y: 0.9)
  716. gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
  717. layer.insertSublayer(gradient, at: 0)
  718. moreButton.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "more"), width: 50, height: 50, color: .white), for: .normal)
  719. title.text = ""
  720. }
  721. func toggleEmptyView(isEmpty: Bool) {
  722. if isEmpty {
  723. UIView.animate(withDuration: 0.3) {
  724. self.moreView.effect = UIBlurEffect(style: .dark)
  725. self.gradient.isHidden = true
  726. self.controlButtonView.isHidden = true
  727. }
  728. } else {
  729. UIView.animate(withDuration: 0.3) {
  730. self.moreView.effect = UIBlurEffect(style: .regular)
  731. self.gradient.isHidden = false
  732. self.controlButtonView.isHidden = false
  733. }
  734. }
  735. }
  736. @IBAction func moreButtonPressed(_ sender: UIButton) {
  737. mediaView?.openMenuButtonMore(sender)
  738. }
  739. @IBAction func zoomInPressed(_ sender: UIButton) {
  740. mediaView?.zoomInGrid()
  741. }
  742. @IBAction func zoomOutPressed(_ sender: UIButton) {
  743. mediaView?.zoomOutGrid()
  744. }
  745. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  746. self.collapseControlButtonView(false)
  747. }
  748. func collapseControlButtonView(_ collapse: Bool) {
  749. if (collapse) {
  750. self.buttonControlWidthConstraint.constant = 40
  751. UIView.animate(withDuration: 0.25) {
  752. self.zoomOutButton.isHidden = true
  753. self.zoomInButton.isHidden = true
  754. self.separatorView.isHidden = true
  755. self.gridSwitchButton.isHidden = false
  756. self.layoutIfNeeded()
  757. }
  758. } else {
  759. self.buttonControlWidthConstraint.constant = 80
  760. UIView.animate(withDuration: 0.25) {
  761. self.zoomOutButton.isHidden = false
  762. self.zoomInButton.isHidden = false
  763. self.separatorView.isHidden = false
  764. self.gridSwitchButton.isHidden = true
  765. self.layoutIfNeeded()
  766. }
  767. }
  768. }
  769. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  770. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  771. }
  772. override func layoutSublayers(of layer: CALayer) {
  773. super.layoutSublayers(of: layer)
  774. gradient.frame = bounds
  775. }
  776. }
  777. // MARK: - Media Grid Layout
  778. class NCGridMediaLayout: UICollectionViewFlowLayout {
  779. var marginLeftRight: CGFloat = 6
  780. var itemForLine: CGFloat = 3
  781. override init() {
  782. super.init()
  783. sectionHeadersPinToVisibleBounds = false
  784. minimumInteritemSpacing = 0
  785. minimumLineSpacing = marginLeftRight
  786. self.scrollDirection = .vertical
  787. self.sectionInset = UIEdgeInsets(top: 0, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  788. }
  789. required init?(coder aDecoder: NSCoder) {
  790. fatalError("init(coder:) has not been implemented")
  791. }
  792. override var itemSize: CGSize {
  793. get {
  794. if let collectionView = collectionView {
  795. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  796. let itemHeight: CGFloat = itemWidth
  797. return CGSize(width: itemWidth, height: itemHeight)
  798. }
  799. // Default fallback
  800. return CGSize(width: 100, height: 100)
  801. }
  802. set {
  803. super.itemSize = newValue
  804. }
  805. }
  806. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  807. return proposedContentOffset
  808. }
  809. }