NCMedia.swift 44 KB

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