NCMedia.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. //
  2. // NCMedia.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/02/2019.
  6. // Copyright © 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. import Sheeeeeeeeet
  25. import FastScroll
  26. class NCMedia: UIViewController, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, NCSelectDelegate {
  27. @IBOutlet weak var collectionView : FastScrollCollectionView!
  28. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  29. var sectionDatasource = CCSectionDataSourceMetadata()
  30. private var metadataPush: tableMetadata?
  31. private var isEditMode = false
  32. private var selectocId = [String]()
  33. private var filterTypeFileImage = false;
  34. private var filterTypeFileVideo = false;
  35. private var autoUploadFileName = ""
  36. private var autoUploadDirectory = ""
  37. private var gridLayout: NCGridMediaLayout!
  38. private var actionSheet: ActionSheet?
  39. private let sectionHeaderHeight: CGFloat = 50
  40. private let footerHeight: CGFloat = 50
  41. private var stepImageWidth: CGFloat = 10
  42. private var isDistantPast = false
  43. private let refreshControl = UIRefreshControl()
  44. private var loadingSearch = false
  45. required init?(coder aDecoder: NSCoder) {
  46. super.init(coder: aDecoder)
  47. appDelegate.activeMedia = self
  48. }
  49. override func viewDidLoad() {
  50. super.viewDidLoad()
  51. self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: CCGraphics.changeThemingColorImage(UIImage(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.textView), style: .plain, target: self, action: #selector(touchUpInsideMenuButtonMore))
  52. self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: CCGraphics.changeThemingColorImage(UIImage(named: "grid"), width: 50, height: 50, color: NCBrandColor.sharedInstance.textView), style: .plain, target: self, action: #selector(touchUpInsideMenuButtonSwitch))
  53. // Cell
  54. collectionView.register(UINib.init(nibName: "NCGridMediaCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  55. // Header
  56. collectionView.register(UINib.init(nibName: "NCSectionMediaHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  57. // Footer
  58. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  59. collectionView.alwaysBounceVertical = true
  60. gridLayout = NCGridMediaLayout()
  61. gridLayout.preferenceWidth = CGFloat(CCUtility.getMediaWidthImage())
  62. gridLayout.sectionHeadersPinToVisibleBounds = true
  63. collectionView.collectionViewLayout = gridLayout
  64. // Add Refresh Control
  65. collectionView.refreshControl = refreshControl
  66. // empty Data Source
  67. collectionView.emptyDataSetDelegate = self
  68. collectionView.emptyDataSetSource = self
  69. // 3D Touch peek and pop
  70. if traitCollection.forceTouchCapability == .available {
  71. registerForPreviewing(with: self, sourceView: view)
  72. }
  73. // Notification
  74. NotificationCenter.default.addObserver(self, selector: #selector(self.deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  75. NotificationCenter.default.addObserver(self, selector: #selector(self.changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  76. NotificationCenter.default.addObserver(self, selector: #selector(self.moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  77. NotificationCenter.default.addObserver(self, selector: #selector(self.renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  78. // changeTheming
  79. changeTheming()
  80. }
  81. override func viewWillAppear(_ animated: Bool) {
  82. super.viewWillAppear(animated)
  83. // Configure Refresh Control
  84. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  85. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  86. refreshControl.addTarget(self, action: #selector(loadNetworkDatasource), for: .valueChanged)
  87. // get auto upload folder
  88. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  89. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(appDelegate.activeUrl)
  90. // Title
  91. self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  92. // Fast Scrool
  93. configFastScroll()
  94. // Reload Data Source
  95. self.reloadDataSource(loadNetworkDatasource: true) { }
  96. }
  97. override func viewDidAppear(_ animated: Bool) {
  98. super.viewDidAppear(animated)
  99. collectionView?.reloadDataThenPerform {
  100. self.selectSearchSections()
  101. }
  102. }
  103. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  104. super.viewWillTransition(to: size, with: coordinator)
  105. coordinator.animate(alongsideTransition: nil) { _ in
  106. self.collectionView?.reloadDataThenPerform {
  107. self.downloadThumbnail()
  108. }
  109. self.actionSheet?.viewDidLayoutSubviews()
  110. }
  111. }
  112. //MARK: - NotificationCenter
  113. @objc func changeTheming() {
  114. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  115. }
  116. @objc func deleteFile(_ notification: NSNotification) {
  117. if let userInfo = notification.userInfo as NSDictionary? {
  118. if let metadata = userInfo["metadata"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  119. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  120. self.reloadDataSource(loadNetworkDatasource: false) {
  121. let userInfo: [String : Any] = ["metadata": metadata, "type": "delete"]
  122. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  123. }
  124. }
  125. }
  126. }
  127. }
  128. @objc func moveFile(_ notification: NSNotification) {
  129. if let userInfo = notification.userInfo as NSDictionary? {
  130. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  131. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  132. self.reloadDataSource(loadNetworkDatasource: false) {
  133. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "move"]
  134. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  135. }
  136. }
  137. }
  138. }
  139. }
  140. @objc func renameFile(_ notification: NSNotification) {
  141. if let userInfo = notification.userInfo as NSDictionary? {
  142. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata, let errorCode = userInfo["errorCode"] as? Int {
  143. if errorCode == 0 && (metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio) {
  144. self.reloadDataSource(loadNetworkDatasource: false) {
  145. let userInfo: [String : Any] = ["metadata": metadata, "metadataNew": metadataNew, "type": "rename"]
  146. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  147. }
  148. }
  149. }
  150. }
  151. }
  152. // MARK: DZNEmpty
  153. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  154. return NCBrandColor.sharedInstance.backgroundView
  155. }
  156. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  157. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  158. }
  159. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  160. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  161. if loadingSearch {
  162. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  163. }
  164. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  165. return NSAttributedString.init(string: text, attributes: attributes)
  166. }
  167. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  168. return true
  169. }
  170. // MARK: IBAction
  171. @objc func touchUpInsideMenuButtonSwitch(_ sender: Any) {
  172. let itemSizeStart = self.gridLayout.itemSize
  173. UIView.animate(withDuration: 0.0, animations: {
  174. if self.gridLayout.numItems == 1 && self.stepImageWidth > 0 {
  175. self.stepImageWidth = -10
  176. } else if itemSizeStart.width < 50 {
  177. self.stepImageWidth = 10
  178. }
  179. repeat {
  180. self.gridLayout.preferenceWidth = self.gridLayout.preferenceWidth + self.stepImageWidth
  181. } while (self.gridLayout.itemSize == itemSizeStart)
  182. CCUtility.setMediaWidthImage(Int(self.gridLayout?.preferenceWidth ?? 80))
  183. self.collectionView.collectionViewLayout.invalidateLayout()
  184. if self.stepImageWidth < 0 {
  185. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  186. self.selectSearchSections()
  187. }
  188. }
  189. })
  190. }
  191. @objc func touchUpInsideMenuButtonMore(_ sender: Any) {
  192. var menu: DropdownMenu?
  193. if !isEditMode {
  194. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "selectFull"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_", comment: ""))
  195. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_media_folder_", comment: ""))
  196. var item2: DropdownItem
  197. if filterTypeFileImage {
  198. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageno"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_show_", comment: ""))
  199. } else {
  200. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_hide_", comment: ""))
  201. }
  202. var item3: DropdownItem
  203. if filterTypeFileVideo {
  204. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videono"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_show_", comment: ""))
  205. } else {
  206. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videoyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_hide_", comment: ""))
  207. }
  208. menu = DropdownMenu(navigationController: self.navigationController!, items: [item0,item1,item2,item3], selectedRow: -1)
  209. menu?.token = "menuButtonMore"
  210. } else {
  211. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "cancel"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_cancel_", comment: ""))
  212. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_delete_", comment: ""))
  213. menu = DropdownMenu(navigationController: self.navigationController!, items: [item0, item1], selectedRow: -1)
  214. menu?.token = "menuButtonMoreSelect"
  215. }
  216. menu?.delegate = self
  217. menu?.rowHeight = 45
  218. menu?.highlightColor = NCBrandColor.sharedInstance.brand
  219. menu?.tableView.alwaysBounceVertical = false
  220. menu?.tableViewSeperatorColor = NCBrandColor.sharedInstance.separator
  221. menu?.tableViewBackgroundColor = NCBrandColor.sharedInstance.backgroundForm
  222. menu?.cellBackgroundColor = NCBrandColor.sharedInstance.backgroundForm
  223. menu?.textColor = NCBrandColor.sharedInstance.textView
  224. menu?.showMenu()
  225. }
  226. // MARK: DROP-DOWN-MENU
  227. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  228. if dropdownMenu.token == "menuButtonMore" {
  229. switch indexPath.row {
  230. case 0:
  231. isEditMode = true
  232. case 1:
  233. selectStartDirectoryPhotosTab()
  234. case 2:
  235. filterTypeFileImage = !filterTypeFileImage
  236. reloadDataSource(loadNetworkDatasource: false) { }
  237. case 3:
  238. filterTypeFileVideo = !filterTypeFileVideo
  239. reloadDataSource(loadNetworkDatasource: false) { }
  240. default: ()
  241. }
  242. }
  243. if dropdownMenu.token == "menuButtonMoreSelect" {
  244. switch indexPath.row {
  245. case 0:
  246. isEditMode = false
  247. selectocId.removeAll()
  248. collectionView?.reloadDataThenPerform {
  249. self.downloadThumbnail()
  250. }
  251. case 1:
  252. deleteItems()
  253. default: ()
  254. }
  255. }
  256. }
  257. // MARK: Select Directory
  258. func selectStartDirectoryPhotosTab() {
  259. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  260. let viewController = navigationController.topViewController as! NCSelect
  261. viewController.delegate = self
  262. viewController.hideButtonCreateFolder = true
  263. viewController.includeDirectoryE2EEncryption = false
  264. viewController.includeImages = false
  265. viewController.layoutViewSelect = k_layout_view_move
  266. viewController.selectFile = false
  267. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  268. viewController.type = "mediaFolder"
  269. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  270. self.present(navigationController, animated: true, completion: nil)
  271. }
  272. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  273. let oldStartDirectoryMediaTabView = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  274. if serverUrl != nil && serverUrl != oldStartDirectoryMediaTabView {
  275. // Save Start Directory
  276. NCManageDatabase.sharedInstance.setAccountStartDirectoryMediaTabView(serverUrl!)
  277. //
  278. NCManageDatabase.sharedInstance.clearTable(tableMedia.self, account: appDelegate.activeAccount)
  279. self.sectionDatasource = CCSectionDataSourceMetadata()
  280. //
  281. loadNetworkDatasource()
  282. }
  283. }
  284. // MARK: SEGUE
  285. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  286. let photoDataSource: NSMutableArray = []
  287. for ocId: String in sectionDatasource.allOcId as! [String] {
  288. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: ocId) as! tableMetadata
  289. if metadata.typeFile == k_metadataTypeFile_image {
  290. photoDataSource.add(metadata)
  291. }
  292. }
  293. if let segueNavigationController = segue.destination as? UINavigationController {
  294. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  295. segueViewController.metadata = metadataPush
  296. segueViewController.metadatas = sectionDatasource.metadatas as! [tableMetadata]
  297. segueViewController.mediaFilterImage = true
  298. }
  299. }
  300. }
  301. }
  302. // MARK: - 3D Touch peek and pop
  303. extension NCMedia: UIViewControllerPreviewingDelegate {
  304. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  305. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  306. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  307. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else { return nil }
  308. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridMediaCell else { return nil }
  309. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  310. previewingContext.sourceRect = cell.frame
  311. viewController.metadata = metadata
  312. viewController.imageFile = cell.imageItem.image
  313. viewController.showOpenIn = true
  314. viewController.showShare = false
  315. viewController.showOpenInternalViewer = false
  316. return viewController
  317. }
  318. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  319. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  320. collectionView(collectionView, didSelectItemAt: indexPath)
  321. }
  322. }
  323. // MARK: - Collection View
  324. extension NCMedia: UICollectionViewDelegate {
  325. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  326. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  327. return
  328. }
  329. metadataPush = metadata
  330. if isEditMode {
  331. if let index = selectocId.firstIndex(of: metadata.ocId) {
  332. selectocId.remove(at: index)
  333. } else {
  334. selectocId.append(metadata.ocId)
  335. }
  336. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  337. collectionView.reloadItems(at: [indexPath])
  338. }
  339. return
  340. }
  341. performSegue(withIdentifier: "segueDetail", sender: self)
  342. }
  343. }
  344. extension NCMedia: UICollectionViewDataSource {
  345. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  346. if kind == UICollectionView.elementKindSectionHeader {
  347. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionMediaHeader
  348. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  349. header.labelSection.textColor = .white
  350. header.labelHeightConstraint.constant = 20
  351. header.labelSection.layer.cornerRadius = 10
  352. header.labelSection.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  353. let width = header.labelSection.intrinsicContentSize.width + 30
  354. let leading = collectionView.bounds.width / 2 - width / 2
  355. header.labelWidthConstraint.constant = width
  356. header.labelLeadingConstraint.constant = leading
  357. return header
  358. } else {
  359. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  360. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  361. return footer
  362. }
  363. }
  364. func numberOfSections(in collectionView: UICollectionView) -> Int {
  365. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  366. return sections
  367. }
  368. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  369. var numberOfItemsInSection: Int = 0
  370. if section < sectionDatasource.sections.count {
  371. let key = sectionDatasource.sections.object(at: section)
  372. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  373. numberOfItemsInSection = datasource.count
  374. }
  375. return numberOfItemsInSection
  376. }
  377. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  378. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  379. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  380. }
  381. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  382. NCMainCommon.sharedInstance.collectionViewCellForItemAt(indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: nil, serverUrl: metadata.serverUrl, isEditMode: isEditMode, selectocId: selectocId, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: true, downloadThumbnail: false, shares: nil, source: self)
  383. return cell
  384. }
  385. }
  386. extension NCMedia: UICollectionViewDelegateFlowLayout {
  387. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  388. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  389. }
  390. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  391. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  392. if (section == sections - 1) {
  393. return CGSize(width: collectionView.frame.width, height: footerHeight)
  394. } else {
  395. return CGSize(width: collectionView.frame.width, height: 0)
  396. }
  397. }
  398. }
  399. // MARK: - NC API & Algorithm
  400. extension NCMedia {
  401. public func reloadDataSource(loadNetworkDatasource: Bool, completion: @escaping ()->()) {
  402. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  403. return
  404. }
  405. DispatchQueue.global().async {
  406. let metadatas = NCManageDatabase.sharedInstance.getMedias(account: self.appDelegate.activeAccount, predicate: NSPredicate(format: "account == %@", self.appDelegate.activeAccount))
  407. self.sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: "date", filterocId: nil, filterTypeFileImage: self.filterTypeFileImage, filterTypeFileVideo: self.filterTypeFileVideo, sorted: "date", ascending: false, activeAccount: self.appDelegate.activeAccount)
  408. DispatchQueue.main.async {
  409. self.collectionView?.reloadData()
  410. if loadNetworkDatasource {
  411. self.loadNetworkDatasource()
  412. }
  413. self.collectionView?.reloadDataThenPerform {
  414. self.downloadThumbnail()
  415. }
  416. completion()
  417. }
  418. }
  419. }
  420. func deleteItems() {
  421. self.isEditMode = false
  422. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  423. return
  424. }
  425. for ocId in selectocId {
  426. if let metadata = NCManageDatabase.sharedInstance.getMedia(predicate: NSPredicate(format: "ocId == %@", ocId)) {
  427. NCNetworking.sharedInstance.deleteMetadata(metadata, user: appDelegate.activeUser, userID: appDelegate.activeUserID, password: appDelegate.activePassword, url: appDelegate.activeUrl) { (errorCode, errorDescription) in }
  428. }
  429. }
  430. }
  431. func search(lteDate: Date, gteDate: Date, addPast: Bool, insertPrevius: Int,setDistantPast: Bool, debug: String) {
  432. // ----- DEBUG -----
  433. #if DEBUG
  434. let dateFormatter = DateFormatter()
  435. dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
  436. print("[LOG] Search: addPast \(addPast), distantPass: \(setDistantPast), Lte: " + dateFormatter.string(from: lteDate) + " - Gte: " + dateFormatter.string(from: gteDate) + " DEBUG: " + debug)
  437. #endif
  438. // -----------------
  439. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  440. return
  441. }
  442. if addPast && loadingSearch {
  443. return
  444. }
  445. if setDistantPast {
  446. isDistantPast = true
  447. }
  448. if addPast {
  449. //CCGraphics.addImage(toTitle: NSLocalizedString("_media_", comment: ""), colorTitle: NCBrandColor.sharedInstance.brandText, imageTitle: CCGraphics.changeThemingColorImage(UIImage.init(named: "load"), multiplier: 2, color: NCBrandColor.sharedInstance.brandText), imageRight: false, navigationItem: self.navigationItem)
  450. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: 50)
  451. }
  452. loadingSearch = true
  453. let startDirectory = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  454. OCNetworking.sharedManager()?.search(withAccount: appDelegate.activeAccount, fileName: "", serverUrl: startDirectory, contentType: ["image/%", "video/%"], lteDateLastModified: lteDate, gteDateLastModified: gteDate, depth: "infinity", completion: { (account, metadatas, message, errorCode) in
  455. self.refreshControl.endRefreshing()
  456. NCUtility.sharedInstance.stopActivityIndicator()
  457. //self.navigationItem.titleView = nil
  458. //self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  459. if errorCode == 0 && account == self.appDelegate.activeAccount {
  460. var isDifferent: Bool = false
  461. var newInsert: Int = 0
  462. let totalDistance = Calendar.current.dateComponents([Calendar.Component.day], from: gteDate, to: lteDate).value(for: .day) ?? 0
  463. let difference = NCManageDatabase.sharedInstance.createTableMedia(metadatas as! [tableMetadata], lteDate: lteDate, gteDate: gteDate, account: account!)
  464. isDifferent = difference.isDifferent
  465. newInsert = difference.newInsert
  466. self.loadingSearch = false
  467. print("[LOG] Search: Totale Distance \(totalDistance) - It's Different \(isDifferent) - New insert \(newInsert)")
  468. if isDifferent {
  469. self.reloadDataSource(loadNetworkDatasource: false) { }
  470. }
  471. if (isDifferent == false || newInsert+insertPrevius < 100) && addPast && setDistantPast == false {
  472. switch totalDistance {
  473. case 0...89:
  474. if var gteDate90 = Calendar.current.date(byAdding: .day, value: -90, to: gteDate) {
  475. gteDate90 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate90) ?? Date()
  476. self.search(lteDate: lteDate, gteDate: gteDate90, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -90 gg")
  477. }
  478. case 90...179:
  479. if var gteDate180 = Calendar.current.date(byAdding: .day, value: -180, to: gteDate) {
  480. gteDate180 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate180) ?? Date()
  481. self.search(lteDate: lteDate, gteDate: gteDate180, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -180 gg")
  482. }
  483. case 180...364:
  484. if var gteDate365 = Calendar.current.date(byAdding: .day, value: -365, to: gteDate) {
  485. gteDate365 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate365) ?? Date()
  486. self.search(lteDate: lteDate, gteDate: gteDate365, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -365 gg")
  487. }
  488. default:
  489. self.search(lteDate: lteDate, gteDate: NSDate.distantPast, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: true, debug: "search recursive distant pass")
  490. }
  491. }
  492. self.collectionView?.reloadDataThenPerform {
  493. self.downloadThumbnail()
  494. }
  495. } else {
  496. self.loadingSearch = false
  497. self.reloadDataSource(loadNetworkDatasource: false) { }
  498. }
  499. })
  500. }
  501. @objc private func loadNetworkDatasource() {
  502. isDistantPast = false
  503. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  504. return
  505. }
  506. if sectionDatasource.allRecordsDataSource.count == 0 {
  507. let gteDate = Calendar.current.date(byAdding: .day, value: -30, to: Date())
  508. search(lteDate: Date(), gteDate: gteDate!, addPast: true, insertPrevius: 0, setDistantPast: false, debug: "search (add past) today, -30 gg")
  509. } else {
  510. let gteDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedAscending)
  511. search(lteDate: Date(), gteDate: gteDate, addPast: false, insertPrevius: 0, setDistantPast: false, debug: "search today, first date record")
  512. }
  513. collectionView?.reloadDataThenPerform {
  514. self.downloadThumbnail()
  515. }
  516. }
  517. private func selectSearchSections() {
  518. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  519. return
  520. }
  521. let sections = NSMutableSet()
  522. let lastDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedDescending)
  523. var gteDate: Date?
  524. for item in collectionView.indexPathsForVisibleItems {
  525. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: sectionDatasource) {
  526. if let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: metadata.date as Date) {
  527. sections.add(date)
  528. }
  529. }
  530. }
  531. let sortedSections = sections.sorted { (date1, date2) -> Bool in
  532. (date1 as! Date).compare(date2 as! Date) == .orderedDescending
  533. }
  534. if sortedSections.count >= 1 {
  535. let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: sortedSections.first as! Date)!
  536. if lastDate == sortedSections.last as! Date {
  537. gteDate = Calendar.current.date(byAdding: .day, value: -30, to: sortedSections.last as! Date)!
  538. search(lteDate: lteDate, gteDate: gteDate!, addPast: true, insertPrevius: 0, setDistantPast: false, debug: "search (add past) last record, -30 gg")
  539. } else {
  540. gteDate = Calendar.current.date(byAdding: .day, value: -1, to: sortedSections.last as! Date)!
  541. search(lteDate: lteDate, gteDate: gteDate!, addPast: false, insertPrevius: 0, setDistantPast: false, debug: "search [refresh window]")
  542. }
  543. }
  544. }
  545. private func downloadThumbnail() {
  546. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  547. for item in self.collectionView.indexPathsForVisibleItems {
  548. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: self.sectionDatasource) {
  549. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: self.collectionView as Any, indexPath: item)
  550. }
  551. }
  552. }
  553. }
  554. }
  555. // MARK: - FastScroll - ScrollView
  556. extension NCMedia: UIScrollViewDelegate {
  557. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  558. collectionView.scrollViewDidScroll(scrollView)
  559. }
  560. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  561. collectionView.scrollViewWillBeginDragging(scrollView)
  562. }
  563. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  564. collectionView.scrollViewDidEndDecelerating(scrollView)
  565. }
  566. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  567. collectionView.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
  568. }
  569. func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
  570. selectSearchSections()
  571. }
  572. }
  573. extension NCMedia: FastScrollCollectionViewDelegate {
  574. fileprivate func configFastScroll() {
  575. collectionView.fastScrollDelegate = self
  576. //bubble
  577. collectionView.deactivateBubble = true
  578. collectionView.bubbleFocus = .dynamic
  579. collectionView.bubbleTextSize = 14.0
  580. collectionView.bubbleMarginRight = 50.0
  581. collectionView.bubbleColor = UIColor(red: 38.0 / 255.0, green: 48.0 / 255.0, blue: 60.0 / 255.0, alpha: 1.0)
  582. //handle
  583. /*
  584. collectionView.handleHeight = 40.0
  585. collectionView.handleWidth = 40.0
  586. collectionView.handleRadius = 20.0
  587. */
  588. collectionView.handleTimeToDisappear = 1
  589. collectionView.handleMarginRight = 3
  590. collectionView.handleColor = NCBrandColor.sharedInstance.brand
  591. collectionView.handle?.backgroundColor = NCBrandColor.sharedInstance.brand
  592. //scrollbar
  593. collectionView.scrollbarWidth = 0.0
  594. collectionView.scrollbarMarginTop = 43.0
  595. collectionView.scrollbarMarginBottom = 5.0
  596. collectionView.scrollbarMarginRight = 10.0
  597. //callback action to display bubble name
  598. /*
  599. collectionView.bubbleNameForIndexPath = { indexPath in
  600. let visibleSection: Section = self.data[indexPath.section]
  601. return visibleSection.sectionTitle
  602. }
  603. */
  604. }
  605. func hideHandle() {
  606. selectSearchSections()
  607. }
  608. }
  609. extension FastScrollCollectionView
  610. {
  611. /// Calls reloadsData() on self, and ensures that the given closure is
  612. /// called after reloadData() has been completed.
  613. ///
  614. /// Discussion: reloadData() appears to be asynchronous. i.e. the
  615. /// reloading actually happens during the next layout pass. So, doing
  616. /// things like scrolling the collectionView immediately after a
  617. /// call to reloadData() can cause trouble.
  618. ///
  619. /// This method uses CATransaction to schedule the closure.
  620. func reloadDataThenPerform(_ closure: @escaping (() -> Void))
  621. {
  622. CATransaction.begin()
  623. CATransaction.setCompletionBlock(closure)
  624. self.reloadData()
  625. CATransaction.commit()
  626. }
  627. }