NCMedia.swift 35 KB

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