NCMedia.swift 43 KB

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