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