NCMedia.swift 37 KB

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