NCMedia.swift 35 KB

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