NCMedia.swift 36 KB

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