NCMedia.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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 UIKit
  24. import NextcloudKit
  25. import JGProgressHUD
  26. class NCMedia: UIViewController, NCEmptyDataSetDelegate, NCSelectDelegate {
  27. @IBOutlet weak var collectionView: UICollectionView!
  28. private var emptyDataSet: NCEmptyDataSet?
  29. private var mediaCommandView: NCMediaCommandView?
  30. private var gridLayout: NCGridMediaLayout!
  31. internal var documentPickerViewController: NCDocumentPickerViewController?
  32. internal let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. public var metadatas: [tableMetadata] = []
  34. private var account: String = ""
  35. private var predicateDefault: NSPredicate?
  36. private var predicate: NSPredicate?
  37. internal var isEditMode = false
  38. internal var selectOcId: [String] = []
  39. internal var selectIndexPath: [IndexPath] = []
  40. internal var filterClassTypeImage = false
  41. internal var filterClassTypeVideo = false
  42. private let maxImageGrid: CGFloat = 7
  43. private var cellHeigth: CGFloat = 0
  44. private var oldInProgress = false
  45. private var newInProgress = false
  46. private var lastContentOffsetY: CGFloat = 0
  47. private var mediaPath = ""
  48. private var livePhoto: Bool = false
  49. private var timeIntervalSearchNewMedia: TimeInterval = 3.0
  50. private var timerSearchNewMedia: Timer?
  51. private let insetsTop: CGFloat = 75
  52. struct cacheImages {
  53. static var cellLivePhotoImage = UIImage()
  54. static var cellPlayImage = UIImage()
  55. }
  56. // MARK: - View Life Cycle
  57. override func viewDidLoad() {
  58. super.viewDidLoad()
  59. view.backgroundColor = .systemBackground
  60. collectionView.register(UINib(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  61. collectionView.alwaysBounceVertical = true
  62. collectionView.contentInset = UIEdgeInsets(top: insetsTop, left: 0, bottom: 50, right: 0)
  63. collectionView.backgroundColor = .systemBackground
  64. gridLayout = NCGridMediaLayout()
  65. gridLayout.itemForLine = CGFloat(min(CCUtility.getMediaWidthImage(), 5))
  66. gridLayout.sectionHeadersPinToVisibleBounds = true
  67. collectionView.collectionViewLayout = gridLayout
  68. // Empty
  69. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: 0, delegate: self)
  70. // Notification
  71. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  72. mediaCommandView = Bundle.main.loadNibNamed("NCMediaCommandView", owner: self, options: nil)?.first as? NCMediaCommandView
  73. self.view.addSubview(mediaCommandView!)
  74. mediaCommandView?.mediaView = self
  75. mediaCommandView?.zoomInButton.isEnabled = !(gridLayout.itemForLine == 1)
  76. mediaCommandView?.zoomOutButton.isEnabled = !(gridLayout.itemForLine == maxImageGrid - 1)
  77. mediaCommandView?.collapseControlButtonView(true)
  78. mediaCommandView?.translatesAutoresizingMaskIntoConstraints = false
  79. mediaCommandView?.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  80. mediaCommandView?.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  81. mediaCommandView?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  82. mediaCommandView?.heightAnchor.constraint(equalToConstant: 150).isActive = true
  83. self.updateMediaControlVisibility()
  84. collectionView.prefetchDataSource = self
  85. cacheImages.cellLivePhotoImage = NCUtility.shared.loadImage(named: "livephoto", color: .white)
  86. cacheImages.cellPlayImage = NCUtility.shared.loadImage(named: "play.fill", color: .white)
  87. }
  88. override func viewWillAppear(_ animated: Bool) {
  89. super.viewWillAppear(animated)
  90. appDelegate.activeViewController = self
  91. navigationController?.setMediaAppreance()
  92. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  93. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  94. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  95. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  96. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  97. self.reloadDataSourceWithCompletion { _ in
  98. self.timerSearchNewMedia?.invalidate()
  99. self.timerSearchNewMedia = Timer.scheduledTimer(timeInterval: self.timeIntervalSearchNewMedia, target: self, selector: #selector(self.searchNewMediaTimer), userInfo: nil, repeats: false)
  100. }
  101. }
  102. override func viewDidAppear(_ animated: Bool) {
  103. super.viewDidAppear(animated)
  104. mediaCommandTitle()
  105. }
  106. override func viewWillDisappear(_ animated: Bool) {
  107. super.viewWillDisappear(animated)
  108. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  109. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  110. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  111. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  112. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  113. }
  114. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  115. super.viewWillTransition(to: size, with: coordinator)
  116. self.collectionView?.collectionViewLayout.invalidateLayout()
  117. }
  118. override var preferredStatusBarStyle: UIStatusBarStyle {
  119. return .lightContent
  120. }
  121. // MARK: - NotificationCenter
  122. @objc func initialize() {
  123. self.reloadDataSourceWithCompletion { _ in
  124. self.timerSearchNewMedia?.invalidate()
  125. self.timerSearchNewMedia = Timer.scheduledTimer(timeInterval: self.timeIntervalSearchNewMedia, target: self, selector: #selector(self.searchNewMediaTimer), userInfo: nil, repeats: false)
  126. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  127. self.mediaCommandTitle()
  128. }
  129. }
  130. }
  131. @objc func deleteFile(_ notification: NSNotification) {
  132. guard let userInfo = notification.userInfo as NSDictionary?,
  133. let error = userInfo["error"] as? NKError else { return }
  134. let onlyLocalCache: Bool = userInfo["onlyLocalCache"] as? Bool ?? false
  135. self.queryDB(isForced: true)
  136. if error == .success, let indexPath = userInfo["indexPath"] as? [IndexPath], !indexPath.isEmpty, !onlyLocalCache {
  137. collectionView?.performBatchUpdates({
  138. collectionView?.deleteItems(at: indexPath)
  139. }, completion: { _ in
  140. self.collectionView?.reloadData()
  141. })
  142. } else {
  143. if error != .success {
  144. NCContentPresenter.shared.showError(error: error)
  145. }
  146. self.collectionView?.reloadData()
  147. }
  148. if let hud = userInfo["hud"] as? JGProgressHUD {
  149. hud.dismiss()
  150. }
  151. }
  152. @objc func moveFile(_ notification: NSNotification) {
  153. guard let userInfo = notification.userInfo as NSDictionary? else { return }
  154. if let hud = userInfo["hud"] as? JGProgressHUD {
  155. hud.dismiss()
  156. }
  157. }
  158. @objc func copyFile(_ notification: NSNotification) {
  159. moveFile(notification)
  160. }
  161. @objc func renameFile(_ notification: NSNotification) {
  162. guard let userInfo = notification.userInfo as NSDictionary?,
  163. let account = userInfo["account"] as? String,
  164. account == appDelegate.account
  165. else { return }
  166. self.reloadDataSourceWithCompletion { _ in }
  167. }
  168. @objc func uploadedFile(_ notification: NSNotification) {
  169. guard let userInfo = notification.userInfo as NSDictionary?,
  170. let error = userInfo["error"] as? NKError,
  171. error == .success,
  172. let account = userInfo["account"] as? String,
  173. account == appDelegate.account
  174. else { return }
  175. self.reloadDataSourceWithCompletion { _ in }
  176. }
  177. // MARK: - Command
  178. func mediaCommandTitle() {
  179. mediaCommandView?.title.text = ""
  180. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  181. if let cell = visibleCells.first as? NCGridMediaCell {
  182. if cell.date != nil {
  183. mediaCommandView?.title.text = CCUtility.getTitleSectionDate(cell.date)
  184. }
  185. }
  186. }
  187. }
  188. @objc func zoomOutGrid() {
  189. UIView.animate(withDuration: 0.0, animations: {
  190. if self.gridLayout.itemForLine + 1 < self.maxImageGrid {
  191. self.gridLayout.itemForLine += 1
  192. self.mediaCommandView?.zoomInButton.isEnabled = true
  193. }
  194. if self.gridLayout.itemForLine == self.maxImageGrid - 1 {
  195. self.mediaCommandView?.zoomOutButton.isEnabled = false
  196. }
  197. self.collectionView.collectionViewLayout.invalidateLayout()
  198. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemForLine))
  199. })
  200. }
  201. @objc func zoomInGrid() {
  202. UIView.animate(withDuration: 0.0, animations: {
  203. if self.gridLayout.itemForLine - 1 > 0 {
  204. self.gridLayout.itemForLine -= 1
  205. self.mediaCommandView?.zoomOutButton.isEnabled = true
  206. }
  207. if self.gridLayout.itemForLine == 1 {
  208. self.mediaCommandView?.zoomInButton.isEnabled = false
  209. }
  210. self.collectionView.collectionViewLayout.invalidateLayout()
  211. CCUtility.setMediaWidthImage(Int(self.gridLayout.itemForLine))
  212. })
  213. }
  214. @objc func openMenuButtonMore(_ sender: Any) {
  215. toggleMenu()
  216. }
  217. // MARK: Select Path
  218. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], indexPath: [IndexPath], overwrite: Bool, copy: Bool, move: Bool) {
  219. guard let serverUrl = serverUrl else { return }
  220. let path = CCUtility.returnPathfromServerUrl(serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account) ?? ""
  221. NCManageDatabase.shared.setAccountMediaPath(path, account: appDelegate.account)
  222. reloadDataSourceWithCompletion { _ in
  223. self.searchNewMedia()
  224. }
  225. }
  226. // MARK: - Empty
  227. func emptyDataSetView(_ view: NCEmptyView) {
  228. view.emptyImage.image = UIImage(named: "media")?.image(color: .gray, size: UIScreen.main.bounds.width)
  229. if oldInProgress || newInProgress {
  230. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  231. } else {
  232. view.emptyTitle.text = NSLocalizedString("_tutorial_photo_view_", comment: "")
  233. }
  234. view.emptyDescription.text = ""
  235. }
  236. }
  237. // MARK: - Collection View
  238. extension NCMedia: UICollectionViewDelegate {
  239. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  240. let metadata = metadatas[indexPath.row]
  241. if isEditMode {
  242. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  243. selectOcId.remove(at: index)
  244. selectIndexPath.removeAll(where: { $0 == indexPath })
  245. } else {
  246. selectOcId.append(metadata.ocId)
  247. selectIndexPath.append(indexPath)
  248. }
  249. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  250. collectionView.reloadItems(at: [indexPath])
  251. }
  252. } else {
  253. // ACTIVE SERVERURL
  254. appDelegate.activeServerUrl = metadata.serverUrl
  255. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridMediaCell
  256. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: cell?.imageItem.image)
  257. }
  258. }
  259. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  260. guard let cell = collectionView.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  261. let metadata = metadatas[indexPath.row]
  262. let identifier = indexPath as NSCopying
  263. let image = cell.imageItem.image
  264. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  265. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  266. }, actionProvider: { _ in
  267. return NCContextMenu().viewMenu(ocId: metadata.ocId, indexPath: indexPath, viewController: self, image: image)
  268. })
  269. }
  270. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  271. animator.addCompletion {
  272. if let indexPath = configuration.identifier as? IndexPath {
  273. self.collectionView(collectionView, didSelectItemAt: indexPath)
  274. }
  275. }
  276. }
  277. }
  278. extension NCMedia: UICollectionViewDataSourcePrefetching {
  279. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  280. // print("[LOG] n. " + String(indexPaths.count))
  281. }
  282. }
  283. extension NCMedia: UICollectionViewDataSource {
  284. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  285. CATransaction.begin()
  286. CATransaction.setCompletionBlock(closure)
  287. collectionView?.reloadData()
  288. CATransaction.commit()
  289. }
  290. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  291. emptyDataSet?.numberOfItemsInSection(metadatas.count, section: section)
  292. return metadatas.count
  293. }
  294. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  295. guard let cell = (cell as? NCGridMediaCell), indexPath.row < self.metadatas.count else { return }
  296. let metadata = self.metadatas[indexPath.row]
  297. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  298. cell.imageItem.backgroundColor = nil
  299. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  300. } else {
  301. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: false, cell: cell, view: collectionView)
  302. }
  303. }
  304. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  305. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
  306. let metadata = metadatas[indexPath.row]
  307. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  308. }
  309. }
  310. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  311. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) && indexPath.row < metadatas.count {
  312. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  313. let metadata = metadatas[indexPath.row]
  314. self.cellHeigth = cell.frame.size.height
  315. cell.date = metadata.date as Date
  316. cell.fileObjectId = metadata.ocId
  317. cell.indexPath = indexPath
  318. cell.fileUser = metadata.ownerId
  319. if metadata.isAudioOrVideo {
  320. cell.imageStatus.image = cacheImages.cellPlayImage
  321. } else if metadata.livePhoto && livePhoto {
  322. cell.imageStatus.image = cacheImages.cellLivePhotoImage
  323. }
  324. if isEditMode {
  325. cell.selectMode(true)
  326. if selectOcId.contains(metadata.ocId) {
  327. cell.selected(true)
  328. } else {
  329. cell.selected(false)
  330. }
  331. } else {
  332. cell.selectMode(false)
  333. }
  334. return cell
  335. } else {
  336. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  337. }
  338. }
  339. }
  340. extension NCMedia: UICollectionViewDelegateFlowLayout {
  341. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  342. return CGSize(width: collectionView.frame.width, height: 0)
  343. }
  344. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  345. return CGSize(width: collectionView.frame.width, height: 0)
  346. }
  347. }
  348. extension NCMedia {
  349. // MARK: - Datasource
  350. func queryDB(isForced: Bool) {
  351. livePhoto = CCUtility.getLivePhoto()
  352. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  353. self.mediaPath = activeAccount.mediaPath
  354. }
  355. let startServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) + mediaPath
  356. predicateDefault = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND (classFile == %@ OR classFile == %@) AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.TypeClassFile.image.rawValue, NKCommon.TypeClassFile.video.rawValue)
  357. if filterClassTypeImage {
  358. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.TypeClassFile.video.rawValue)
  359. } else if filterClassTypeVideo {
  360. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND classFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NKCommon.TypeClassFile.image.rawValue)
  361. } else {
  362. predicate = predicateDefault
  363. }
  364. guard let predicate = predicate else { return }
  365. self.metadatas = NCManageDatabase.shared.getMetadatasMedia(predicate: predicate, livePhoto: self.livePhoto)
  366. switch CCUtility.getMediaSortDate() {
  367. case "date":
  368. self.metadatas = self.metadatas.sorted(by: {($0.date as Date) > ($1.date as Date)})
  369. case "creationDate":
  370. self.metadatas = self.metadatas.sorted(by: {($0.creationDate as Date) > ($1.creationDate as Date)})
  371. case "uploadDate":
  372. self.metadatas = self.metadatas.sorted(by: {($0.uploadDate as Date) > ($1.uploadDate as Date)})
  373. default:
  374. break
  375. }
  376. }
  377. @objc func reloadDataSourceWithCompletion(_ completion: @escaping (_ metadatas: [tableMetadata]) -> Void) {
  378. guard !appDelegate.account.isEmpty else { return }
  379. if account != appDelegate.account {
  380. self.metadatas = []
  381. account = appDelegate.account
  382. DispatchQueue.main.async { self.collectionView?.reloadData() }
  383. }
  384. DispatchQueue.global().async {
  385. self.queryDB(isForced: true)
  386. DispatchQueue.main.sync {
  387. self.reloadDataThenPerform {
  388. self.updateMediaControlVisibility()
  389. self.mediaCommandTitle()
  390. completion(self.metadatas)
  391. }
  392. }
  393. }
  394. }
  395. func updateMediaControlVisibility() {
  396. if self.metadatas.count == 0 {
  397. if !self.filterClassTypeImage && !self.filterClassTypeVideo {
  398. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  399. self.mediaCommandView?.isHidden = false
  400. } else {
  401. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  402. self.mediaCommandView?.isHidden = false
  403. }
  404. } else {
  405. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  406. self.mediaCommandView?.isHidden = false
  407. }
  408. }
  409. // MARK: - Search media
  410. private func searchOldMedia(value: Int = -30, limit: Int = 300) {
  411. if oldInProgress { return } else { oldInProgress = true }
  412. DispatchQueue.main.async {
  413. self.collectionView.reloadData()
  414. var bottom: CGFloat = 0
  415. if let mainTabBar = self.tabBarController?.tabBar as? NCMainTabBar {
  416. bottom = -mainTabBar.getHeight()
  417. }
  418. NCActivityIndicator.shared.start(backgroundView: self.view, bottom: bottom - 5, style: .medium)
  419. }
  420. var lessDate = Date()
  421. if predicateDefault != nil {
  422. if let metadata = NCManageDatabase.shared.getMetadata(predicate: predicateDefault!, sorted: "date", ascending: true) {
  423. lessDate = metadata.date as Date
  424. }
  425. }
  426. var greaterDate: Date
  427. if value == -999 {
  428. greaterDate = Date.distantPast
  429. } else {
  430. greaterDate = Calendar.current.date(byAdding: .day, value: value, to: lessDate)!
  431. }
  432. let options = NKRequestOptions(timeout: 300, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  433. NextcloudKit.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { account, files, _, error in
  434. self.oldInProgress = false
  435. DispatchQueue.main.async {
  436. NCActivityIndicator.shared.stop()
  437. self.collectionView.reloadData()
  438. }
  439. if error == .success && account == self.appDelegate.account {
  440. if files.count > 0 {
  441. NCManageDatabase.shared.convertFilesToMetadatas(files, useMetadataFolder: false) { _, _, metadatas in
  442. let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  443. let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateDate, self.predicateDefault!])
  444. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult)
  445. let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  446. if metadatasChanged.metadatasUpdate.count == 0 {
  447. self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: true)
  448. } else {
  449. self.reloadDataSourceWithCompletion { _ in }
  450. }
  451. }
  452. } else {
  453. self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: false)
  454. }
  455. } else if error != .success {
  456. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Media search old media error code \(error.errorCode) " + error.errorDescription)
  457. }
  458. }
  459. }
  460. private func researchOldMedia(value: Int, limit: Int, withElseReloadDataSource: Bool) {
  461. if value == -30 {
  462. searchOldMedia(value: -90)
  463. } else if value == -90 {
  464. searchOldMedia(value: -180)
  465. } else if value == -180 {
  466. searchOldMedia(value: -999)
  467. } else if value == -999 && limit > 0 {
  468. searchOldMedia(value: -999, limit: 0)
  469. } else {
  470. if withElseReloadDataSource {
  471. self.reloadDataSourceWithCompletion { _ in }
  472. }
  473. }
  474. }
  475. @objc func searchNewMediaTimer() {
  476. self.searchNewMedia()
  477. }
  478. @objc func searchNewMedia() {
  479. if newInProgress { return } else {
  480. newInProgress = true
  481. mediaCommandView?.activityIndicator.startAnimating()
  482. }
  483. var limit: Int = 1000
  484. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  485. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  486. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  487. if let cell = visibleCells.first as? NCGridMediaCell {
  488. if cell.date != nil {
  489. if cell.date != self.metadatas.first?.date as Date? {
  490. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  491. limit = 0
  492. }
  493. }
  494. }
  495. if let cell = visibleCells.last as? NCGridMediaCell {
  496. if cell.date != nil {
  497. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  498. }
  499. }
  500. }
  501. reloadDataThenPerform {
  502. let options = NKRequestOptions(timeout: 300, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  503. NextcloudKit.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), options: options) { account, files, _, error in
  504. self.newInProgress = false
  505. DispatchQueue.main.async {
  506. self.mediaCommandView?.activityIndicator.stopAnimating()
  507. }
  508. if error == .success && account == self.appDelegate.account && files.count > 0 {
  509. NCManageDatabase.shared.convertFilesToMetadatas(files, useMetadataFolder: false) { _, _, metadatas in
  510. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  511. let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, self.predicate!])
  512. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult)
  513. let updateMetadatas = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  514. if updateMetadatas.metadatasUpdate.count > 0 || updateMetadatas.metadatasDelete.count > 0 {
  515. self.reloadDataSourceWithCompletion { _ in }
  516. }
  517. }
  518. } else if error == .success && files.count == 0 && self.metadatas.count == 0 {
  519. self.searchOldMedia()
  520. } else if error != .success {
  521. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Media search new media error code \(error.errorCode) " + error.errorDescription)
  522. }
  523. }
  524. }
  525. }
  526. }
  527. // MARK: - ScrollView
  528. extension NCMedia: UIScrollViewDelegate {
  529. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  530. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth / 2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth / 2 >= scrollView.contentOffset.y {
  531. mediaCommandTitle()
  532. lastContentOffsetY = scrollView.contentOffset.y
  533. }
  534. }
  535. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  536. mediaCommandView?.collapseControlButtonView(true)
  537. }
  538. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  539. if !decelerate {
  540. timerSearchNewMedia?.invalidate()
  541. timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false)
  542. if scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) {
  543. searchOldMedia()
  544. }
  545. }
  546. }
  547. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  548. timerSearchNewMedia?.invalidate()
  549. timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false)
  550. if scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) {
  551. searchOldMedia()
  552. }
  553. }
  554. func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
  555. let y = view.safeAreaInsets.top
  556. scrollView.contentOffset.y = -(insetsTop + y)
  557. }
  558. }
  559. // MARK: - Media Command View
  560. class NCMediaCommandView: UIView {
  561. @IBOutlet weak var moreView: UIVisualEffectView!
  562. @IBOutlet weak var gridSwitchButton: UIButton!
  563. @IBOutlet weak var separatorView: UIView!
  564. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  565. @IBOutlet weak var zoomInButton: UIButton!
  566. @IBOutlet weak var zoomOutButton: UIButton!
  567. @IBOutlet weak var moreButton: UIButton!
  568. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  569. @IBOutlet weak var title: UILabel!
  570. @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
  571. var mediaView: NCMedia?
  572. private let gradient: CAGradientLayer = CAGradientLayer()
  573. override func awakeFromNib() {
  574. moreView.layer.cornerRadius = 20
  575. moreView.layer.masksToBounds = true
  576. controlButtonView.layer.cornerRadius = 20
  577. controlButtonView.layer.masksToBounds = true
  578. controlButtonView.effect = UIBlurEffect(style: .dark)
  579. gradient.frame = bounds
  580. gradient.startPoint = CGPoint(x: 0, y: 0.5)
  581. gradient.endPoint = CGPoint(x: 0, y: 1)
  582. gradient.colors = [UIColor.black.withAlphaComponent(UIAccessibility.isReduceTransparencyEnabled ? 0.8 : 0.4).cgColor, UIColor.clear.cgColor]
  583. layer.insertSublayer(gradient, at: 0)
  584. moreButton.setImage(UIImage(named: "more")!.image(color: .white, size: 25), for: .normal)
  585. title.text = ""
  586. }
  587. func toggleEmptyView(isEmpty: Bool) {
  588. if isEmpty {
  589. UIView.animate(withDuration: 0.3) {
  590. self.moreView.effect = UIBlurEffect(style: .dark)
  591. self.gradient.isHidden = true
  592. self.controlButtonView.isHidden = true
  593. }
  594. } else {
  595. UIView.animate(withDuration: 0.3) {
  596. self.moreView.effect = UIBlurEffect(style: .dark)
  597. self.gradient.isHidden = false
  598. self.controlButtonView.isHidden = false
  599. }
  600. }
  601. }
  602. @IBAction func moreButtonPressed(_ sender: UIButton) {
  603. mediaView?.openMenuButtonMore(sender)
  604. }
  605. @IBAction func zoomInPressed(_ sender: UIButton) {
  606. mediaView?.zoomInGrid()
  607. }
  608. @IBAction func zoomOutPressed(_ sender: UIButton) {
  609. mediaView?.zoomOutGrid()
  610. }
  611. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  612. self.collapseControlButtonView(false)
  613. }
  614. func collapseControlButtonView(_ collapse: Bool) {
  615. if collapse {
  616. self.buttonControlWidthConstraint.constant = 40
  617. UIView.animate(withDuration: 0.25) {
  618. self.zoomOutButton.isHidden = true
  619. self.zoomInButton.isHidden = true
  620. self.separatorView.isHidden = true
  621. self.gridSwitchButton.isHidden = false
  622. self.layoutIfNeeded()
  623. }
  624. } else {
  625. self.buttonControlWidthConstraint.constant = 80
  626. UIView.animate(withDuration: 0.25) {
  627. self.zoomOutButton.isHidden = false
  628. self.zoomInButton.isHidden = false
  629. self.separatorView.isHidden = false
  630. self.gridSwitchButton.isHidden = true
  631. self.layoutIfNeeded()
  632. }
  633. }
  634. }
  635. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  636. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  637. }
  638. override func layoutSublayers(of layer: CALayer) {
  639. super.layoutSublayers(of: layer)
  640. gradient.frame = bounds
  641. }
  642. }
  643. // MARK: - Media Grid Layout
  644. class NCGridMediaLayout: UICollectionViewFlowLayout {
  645. var marginLeftRight: CGFloat = 2
  646. var itemForLine: CGFloat = 3
  647. override init() {
  648. super.init()
  649. sectionHeadersPinToVisibleBounds = false
  650. minimumInteritemSpacing = 0
  651. minimumLineSpacing = marginLeftRight
  652. self.scrollDirection = .vertical
  653. self.sectionInset = UIEdgeInsets(top: 0, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  654. }
  655. required init?(coder aDecoder: NSCoder) {
  656. fatalError("init(coder:) has not been implemented")
  657. }
  658. override var itemSize: CGSize {
  659. get {
  660. if let collectionView = collectionView {
  661. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  662. let itemHeight: CGFloat = itemWidth
  663. return CGSize(width: itemWidth, height: itemHeight)
  664. }
  665. // Default fallback
  666. return CGSize(width: 100, height: 100)
  667. }
  668. set {
  669. super.itemSize = newValue
  670. }
  671. }
  672. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  673. return proposedContentOffset
  674. }
  675. }