NCMedia.swift 44 KB

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