NCMedia.swift 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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 NCViewerProviderContextMenu(metadata: metadata)
  411. }, actionProvider: { suggestedActions in
  412. var titleDelete = NSLocalizedString("_delete_photo_", comment: "")
  413. if metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileVideo { titleDelete = NSLocalizedString("_delete_video_", comment: "") }
  414. var save = UIAction(title: NSLocalizedString("_save_selected_files_", comment: ""), image: UIImage(systemName: "square.and.arrow.down")) { action in
  415. NCOperationQueue.shared.download(metadata: metadata, selector: NCBrandGlobal.shared.selectorSaveAlbum, setFavorite: false)
  416. }
  417. if let metadataMov = NCManageDatabase.shared.isLivePhoto(metadata: metadata) {
  418. save = UIAction(title: NSLocalizedString("_livephoto_save_", comment: ""), image: UIImage(systemName: "square.and.arrow.down")) { action in
  419. NCCollectionCommon.shared.saveLivePhoto(metadata: metadata, metadataMov: metadataMov, progressView: nil, viewActivity: self.view)
  420. }
  421. }
  422. let openIn = UIAction(title: NSLocalizedString("_open_in_", comment: ""), image: UIImage(systemName: "square.and.arrow.up") ) { action in
  423. NCNetworkingNotificationCenter.shared.downloadOpen(metadata: metadata, selector: NCBrandGlobal.shared.selectorOpenIn)
  424. }
  425. let moveCopy = UIAction(title: NSLocalizedString("_move_or_copy_", comment: ""), image: UIImage(systemName: "arrow.up.right.square")) { action in
  426. NCCollectionCommon.shared.openSelectView(items: [metadata])
  427. }
  428. let deleteConfirm = UIAction(title: titleDelete, image: UIImage(systemName: "trash"), attributes: .destructive) { action in
  429. NCNetworking.shared.deleteMetadata(metadata, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, onlyLocal: false) { (errorCode, errorDescription) in
  430. if errorCode != 0 {
  431. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCBrandGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  432. }
  433. }
  434. }
  435. let delete = UIMenu(title: titleDelete, image: UIImage(systemName: "trash"), options: .destructive, children: [deleteConfirm])
  436. return UIMenu(title: "", children: [save, openIn, moveCopy, delete])
  437. })
  438. }
  439. }
  440. extension NCMedia: UICollectionViewDataSourcePrefetching {
  441. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  442. //print("[LOG] n. " + String(indexPaths.count))
  443. }
  444. }
  445. extension NCMedia: UICollectionViewDataSource {
  446. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  447. CATransaction.begin()
  448. CATransaction.setCompletionBlock(closure)
  449. collectionView?.reloadData()
  450. CATransaction.commit()
  451. }
  452. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  453. emptyDataSet?.numberOfItemsInSection(metadatas.count, section: section)
  454. return metadatas.count
  455. }
  456. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  457. if indexPath.row < self.metadatas.count {
  458. let metadata = self.metadatas[indexPath.row]
  459. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  460. }
  461. }
  462. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  463. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
  464. let metadata = metadatas[indexPath.row]
  465. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  466. }
  467. }
  468. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  469. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) && indexPath.row < metadatas.count {
  470. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  471. let metadata = metadatas[indexPath.row]
  472. self.cellHeigth = cell.frame.size.height
  473. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  474. cell.imageItem.backgroundColor = nil
  475. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  476. } else if(!metadata.hasPreview) {
  477. cell.imageItem.backgroundColor = nil
  478. if metadata.iconName.count > 0 {
  479. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  480. } else {
  481. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  482. }
  483. }
  484. cell.date = metadata.date as Date
  485. if metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCBrandGlobal.shared.metadataTypeFileAudio {
  486. cell.imageStatus.image = cacheImages.cellPlayImage
  487. } else if metadata.livePhoto && livePhoto {
  488. cell.imageStatus.image = cacheImages.cellLivePhotoImage
  489. }
  490. if isEditMode {
  491. cell.selectMode(true)
  492. if selectOcId.contains(metadata.ocId) {
  493. cell.selected(true)
  494. } else {
  495. cell.selected(false)
  496. }
  497. } else {
  498. cell.selectMode(false)
  499. }
  500. return cell
  501. } else {
  502. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  503. }
  504. }
  505. }
  506. extension NCMedia: UICollectionViewDelegateFlowLayout {
  507. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  508. return CGSize(width: collectionView.frame.width, height: 0)
  509. }
  510. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  511. return CGSize(width: collectionView.frame.width, height: 0)
  512. }
  513. }
  514. // MARK: - NC API & Algorithm
  515. extension NCMedia {
  516. @objc func reloadDataSource() {
  517. self.reloadDataSourceWithCompletion { (_) in }
  518. }
  519. @objc func reloadDataSourceWithCompletion(_ completion: @escaping (_ metadatas: [tableMetadata]) -> Void) {
  520. if appDelegate.account == nil || appDelegate.account.count == 0 { return }
  521. if account != appDelegate.account {
  522. self.metadatas = []
  523. account = appDelegate.account
  524. collectionView?.reloadData()
  525. }
  526. livePhoto = CCUtility.getLivePhoto()
  527. if let tableAccount = NCManageDatabase.shared.getAccountActive() {
  528. self.mediaPath = tableAccount.mediaPath
  529. }
  530. let startServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) + mediaPath
  531. 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)
  532. if filterTypeFileImage {
  533. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NCBrandGlobal.shared.metadataTypeFileVideo)
  534. } else if filterTypeFileVideo {
  535. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NCBrandGlobal.shared.metadataTypeFileImage)
  536. } else {
  537. predicate = predicateDefault
  538. }
  539. guard var predicateForGetMetadatasMedia = predicate else { return }
  540. if livePhoto {
  541. let predicateLivePhoto = NSPredicate(format: "!(ext == 'mov' AND livePhoto == true)")
  542. predicateForGetMetadatasMedia = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateForGetMetadatasMedia, predicateLivePhoto])
  543. }
  544. DispatchQueue.global().async {
  545. self.metadatas = NCManageDatabase.shared.getMetadatasMedia(predicate: predicateForGetMetadatasMedia, sort: CCUtility.getMediaSortDate())
  546. DispatchQueue.main.sync {
  547. self.reloadDataThenPerform {
  548. self.updateMediaControlVisibility()
  549. self.mediaCommandTitle()
  550. completion(self.metadatas)
  551. }
  552. }
  553. }
  554. }
  555. func updateMediaControlVisibility() {
  556. if self.metadatas.count == 0 {
  557. if !self.filterTypeFileImage && !self.filterTypeFileVideo {
  558. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  559. self.mediaCommandView?.isHidden = false
  560. } else {
  561. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  562. self.mediaCommandView?.isHidden = false
  563. }
  564. } else {
  565. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  566. self.mediaCommandView?.isHidden = false
  567. }
  568. }
  569. private func searchOldMedia(value: Int = -30, limit: Int = 300) {
  570. if oldInProgress { return }
  571. else { oldInProgress = true }
  572. collectionView.reloadData()
  573. var lessDate = Date()
  574. if predicateDefault != nil {
  575. if let metadata = NCManageDatabase.shared.getMetadata(predicate: predicateDefault!, sorted: "date", ascending: true) {
  576. lessDate = metadata.date as Date
  577. }
  578. }
  579. var greaterDate: Date
  580. if value == -999 {
  581. greaterDate = Date.distantPast
  582. } else {
  583. greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
  584. }
  585. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  586. NCUtility.shared.startActivityIndicator(view: self.view, bottom: height + 50)
  587. NCCommunication.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), timeout: 120) { (account, files, errorCode, errorDescription) in
  588. self.oldInProgress = false
  589. NCUtility.shared.stopActivityIndicator()
  590. self.collectionView.reloadData()
  591. if errorCode == 0 && account == self.appDelegate.account {
  592. if files.count > 0 {
  593. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: self.appDelegate.account) { (_, _, metadatas) in
  594. let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  595. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateDate, self.predicateDefault!])
  596. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult)
  597. let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  598. if metadatasChanged.metadatasUpdate.count == 0 {
  599. self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: true)
  600. } else {
  601. self.reloadDataSource()
  602. }
  603. }
  604. } else {
  605. self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: false)
  606. }
  607. }
  608. }
  609. }
  610. private func researchOldMedia(value: Int , limit: Int, withElseReloadDataSource: Bool) {
  611. if value == -30 {
  612. searchOldMedia(value: -90)
  613. } else if value == -90 {
  614. searchOldMedia(value: -180)
  615. } else if value == -180 {
  616. searchOldMedia(value: -999)
  617. } else if value == -999 && limit > 0 {
  618. searchOldMedia(value: -999, limit: 0)
  619. } else {
  620. if withElseReloadDataSource {
  621. reloadDataSource()
  622. }
  623. }
  624. }
  625. @objc func searchNewMediaTimer() {
  626. self.searchNewMedia()
  627. }
  628. @objc func searchNewMedia(limit: Int = 300) {
  629. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  630. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  631. newInProgress = true
  632. reloadDataThenPerform {
  633. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  634. if let cell = visibleCells.first as? NCGridMediaCell {
  635. if cell.date != nil {
  636. if cell.date != self.metadatas.first?.date as Date? {
  637. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  638. }
  639. }
  640. }
  641. if let cell = visibleCells.last as? NCGridMediaCell {
  642. if cell.date != nil {
  643. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  644. }
  645. }
  646. }
  647. 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
  648. self.newInProgress = false
  649. if errorCode == 0 && account == self.appDelegate.account && files.count > 0 {
  650. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
  651. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  652. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate, self.predicate!])
  653. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult)
  654. let updateMetadatas = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  655. if updateMetadatas.metadatasUpdate.count > 0 {
  656. self.reloadDataSource()
  657. }
  658. }
  659. } else if errorCode == 0 && files.count == 0 && limit > 0 {
  660. self.searchNewMedia(limit: 0)
  661. } else if errorCode == 0 && files.count == 0 && self.metadatas.count == 0 {
  662. self.searchOldMedia()
  663. }
  664. }
  665. }
  666. }
  667. private func downloadThumbnail() {
  668. guard let collectionView = self.collectionView else { return }
  669. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  670. for indexPath in collectionView.indexPathsForVisibleItems {
  671. let metadata = self.metadatas[indexPath.row]
  672. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  673. }
  674. }
  675. }
  676. }
  677. // MARK: - ScrollView
  678. extension NCMedia: UIScrollViewDelegate {
  679. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  680. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
  681. mediaCommandTitle()
  682. lastContentOffsetY = scrollView.contentOffset.y
  683. }
  684. }
  685. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  686. mediaCommandView?.collapseControlButtonView(true)
  687. }
  688. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  689. if !decelerate {
  690. timerSearchNewMedia?.invalidate()
  691. timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false)
  692. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  693. searchOldMedia()
  694. }
  695. }
  696. }
  697. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  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. // MARK: - Media Command View
  706. class NCMediaCommandView: UIView {
  707. @IBOutlet weak var moreView: UIVisualEffectView!
  708. @IBOutlet weak var gridSwitchButton: UIButton!
  709. @IBOutlet weak var separatorView: UIView!
  710. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  711. @IBOutlet weak var zoomInButton: UIButton!
  712. @IBOutlet weak var zoomOutButton: UIButton!
  713. @IBOutlet weak var moreButton: UIButton!
  714. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  715. @IBOutlet weak var title : UILabel!
  716. var mediaView:NCMedia?
  717. private let gradient: CAGradientLayer = CAGradientLayer()
  718. override func awakeFromNib() {
  719. moreView.layer.cornerRadius = 20
  720. moreView.layer.masksToBounds = true
  721. controlButtonView.layer.cornerRadius = 20
  722. controlButtonView.layer.masksToBounds = true
  723. gradient.frame = bounds
  724. gradient.startPoint = CGPoint(x: 0, y: 0.50)
  725. gradient.endPoint = CGPoint(x: 0, y: 0.9)
  726. gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
  727. layer.insertSublayer(gradient, at: 0)
  728. moreButton.setImage(UIImage.init(named: "more")!.image(color: .white, size: 25), for: .normal)
  729. title.text = ""
  730. }
  731. func toggleEmptyView(isEmpty: Bool) {
  732. if isEmpty {
  733. UIView.animate(withDuration: 0.3) {
  734. self.moreView.effect = UIBlurEffect(style: .dark)
  735. self.gradient.isHidden = true
  736. self.controlButtonView.isHidden = true
  737. }
  738. } else {
  739. UIView.animate(withDuration: 0.3) {
  740. self.moreView.effect = UIBlurEffect(style: .regular)
  741. self.gradient.isHidden = false
  742. self.controlButtonView.isHidden = false
  743. }
  744. }
  745. }
  746. @IBAction func moreButtonPressed(_ sender: UIButton) {
  747. mediaView?.openMenuButtonMore(sender)
  748. }
  749. @IBAction func zoomInPressed(_ sender: UIButton) {
  750. mediaView?.zoomInGrid()
  751. }
  752. @IBAction func zoomOutPressed(_ sender: UIButton) {
  753. mediaView?.zoomOutGrid()
  754. }
  755. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  756. self.collapseControlButtonView(false)
  757. }
  758. func collapseControlButtonView(_ collapse: Bool) {
  759. if (collapse) {
  760. self.buttonControlWidthConstraint.constant = 40
  761. UIView.animate(withDuration: 0.25) {
  762. self.zoomOutButton.isHidden = true
  763. self.zoomInButton.isHidden = true
  764. self.separatorView.isHidden = true
  765. self.gridSwitchButton.isHidden = false
  766. self.layoutIfNeeded()
  767. }
  768. } else {
  769. self.buttonControlWidthConstraint.constant = 80
  770. UIView.animate(withDuration: 0.25) {
  771. self.zoomOutButton.isHidden = false
  772. self.zoomInButton.isHidden = false
  773. self.separatorView.isHidden = false
  774. self.gridSwitchButton.isHidden = true
  775. self.layoutIfNeeded()
  776. }
  777. }
  778. }
  779. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  780. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  781. }
  782. override func layoutSublayers(of layer: CALayer) {
  783. super.layoutSublayers(of: layer)
  784. gradient.frame = bounds
  785. }
  786. }
  787. // MARK: - Media Grid Layout
  788. class NCGridMediaLayout: UICollectionViewFlowLayout {
  789. var marginLeftRight: CGFloat = 6
  790. var itemForLine: CGFloat = 3
  791. override init() {
  792. super.init()
  793. sectionHeadersPinToVisibleBounds = false
  794. minimumInteritemSpacing = 0
  795. minimumLineSpacing = marginLeftRight
  796. self.scrollDirection = .vertical
  797. self.sectionInset = UIEdgeInsets(top: 0, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  798. }
  799. required init?(coder aDecoder: NSCoder) {
  800. fatalError("init(coder:) has not been implemented")
  801. }
  802. override var itemSize: CGSize {
  803. get {
  804. if let collectionView = collectionView {
  805. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  806. let itemHeight: CGFloat = itemWidth
  807. return CGSize(width: itemWidth, height: itemHeight)
  808. }
  809. // Default fallback
  810. return CGSize(width: 100, height: 100)
  811. }
  812. set {
  813. super.itemSize = newValue
  814. }
  815. }
  816. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  817. return proposedContentOffset
  818. }
  819. }