NCMedia.swift 36 KB

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