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