NCMedia.swift 35 KB

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