NCMedia.swift 34 KB

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