NCMedia.swift 39 KB

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