NCMedia.swift 38 KB

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