NCMedia.swift 38 KB

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