NCMedia.swift 35 KB

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