NCMedia.swift 35 KB

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