NCMedia.swift 39 KB

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