NCMedia.swift 35 KB

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