NCMedia.swift 34 KB

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