NCMedia.swift 34 KB

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