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