NCMedia.swift 34 KB

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