NCMedia.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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(NCKeychain().mediaWidthImage, 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. NCKeychain().mediaWidthImage = 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. NCKeychain().mediaWidthImage = 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 home = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  206. let path = serverUrl.replacingOccurrences(of: home, with: "")
  207. NCManageDatabase.shared.setAccountMediaPath(path, account: appDelegate.account)
  208. reloadDataSourceWithCompletion { _ in
  209. self.searchNewMedia()
  210. }
  211. }
  212. // MARK: - Empty
  213. func emptyDataSetView(_ view: NCEmptyView) {
  214. view.emptyImage.image = UIImage(named: "media")?.image(color: .gray, size: UIScreen.main.bounds.width)
  215. if oldInProgress || newInProgress {
  216. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  217. } else {
  218. view.emptyTitle.text = NSLocalizedString("_tutorial_photo_view_", comment: "")
  219. }
  220. view.emptyDescription.text = ""
  221. }
  222. }
  223. // MARK: - Collection View
  224. extension NCMedia: UICollectionViewDelegate {
  225. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  226. let metadata = NCMediaCache.shared.metadatas[indexPath.row]
  227. if isEditMode {
  228. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  229. selectOcId.remove(at: index)
  230. selectIndexPath.removeAll(where: { $0 == indexPath })
  231. } else {
  232. selectOcId.append(metadata.ocId)
  233. selectIndexPath.append(indexPath)
  234. }
  235. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  236. collectionView.reloadItems(at: [indexPath])
  237. }
  238. } else {
  239. // ACTIVE SERVERURL
  240. appDelegate.activeServerUrl = metadata.serverUrl
  241. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridMediaCell
  242. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: NCMediaCache.shared.metadatas, imageIcon: cell?.imageItem.image)
  243. }
  244. }
  245. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  246. guard let cell = collectionView.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  247. let metadata = NCMediaCache.shared.metadatas[indexPath.row]
  248. let identifier = indexPath as NSCopying
  249. let image = cell.imageItem.image
  250. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  251. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  252. }, actionProvider: { _ in
  253. return NCContextMenu().viewMenu(ocId: metadata.ocId, indexPath: indexPath, viewController: self, image: image)
  254. })
  255. }
  256. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  257. animator.addCompletion {
  258. if let indexPath = configuration.identifier as? IndexPath {
  259. self.collectionView(collectionView, didSelectItemAt: indexPath)
  260. }
  261. }
  262. }
  263. }
  264. extension NCMedia: UICollectionViewDataSourcePrefetching {
  265. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  266. // print("[LOG] n. " + String(indexPaths.count))
  267. }
  268. }
  269. extension NCMedia: UICollectionViewDataSource {
  270. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  271. CATransaction.begin()
  272. CATransaction.setCompletionBlock(closure)
  273. collectionView?.reloadData()
  274. CATransaction.commit()
  275. }
  276. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  277. emptyDataSet?.numberOfItemsInSection(NCMediaCache.shared.metadatas.count, section: section)
  278. return NCMediaCache.shared.metadatas.count
  279. }
  280. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  281. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < NCMediaCache.shared.metadatas.count {
  282. let metadata = NCMediaCache.shared.metadatas[indexPath.row]
  283. for case let operation as NCMediaDownloadThumbnaill in appDelegate.downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId {
  284. operation.cancel()
  285. }
  286. }
  287. }
  288. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  289. guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridMediaCell else { return UICollectionViewCell() }
  290. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) && indexPath.row < NCMediaCache.shared.metadatas.count {
  291. let metadata = NCMediaCache.shared.metadatas[indexPath.row]
  292. self.cellHeigth = cell.frame.size.height
  293. cell.date = metadata.date as Date
  294. cell.fileObjectId = metadata.ocId
  295. cell.indexPath = indexPath
  296. cell.fileUser = metadata.ownerId
  297. if let image = NCMediaCache.shared.getImage(ocId: metadata.ocId) {
  298. cell.imageItem.backgroundColor = nil
  299. cell.imageItem.image = image
  300. } else if FileManager().fileExists(atPath: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  301. if let image = UIImage(contentsOfFile: NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  302. cell.imageItem.backgroundColor = nil
  303. cell.imageItem.image = image
  304. NCMediaCache.shared.setImage(ocId: metadata.ocId, image: image)
  305. }
  306. } else {
  307. if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!NCUtilityFileSystem.shared.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) {
  308. if appDelegate.downloadThumbnailQueue.operations.filter({ ($0 as? NCMediaDownloadThumbnaill)?.metadata.ocId == metadata.ocId }).isEmpty {
  309. appDelegate.downloadThumbnailQueue.addOperation(NCMediaDownloadThumbnaill(metadata: metadata, cell: cell, collectionView: collectionView))
  310. }
  311. }
  312. }
  313. if metadata.isAudioOrVideo {
  314. cell.imageStatus.image = cacheImages.cellPlayImage
  315. } else if metadata.livePhoto && NCMediaCache.shared.livePhoto {
  316. cell.imageStatus.image = cacheImages.cellLivePhotoImage
  317. }
  318. if isEditMode {
  319. cell.selectMode(true)
  320. if selectOcId.contains(metadata.ocId) {
  321. cell.selected(true)
  322. } else {
  323. cell.selected(false)
  324. }
  325. } else {
  326. cell.selectMode(false)
  327. }
  328. return cell
  329. } else {
  330. return cell
  331. }
  332. }
  333. }
  334. extension NCMedia: UICollectionViewDelegateFlowLayout {
  335. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  336. return CGSize(width: collectionView.frame.width, height: 0)
  337. }
  338. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  339. return CGSize(width: collectionView.frame.width, height: 0)
  340. }
  341. }
  342. extension NCMedia {
  343. @objc func reloadDataSourceWithCompletion(_ completion: @escaping (_ metadatas: [tableMetadata]) -> Void) {
  344. guard !appDelegate.account.isEmpty else { return }
  345. DispatchQueue.global().async {
  346. NCMediaCache.shared.getMetadatasMedia(account: self.appDelegate.account, filterClassTypeImage: self.filterClassTypeImage, filterClassTypeVideo: self.filterClassTypeVideo)
  347. DispatchQueue.main.sync {
  348. self.reloadDataThenPerform {
  349. self.updateMediaControlVisibility()
  350. self.mediaCommandTitle()
  351. completion(NCMediaCache.shared.metadatas)
  352. }
  353. }
  354. }
  355. }
  356. func updateMediaControlVisibility() {
  357. if NCMediaCache.shared.metadatas.isEmpty {
  358. if !self.filterClassTypeImage && !self.filterClassTypeVideo {
  359. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  360. self.mediaCommandView?.isHidden = false
  361. } else {
  362. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  363. self.mediaCommandView?.isHidden = false
  364. }
  365. } else {
  366. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  367. self.mediaCommandView?.isHidden = false
  368. }
  369. }
  370. // MARK: - Search media
  371. private func searchOldMedia(value: Int = -30, limit: Int = 300) {
  372. if oldInProgress { return } else { oldInProgress = true }
  373. DispatchQueue.main.async {
  374. self.collectionView.reloadData()
  375. var bottom: CGFloat = 0
  376. if let mainTabBar = self.tabBarController?.tabBar as? NCMainTabBar {
  377. bottom = -mainTabBar.getHeight()
  378. }
  379. NCActivityIndicator.shared.start(backgroundView: self.view, bottom: bottom - 5, style: .medium)
  380. }
  381. var lessDate = Date()
  382. if let predicate = NCMediaCache.shared.predicateDefault, let metadata = NCManageDatabase.shared.getMetadata(predicate: predicate, sorted: "date", ascending: true) {
  383. lessDate = metadata.date as Date
  384. }
  385. var greaterDate: Date
  386. if value == -999 {
  387. greaterDate = Date.distantPast
  388. } else {
  389. greaterDate = Calendar.current.date(byAdding: .day, value: value, to: lessDate)!
  390. }
  391. let options = NKRequestOptions(timeout: 300, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  392. NextcloudKit.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: NCKeychain().showHiddenFiles, options: options) { account, files, _, error in
  393. self.oldInProgress = false
  394. DispatchQueue.main.async {
  395. NCActivityIndicator.shared.stop()
  396. self.collectionView.reloadData()
  397. }
  398. if error == .success && account == self.appDelegate.account {
  399. if !files.isEmpty {
  400. NCManageDatabase.shared.convertFilesToMetadatas(files, useMetadataFolder: false) { _, _, metadatas in
  401. let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  402. let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateDate, NCMediaCache.shared.predicateDefault!])
  403. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult)
  404. let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  405. if metadatasChanged.metadatasUpdate.isEmpty {
  406. self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: true)
  407. } else {
  408. self.reloadDataSourceWithCompletion { _ in }
  409. }
  410. }
  411. } else {
  412. self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: false)
  413. }
  414. } else if error != .success {
  415. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Media search old media error code \(error.errorCode) " + error.errorDescription)
  416. }
  417. }
  418. }
  419. private func researchOldMedia(value: Int, limit: Int, withElseReloadDataSource: Bool) {
  420. if value == -30 {
  421. searchOldMedia(value: -90)
  422. } else if value == -90 {
  423. searchOldMedia(value: -180)
  424. } else if value == -180 {
  425. searchOldMedia(value: -999)
  426. } else if value == -999 && limit > 0 {
  427. searchOldMedia(value: -999, limit: 0)
  428. } else {
  429. if withElseReloadDataSource {
  430. self.reloadDataSourceWithCompletion { _ in }
  431. }
  432. }
  433. }
  434. @objc func searchNewMediaTimer() {
  435. self.searchNewMedia()
  436. }
  437. @objc func searchNewMedia() {
  438. if newInProgress { return } else {
  439. newInProgress = true
  440. mediaCommandView?.activityIndicator.startAnimating()
  441. }
  442. var limit: Int = 1000
  443. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  444. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  445. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  446. if let cell = visibleCells.first as? NCGridMediaCell {
  447. if cell.date != nil {
  448. if cell.date != NCMediaCache.shared.metadatas.first?.date as Date? {
  449. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  450. limit = 0
  451. }
  452. }
  453. }
  454. if let cell = visibleCells.last as? NCGridMediaCell {
  455. if cell.date != nil {
  456. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  457. }
  458. }
  459. }
  460. reloadDataThenPerform {
  461. let options = NKRequestOptions(timeout: 300, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  462. NextcloudKit.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: NCKeychain().showHiddenFiles, options: options) { account, files, _, error in
  463. self.newInProgress = false
  464. DispatchQueue.main.async {
  465. self.mediaCommandView?.activityIndicator.stopAnimating()
  466. }
  467. if error == .success, account == self.appDelegate.account, !files.isEmpty {
  468. NCManageDatabase.shared.convertFilesToMetadatas(files, useMetadataFolder: false) { _, _, metadatas in
  469. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  470. let predicateResult = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, NCMediaCache.shared.predicate!])
  471. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult)
  472. let updateMetadatas = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  473. if !updateMetadatas.metadatasUpdate.isEmpty || !updateMetadatas.metadatasDelete.isEmpty {
  474. self.reloadDataSourceWithCompletion { _ in }
  475. }
  476. }
  477. } else if error == .success, files.isEmpty, NCMediaCache.shared.metadatas.isEmpty {
  478. self.searchOldMedia()
  479. } else if error != .success {
  480. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Media search new media error code \(error.errorCode) " + error.errorDescription)
  481. }
  482. }
  483. }
  484. }
  485. }
  486. // MARK: - ScrollView
  487. extension NCMedia: UIScrollViewDelegate {
  488. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  489. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth / 2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth / 2 >= scrollView.contentOffset.y {
  490. mediaCommandTitle()
  491. lastContentOffsetY = scrollView.contentOffset.y
  492. }
  493. }
  494. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  495. mediaCommandView?.collapseControlButtonView(true)
  496. }
  497. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  498. if !decelerate {
  499. timerSearchNewMedia?.invalidate()
  500. timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false)
  501. if scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) {
  502. searchOldMedia()
  503. }
  504. }
  505. }
  506. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  507. timerSearchNewMedia?.invalidate()
  508. timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false)
  509. if scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height) {
  510. searchOldMedia()
  511. }
  512. }
  513. func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
  514. let y = view.safeAreaInsets.top
  515. scrollView.contentOffset.y = -(insetsTop + y)
  516. }
  517. }
  518. // MARK: - Media Command View
  519. class NCMediaCommandView: UIView {
  520. @IBOutlet weak var moreView: UIVisualEffectView!
  521. @IBOutlet weak var gridSwitchButton: UIButton!
  522. @IBOutlet weak var separatorView: UIView!
  523. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  524. @IBOutlet weak var zoomInButton: UIButton!
  525. @IBOutlet weak var zoomOutButton: UIButton!
  526. @IBOutlet weak var moreButton: UIButton!
  527. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  528. @IBOutlet weak var title: UILabel!
  529. @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
  530. var mediaView: NCMedia?
  531. private let gradient: CAGradientLayer = CAGradientLayer()
  532. override func awakeFromNib() {
  533. moreView.layer.cornerRadius = 20
  534. moreView.layer.masksToBounds = true
  535. controlButtonView.layer.cornerRadius = 20
  536. controlButtonView.layer.masksToBounds = true
  537. controlButtonView.effect = UIBlurEffect(style: .dark)
  538. gradient.frame = bounds
  539. gradient.startPoint = CGPoint(x: 0, y: 0.5)
  540. gradient.endPoint = CGPoint(x: 0, y: 1)
  541. gradient.colors = [UIColor.black.withAlphaComponent(UIAccessibility.isReduceTransparencyEnabled ? 0.8 : 0.4).cgColor, UIColor.clear.cgColor]
  542. layer.insertSublayer(gradient, at: 0)
  543. moreButton.setImage(UIImage(named: "more")!.image(color: .white, size: 25), for: .normal)
  544. title.text = ""
  545. }
  546. func toggleEmptyView(isEmpty: Bool) {
  547. if isEmpty {
  548. UIView.animate(withDuration: 0.3) {
  549. self.moreView.effect = UIBlurEffect(style: .dark)
  550. self.gradient.isHidden = true
  551. self.controlButtonView.isHidden = true
  552. }
  553. } else {
  554. UIView.animate(withDuration: 0.3) {
  555. self.moreView.effect = UIBlurEffect(style: .dark)
  556. self.gradient.isHidden = false
  557. self.controlButtonView.isHidden = false
  558. }
  559. }
  560. }
  561. @IBAction func moreButtonPressed(_ sender: UIButton) {
  562. mediaView?.openMenuButtonMore(sender)
  563. }
  564. @IBAction func zoomInPressed(_ sender: UIButton) {
  565. mediaView?.zoomInGrid()
  566. }
  567. @IBAction func zoomOutPressed(_ sender: UIButton) {
  568. mediaView?.zoomOutGrid()
  569. }
  570. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  571. self.collapseControlButtonView(false)
  572. }
  573. func collapseControlButtonView(_ collapse: Bool) {
  574. if collapse {
  575. self.buttonControlWidthConstraint.constant = 40
  576. UIView.animate(withDuration: 0.25) {
  577. self.zoomOutButton.isHidden = true
  578. self.zoomInButton.isHidden = true
  579. self.separatorView.isHidden = true
  580. self.gridSwitchButton.isHidden = false
  581. self.layoutIfNeeded()
  582. }
  583. } else {
  584. self.buttonControlWidthConstraint.constant = 80
  585. UIView.animate(withDuration: 0.25) {
  586. self.zoomOutButton.isHidden = false
  587. self.zoomInButton.isHidden = false
  588. self.separatorView.isHidden = false
  589. self.gridSwitchButton.isHidden = true
  590. self.layoutIfNeeded()
  591. }
  592. }
  593. }
  594. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  595. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  596. }
  597. override func layoutSublayers(of layer: CALayer) {
  598. super.layoutSublayers(of: layer)
  599. gradient.frame = bounds
  600. }
  601. }
  602. // MARK: - Media Grid Layout
  603. class NCGridMediaLayout: UICollectionViewFlowLayout {
  604. var marginLeftRight: CGFloat = 2
  605. var itemForLine: CGFloat = 3
  606. override init() {
  607. super.init()
  608. sectionHeadersPinToVisibleBounds = false
  609. minimumInteritemSpacing = 0
  610. minimumLineSpacing = marginLeftRight
  611. self.scrollDirection = .vertical
  612. self.sectionInset = UIEdgeInsets(top: 0, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  613. }
  614. required init?(coder aDecoder: NSCoder) {
  615. fatalError("init(coder:) has not been implemented")
  616. }
  617. override var itemSize: CGSize {
  618. get {
  619. if let collectionView = collectionView {
  620. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  621. let itemHeight: CGFloat = itemWidth
  622. return CGSize(width: itemWidth, height: itemHeight)
  623. }
  624. // Default fallback
  625. return CGSize(width: 100, height: 100)
  626. }
  627. set {
  628. super.itemSize = newValue
  629. }
  630. }
  631. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  632. return proposedContentOffset
  633. }
  634. }
  635. // MARK: -
  636. class NCMediaDownloadThumbnaill: ConcurrentOperation {
  637. var metadata: tableMetadata
  638. var cell: NCCellProtocol?
  639. var collectionView: UICollectionView?
  640. var fileNamePath: String
  641. var fileNamePreviewLocalPath: String
  642. var fileNameIconLocalPath: String
  643. init(metadata: tableMetadata, cell: NCCellProtocol?, collectionView: UICollectionView?) {
  644. self.metadata = tableMetadata.init(value: metadata)
  645. self.cell = cell
  646. self.collectionView = collectionView
  647. self.fileNamePath = NCUtilityFileSystem.shared.getFileNamePath(metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId)
  648. self.fileNamePreviewLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStoragePreviewOcId(metadata.ocId, etag: metadata.etag)
  649. self.fileNameIconLocalPath = NCUtilityFileSystem.shared.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)
  650. }
  651. override func start() {
  652. guard !isCancelled else { return self.finish() }
  653. var etagResource: String?
  654. if FileManager.default.fileExists(atPath: fileNameIconLocalPath) && FileManager.default.fileExists(atPath: fileNamePreviewLocalPath) {
  655. etagResource = metadata.etagResource
  656. }
  657. NextcloudKit.shared.downloadPreview(fileNamePathOrFileId: fileNamePath,
  658. fileNamePreviewLocalPath: fileNamePreviewLocalPath,
  659. widthPreview: NCGlobal.shared.sizePreview,
  660. heightPreview: NCGlobal.shared.sizePreview,
  661. fileNameIconLocalPath: fileNameIconLocalPath,
  662. sizeIcon: NCGlobal.shared.sizeIcon,
  663. etag: etagResource,
  664. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, imagePreview, _, _, etag, error in
  665. if error == .success, let image = imagePreview {
  666. NCManageDatabase.shared.setMetadataEtagResource(ocId: self.metadata.ocId, etagResource: etag)
  667. DispatchQueue.main.async {
  668. if self.metadata.ocId == self.cell?.fileObjectId, let filePreviewImageView = self.cell?.filePreviewImageView {
  669. UIView.transition(with: filePreviewImageView,
  670. duration: 0.75,
  671. options: .transitionCrossDissolve,
  672. animations: { filePreviewImageView.image = image },
  673. completion: nil)
  674. } else {
  675. self.collectionView?.reloadData()
  676. }
  677. }
  678. NCMediaCache.shared.setImage(ocId: self.metadata.ocId, image: image)
  679. }
  680. self.finish()
  681. }
  682. }
  683. }