NCMedia.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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. return NCFunctionCenter.shared.contextMenuConfiguration(metadata: metadata, viewController: self, enableDeleteLocal: false, enableViewInFolder: true)
  266. })
  267. }
  268. @available(iOS 13.0, *)
  269. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  270. animator.addCompletion {
  271. if let indexPath = configuration.identifier as? IndexPath {
  272. self.collectionView(collectionView, didSelectItemAt: indexPath)
  273. }
  274. }
  275. }
  276. }
  277. extension NCMedia: UICollectionViewDataSourcePrefetching {
  278. func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
  279. //print("[LOG] n. " + String(indexPaths.count))
  280. }
  281. }
  282. extension NCMedia: UICollectionViewDataSource {
  283. func reloadDataThenPerform(_ closure: @escaping (() -> Void)) {
  284. CATransaction.begin()
  285. CATransaction.setCompletionBlock(closure)
  286. collectionView?.reloadData()
  287. CATransaction.commit()
  288. }
  289. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  290. emptyDataSet?.numberOfItemsInSection(metadatas.count, section: section)
  291. return metadatas.count
  292. }
  293. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  294. if indexPath.row < self.metadatas.count {
  295. let metadata = self.metadatas[indexPath.row]
  296. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  297. }
  298. }
  299. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  300. if !collectionView.indexPathsForVisibleItems.contains(indexPath) && indexPath.row < metadatas.count {
  301. let metadata = metadatas[indexPath.row]
  302. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  303. }
  304. }
  305. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  306. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) && indexPath.row < metadatas.count {
  307. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  308. let metadata = metadatas[indexPath.row]
  309. self.cellHeigth = cell.frame.size.height
  310. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  311. cell.imageItem.backgroundColor = nil
  312. cell.imageItem.image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  313. } else if(!metadata.hasPreview) {
  314. cell.imageItem.backgroundColor = nil
  315. if metadata.iconName.count > 0 {
  316. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  317. } else {
  318. cell.imageItem.image = NCBrandColor.cacheImages.file
  319. }
  320. }
  321. cell.date = metadata.date as Date
  322. if metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  323. cell.imageStatus.image = cacheImages.cellPlayImage
  324. } else if metadata.livePhoto && livePhoto {
  325. cell.imageStatus.image = cacheImages.cellLivePhotoImage
  326. }
  327. if isEditMode {
  328. cell.selectMode(true)
  329. if selectOcId.contains(metadata.ocId) {
  330. cell.selected(true)
  331. } else {
  332. cell.selected(false)
  333. }
  334. } else {
  335. cell.selectMode(false)
  336. }
  337. return cell
  338. } else {
  339. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  340. }
  341. }
  342. }
  343. extension NCMedia: UICollectionViewDelegateFlowLayout {
  344. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  345. return CGSize(width: collectionView.frame.width, height: 0)
  346. }
  347. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  348. return CGSize(width: collectionView.frame.width, height: 0)
  349. }
  350. }
  351. extension NCMedia {
  352. // MARK: - Datasource
  353. @objc func reloadDataSource() {
  354. self.reloadDataSourceWithCompletion { (_) in }
  355. }
  356. @objc func reloadDataSourceWithCompletion(_ completion: @escaping (_ metadatas: [tableMetadata]) -> Void) {
  357. if appDelegate.account == "" { return }
  358. if account != appDelegate.account {
  359. self.metadatas = []
  360. account = appDelegate.account
  361. collectionView?.reloadData()
  362. }
  363. livePhoto = CCUtility.getLivePhoto()
  364. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  365. self.mediaPath = activeAccount.mediaPath
  366. }
  367. let startServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) + mediaPath
  368. 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)
  369. if filterTypeFileImage {
  370. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NCGlobal.shared.metadataTypeFileVideo)
  371. } else if filterTypeFileVideo {
  372. predicate = NSPredicate(format: "account == %@ AND serverUrl BEGINSWITH %@ AND typeFile == %@ AND NOT (session CONTAINS[c] 'upload')", appDelegate.account, startServerUrl, NCGlobal.shared.metadataTypeFileImage)
  373. } else {
  374. predicate = predicateDefault
  375. }
  376. guard var predicateForGetMetadatasMedia = predicate else { return }
  377. if livePhoto {
  378. let predicateLivePhoto = NSPredicate(format: "!(ext == 'mov' AND livePhoto == true)")
  379. predicateForGetMetadatasMedia = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateForGetMetadatasMedia, predicateLivePhoto])
  380. }
  381. DispatchQueue.global().async {
  382. self.metadatas = NCManageDatabase.shared.getMetadatasMedia(predicate: predicateForGetMetadatasMedia, sort: CCUtility.getMediaSortDate())
  383. DispatchQueue.main.sync {
  384. self.reloadDataThenPerform {
  385. self.updateMediaControlVisibility()
  386. self.mediaCommandTitle()
  387. completion(self.metadatas)
  388. }
  389. }
  390. }
  391. }
  392. func updateMediaControlVisibility() {
  393. if self.metadatas.count == 0 {
  394. if !self.filterTypeFileImage && !self.filterTypeFileVideo {
  395. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  396. self.mediaCommandView?.isHidden = false
  397. } else {
  398. self.mediaCommandView?.toggleEmptyView(isEmpty: true)
  399. self.mediaCommandView?.isHidden = false
  400. }
  401. } else {
  402. self.mediaCommandView?.toggleEmptyView(isEmpty: false)
  403. self.mediaCommandView?.isHidden = false
  404. }
  405. }
  406. // MARK: - Search media
  407. private func searchOldMedia(value: Int = -30, limit: Int = 300) {
  408. if oldInProgress { return }
  409. else { oldInProgress = true }
  410. collectionView.reloadData()
  411. var lessDate = Date()
  412. if predicateDefault != nil {
  413. if let metadata = NCManageDatabase.shared.getMetadata(predicate: predicateDefault!, sorted: "date", ascending: true) {
  414. lessDate = metadata.date as Date
  415. }
  416. }
  417. var greaterDate: Date
  418. if value == -999 {
  419. greaterDate = Date.distantPast
  420. } else {
  421. greaterDate = Calendar.current.date(byAdding: .day, value:value, to: lessDate)!
  422. }
  423. let height = self.tabBarController?.tabBar.frame.size.height ?? 0
  424. NCUtility.shared.startActivityIndicator(backgroundView: self.view, blurEffect: false, bottom: height + 50, style: .gray)
  425. NCCommunication.shared.searchMedia(path: mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), timeout: 120) { (account, files, errorCode, errorDescription) in
  426. self.oldInProgress = false
  427. NCUtility.shared.stopActivityIndicator()
  428. self.collectionView.reloadData()
  429. if errorCode == 0 && account == self.appDelegate.account {
  430. if files.count > 0 {
  431. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: self.appDelegate.account) { (_, _, metadatas) in
  432. let predicateDate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  433. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicateDate, self.predicateDefault!])
  434. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult)
  435. let metadatasChanged = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  436. if metadatasChanged.metadatasUpdate.count == 0 {
  437. self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: true)
  438. } else {
  439. self.reloadDataSource()
  440. }
  441. }
  442. } else {
  443. self.researchOldMedia(value: value, limit: limit, withElseReloadDataSource: false)
  444. }
  445. } else if errorCode != 0 {
  446. NCCommunicationCommon.shared.writeLog("Media search old media error code \(errorCode) " + errorDescription)
  447. }
  448. }
  449. }
  450. private func researchOldMedia(value: Int , limit: Int, withElseReloadDataSource: Bool) {
  451. if value == -30 {
  452. searchOldMedia(value: -90)
  453. } else if value == -90 {
  454. searchOldMedia(value: -180)
  455. } else if value == -180 {
  456. searchOldMedia(value: -999)
  457. } else if value == -999 && limit > 0 {
  458. searchOldMedia(value: -999, limit: 0)
  459. } else {
  460. if withElseReloadDataSource {
  461. reloadDataSource()
  462. }
  463. }
  464. }
  465. @objc func searchNewMediaTimer() {
  466. self.searchNewMedia()
  467. }
  468. @objc func searchNewMedia() {
  469. if newInProgress { return }
  470. else {
  471. newInProgress = true
  472. mediaCommandView?.activityIndicator.startAnimating()
  473. }
  474. var limit: Int = 1000
  475. guard var lessDate = Calendar.current.date(byAdding: .second, value: 1, to: Date()) else { return }
  476. guard var greaterDate = Calendar.current.date(byAdding: .day, value: -30, to: Date()) else { return }
  477. if let visibleCells = self.collectionView?.indexPathsForVisibleItems.sorted(by: { $0.row < $1.row }).compactMap({ self.collectionView?.cellForItem(at: $0) }) {
  478. if let cell = visibleCells.first as? NCGridMediaCell {
  479. if cell.date != nil {
  480. if cell.date != self.metadatas.first?.date as Date? {
  481. lessDate = Calendar.current.date(byAdding: .second, value: 1, to: cell.date!)!
  482. limit = 0
  483. }
  484. }
  485. }
  486. if let cell = visibleCells.last as? NCGridMediaCell {
  487. if cell.date != nil {
  488. greaterDate = Calendar.current.date(byAdding: .second, value: -1, to: cell.date!)!
  489. }
  490. }
  491. }
  492. reloadDataThenPerform {
  493. NCCommunication.shared.searchMedia(path: self.mediaPath, lessDate: lessDate, greaterDate: greaterDate, elementDate: "d:getlastmodified/", limit: limit, showHiddenFiles: CCUtility.getShowHiddenFiles(), timeout: 120) { (account, files, errorCode, errorDescription) in
  494. self.newInProgress = false
  495. self.mediaCommandView?.activityIndicator.stopAnimating()
  496. if errorCode == 0 && account == self.appDelegate.account && files.count > 0 {
  497. NCManageDatabase.shared.convertNCCommunicationFilesToMetadatas(files, useMetadataFolder: false, account: account) { (_, _, metadatas) in
  498. let predicate = NSPredicate(format: "date > %@ AND date < %@", greaterDate as NSDate, lessDate as NSDate)
  499. let predicateResult = NSCompoundPredicate.init(andPredicateWithSubpredicates:[predicate, self.predicate!])
  500. let metadatasResult = NCManageDatabase.shared.getMetadatas(predicate: predicateResult)
  501. let updateMetadatas = NCManageDatabase.shared.updateMetadatas(metadatas, metadatasResult: metadatasResult, addCompareLivePhoto: false)
  502. if updateMetadatas.metadatasUpdate.count > 0 {
  503. self.reloadDataSource()
  504. }
  505. }
  506. } else if errorCode == 0 && files.count == 0 && self.metadatas.count == 0 {
  507. self.searchOldMedia()
  508. } else if errorCode != 0 {
  509. NCCommunicationCommon.shared.writeLog("Media search new media error code \(errorCode) " + errorDescription)
  510. }
  511. }
  512. }
  513. }
  514. private func downloadThumbnail() {
  515. guard let collectionView = self.collectionView else { return }
  516. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  517. for indexPath in collectionView.indexPathsForVisibleItems {
  518. let metadata = self.metadatas[indexPath.row]
  519. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: self.appDelegate.urlBase, view: self.collectionView as Any, indexPath: indexPath)
  520. }
  521. }
  522. }
  523. }
  524. // MARK: - ScrollView
  525. extension NCMedia: UIScrollViewDelegate {
  526. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  527. if lastContentOffsetY == 0 || lastContentOffsetY + cellHeigth/2 <= scrollView.contentOffset.y || lastContentOffsetY - cellHeigth/2 >= scrollView.contentOffset.y {
  528. mediaCommandTitle()
  529. lastContentOffsetY = scrollView.contentOffset.y
  530. }
  531. }
  532. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  533. mediaCommandView?.collapseControlButtonView(true)
  534. }
  535. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  536. if !decelerate {
  537. timerSearchNewMedia?.invalidate()
  538. timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false)
  539. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  540. searchOldMedia()
  541. }
  542. }
  543. }
  544. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  545. timerSearchNewMedia?.invalidate()
  546. timerSearchNewMedia = Timer.scheduledTimer(timeInterval: timeIntervalSearchNewMedia, target: self, selector: #selector(searchNewMediaTimer), userInfo: nil, repeats: false)
  547. if (scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
  548. searchOldMedia()
  549. }
  550. }
  551. }
  552. // MARK: - Media Command View
  553. class NCMediaCommandView: UIView {
  554. @IBOutlet weak var moreView: UIVisualEffectView!
  555. @IBOutlet weak var gridSwitchButton: UIButton!
  556. @IBOutlet weak var separatorView: UIView!
  557. @IBOutlet weak var buttonControlWidthConstraint: NSLayoutConstraint!
  558. @IBOutlet weak var zoomInButton: UIButton!
  559. @IBOutlet weak var zoomOutButton: UIButton!
  560. @IBOutlet weak var moreButton: UIButton!
  561. @IBOutlet weak var controlButtonView: UIVisualEffectView!
  562. @IBOutlet weak var title : UILabel!
  563. @IBOutlet weak var activityIndicator : UIActivityIndicatorView!
  564. var mediaView:NCMedia?
  565. private let gradient: CAGradientLayer = CAGradientLayer()
  566. override func awakeFromNib() {
  567. moreView.layer.cornerRadius = 20
  568. moreView.layer.masksToBounds = true
  569. controlButtonView.layer.cornerRadius = 20
  570. controlButtonView.layer.masksToBounds = true
  571. gradient.frame = bounds
  572. gradient.startPoint = CGPoint(x: 0, y: 0.50)
  573. gradient.endPoint = CGPoint(x: 0, y: 0.9)
  574. gradient.colors = [UIColor.black.withAlphaComponent(0.4).cgColor , UIColor.clear.cgColor]
  575. layer.insertSublayer(gradient, at: 0)
  576. moreButton.setImage(UIImage.init(named: "more")!.image(color: .white, size: 25), for: .normal)
  577. title.text = ""
  578. }
  579. func toggleEmptyView(isEmpty: Bool) {
  580. if isEmpty {
  581. UIView.animate(withDuration: 0.3) {
  582. self.moreView.effect = UIBlurEffect(style: .dark)
  583. self.gradient.isHidden = true
  584. self.controlButtonView.isHidden = true
  585. }
  586. } else {
  587. UIView.animate(withDuration: 0.3) {
  588. self.moreView.effect = UIBlurEffect(style: .regular)
  589. self.gradient.isHidden = false
  590. self.controlButtonView.isHidden = false
  591. }
  592. }
  593. }
  594. @IBAction func moreButtonPressed(_ sender: UIButton) {
  595. mediaView?.openMenuButtonMore(sender)
  596. }
  597. @IBAction func zoomInPressed(_ sender: UIButton) {
  598. mediaView?.zoomInGrid()
  599. }
  600. @IBAction func zoomOutPressed(_ sender: UIButton) {
  601. mediaView?.zoomOutGrid()
  602. }
  603. @IBAction func gridSwitchButtonPressed(_ sender: Any) {
  604. self.collapseControlButtonView(false)
  605. }
  606. func collapseControlButtonView(_ collapse: Bool) {
  607. if (collapse) {
  608. self.buttonControlWidthConstraint.constant = 40
  609. UIView.animate(withDuration: 0.25) {
  610. self.zoomOutButton.isHidden = true
  611. self.zoomInButton.isHidden = true
  612. self.separatorView.isHidden = true
  613. self.gridSwitchButton.isHidden = false
  614. self.layoutIfNeeded()
  615. }
  616. } else {
  617. self.buttonControlWidthConstraint.constant = 80
  618. UIView.animate(withDuration: 0.25) {
  619. self.zoomOutButton.isHidden = false
  620. self.zoomInButton.isHidden = false
  621. self.separatorView.isHidden = false
  622. self.gridSwitchButton.isHidden = true
  623. self.layoutIfNeeded()
  624. }
  625. }
  626. }
  627. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
  628. return moreView.frame.contains(point) || controlButtonView.frame.contains(point)
  629. }
  630. override func layoutSublayers(of layer: CALayer) {
  631. super.layoutSublayers(of: layer)
  632. gradient.frame = bounds
  633. }
  634. }
  635. // MARK: - Media Grid Layout
  636. class NCGridMediaLayout: UICollectionViewFlowLayout {
  637. var marginLeftRight: CGFloat = 6
  638. var itemForLine: CGFloat = 3
  639. override init() {
  640. super.init()
  641. sectionHeadersPinToVisibleBounds = false
  642. minimumInteritemSpacing = 0
  643. minimumLineSpacing = marginLeftRight
  644. self.scrollDirection = .vertical
  645. self.sectionInset = UIEdgeInsets(top: 0, left: marginLeftRight, bottom: 0, right: marginLeftRight)
  646. }
  647. required init?(coder aDecoder: NSCoder) {
  648. fatalError("init(coder:) has not been implemented")
  649. }
  650. override var itemSize: CGSize {
  651. get {
  652. if let collectionView = collectionView {
  653. let itemWidth: CGFloat = (collectionView.frame.width - marginLeftRight * 2 - marginLeftRight * (itemForLine - 1)) / itemForLine
  654. let itemHeight: CGFloat = itemWidth
  655. return CGSize(width: itemWidth, height: itemHeight)
  656. }
  657. // Default fallback
  658. return CGSize(width: 100, height: 100)
  659. }
  660. set {
  661. super.itemSize = newValue
  662. }
  663. }
  664. override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
  665. return proposedContentOffset
  666. }
  667. }