NCMedia.swift 36 KB

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