NCMedia.swift 43 KB

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