NCMedia.swift 34 KB

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