NCMedia.swift 35 KB

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