NCMedia.swift 35 KB

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