NCMedia.swift 35 KB

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