NCMedia.swift 37 KB

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