NCMedia.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. //
  2. // NCMedia.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/02/2019.
  6. // Copyright © 2019 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. import Sheeeeeeeeet
  25. import FastScroll
  26. class NCMedia: UIViewController, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, NCSelectDelegate {
  27. @IBOutlet weak var collectionView : FastScrollCollectionView!
  28. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  29. var sectionDatasource = CCSectionDataSourceMetadata()
  30. private var metadataPush: tableMetadata?
  31. private var isEditMode = false
  32. private var selectocId = [String]()
  33. private var filterTypeFileImage = false;
  34. private var filterTypeFileVideo = false;
  35. private var autoUploadFileName = ""
  36. private var autoUploadDirectory = ""
  37. private var gridLayout: NCGridMediaLayout!
  38. private var actionSheet: ActionSheet?
  39. private let sectionHeaderHeight: CGFloat = 50
  40. private let footerHeight: CGFloat = 50
  41. private var stepImageWidth: CGFloat = 10
  42. private var isDistantPast = false
  43. private let refreshControl = UIRefreshControl()
  44. private var loadingSearch = false
  45. required init?(coder aDecoder: NSCoder) {
  46. super.init(coder: aDecoder)
  47. appDelegate.activeMedia = self
  48. 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: CCGraphics.changeThemingColorImage(UIImage(named: "more"), width: 50, height: 50, color: NCBrandColor.sharedInstance.textView), style: .plain, target: self, action: #selector(touchUpInsideMenuButtonMore))
  54. self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: CCGraphics.changeThemingColorImage(UIImage(named: "grid"), width: 50, height: 50, color: NCBrandColor.sharedInstance.textView), style: .plain, target: self, action: #selector(touchUpInsideMenuButtonSwitch))
  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, let errorCode = userInfo["errorCode"] as? Int {
  116. if errorCode != 0 { return }
  117. self.selectocId.removeAll { $0 == metadata.ocId }
  118. self.reloadDataSource(loadNetworkDatasource: false)
  119. let userInfo: [String : Any] = ["metadata": metadata, "type": "delete"]
  120. NotificationCenter.default.post(name: Notification.Name.init(rawValue: k_notificationCenter_synchronizationMedia), object: nil, userInfo: userInfo)
  121. }
  122. }
  123. }
  124. // MARK: DZNEmpty
  125. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  126. return NCBrandColor.sharedInstance.backgroundView
  127. }
  128. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  129. return CCGraphics.changeThemingColorImage(UIImage.init(named: "media"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  130. }
  131. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  132. var text = "\n" + NSLocalizedString("_tutorial_photo_view_", comment: "")
  133. if loadingSearch {
  134. text = "\n" + NSLocalizedString("_search_in_progress_", comment: "")
  135. }
  136. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  137. return NSAttributedString.init(string: text, attributes: attributes)
  138. }
  139. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  140. return true
  141. }
  142. // MARK: IBAction
  143. @objc func touchUpInsideMenuButtonSwitch(_ sender: Any) {
  144. let itemSizeStart = self.gridLayout.itemSize
  145. UIView.animate(withDuration: 0.0, animations: {
  146. if self.gridLayout.numItems == 1 && self.stepImageWidth > 0 {
  147. self.stepImageWidth = -10
  148. } else if itemSizeStart.width < 50 {
  149. self.stepImageWidth = 10
  150. }
  151. repeat {
  152. self.gridLayout.preferenceWidth = self.gridLayout.preferenceWidth + self.stepImageWidth
  153. } while (self.gridLayout.itemSize == itemSizeStart)
  154. CCUtility.setMediaWidthImage(Int(self.gridLayout?.preferenceWidth ?? 80))
  155. self.collectionView.collectionViewLayout.invalidateLayout()
  156. if self.stepImageWidth < 0 {
  157. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  158. self.selectSearchSections()
  159. }
  160. }
  161. })
  162. }
  163. @objc func touchUpInsideMenuButtonMore(_ sender: Any) {
  164. var menu: DropdownMenu?
  165. if !isEditMode {
  166. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "selectFull"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_", comment: ""))
  167. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "folderAutomaticUpload"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_select_media_folder_", comment: ""))
  168. var item2: DropdownItem
  169. if filterTypeFileImage {
  170. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageno"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_show_", comment: ""))
  171. } else {
  172. item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "imageyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewimage_hide_", comment: ""))
  173. }
  174. var item3: DropdownItem
  175. if filterTypeFileVideo {
  176. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videono"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_show_", comment: ""))
  177. } else {
  178. item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "videoyes"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_media_viewvideo_hide_", comment: ""))
  179. }
  180. menu = DropdownMenu(navigationController: self.navigationController!, items: [item0,item1,item2,item3], selectedRow: -1)
  181. menu?.token = "menuButtonMore"
  182. } else {
  183. let item0 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "cancel"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_cancel_", comment: ""))
  184. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_delete_", comment: ""))
  185. menu = DropdownMenu(navigationController: self.navigationController!, items: [item0, item1], selectedRow: -1)
  186. menu?.token = "menuButtonMoreSelect"
  187. }
  188. menu?.delegate = self
  189. menu?.rowHeight = 45
  190. menu?.highlightColor = NCBrandColor.sharedInstance.brand
  191. menu?.tableView.alwaysBounceVertical = false
  192. menu?.tableViewSeperatorColor = NCBrandColor.sharedInstance.separator
  193. menu?.tableViewBackgroundColor = NCBrandColor.sharedInstance.backgroundForm
  194. menu?.cellBackgroundColor = NCBrandColor.sharedInstance.backgroundForm
  195. menu?.textColor = NCBrandColor.sharedInstance.textView
  196. menu?.showMenu()
  197. }
  198. // MARK: DROP-DOWN-MENU
  199. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  200. if dropdownMenu.token == "menuButtonMore" {
  201. switch indexPath.row {
  202. case 0:
  203. isEditMode = true
  204. case 1:
  205. selectStartDirectoryPhotosTab()
  206. case 2:
  207. filterTypeFileImage = !filterTypeFileImage
  208. reloadDataSource(loadNetworkDatasource: false)
  209. case 3:
  210. filterTypeFileVideo = !filterTypeFileVideo
  211. reloadDataSource(loadNetworkDatasource: false)
  212. default: ()
  213. }
  214. }
  215. if dropdownMenu.token == "menuButtonMoreSelect" {
  216. switch indexPath.row {
  217. case 0:
  218. isEditMode = false
  219. selectocId.removeAll()
  220. collectionView?.reloadDataThenPerform {
  221. self.downloadThumbnail()
  222. }
  223. case 1:
  224. deleteItems()
  225. default: ()
  226. }
  227. }
  228. }
  229. // MARK: Select Directory
  230. func selectStartDirectoryPhotosTab() {
  231. let navigationController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateInitialViewController() as! UINavigationController
  232. let viewController = navigationController.topViewController as! NCSelect
  233. viewController.delegate = self
  234. viewController.hideButtonCreateFolder = true
  235. viewController.includeDirectoryE2EEncryption = false
  236. viewController.includeImages = false
  237. viewController.layoutViewSelect = k_layout_view_move
  238. viewController.selectFile = false
  239. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  240. viewController.type = "mediaFolder"
  241. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  242. self.present(navigationController, animated: true, completion: nil)
  243. }
  244. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  245. let oldStartDirectoryMediaTabView = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  246. if serverUrl != nil && serverUrl != oldStartDirectoryMediaTabView {
  247. // Save Start Directory
  248. NCManageDatabase.sharedInstance.setAccountStartDirectoryMediaTabView(serverUrl!)
  249. //
  250. NCManageDatabase.sharedInstance.clearTable(tableMedia.self, account: appDelegate.activeAccount)
  251. self.sectionDatasource = CCSectionDataSourceMetadata()
  252. //
  253. loadNetworkDatasource()
  254. }
  255. }
  256. // MARK: SEGUE
  257. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  258. let photoDataSource: NSMutableArray = []
  259. for ocId: String in sectionDatasource.allOcId as! [String] {
  260. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: ocId) as! tableMetadata
  261. if metadata.typeFile == k_metadataTypeFile_image {
  262. photoDataSource.add(metadata)
  263. }
  264. }
  265. if let segueNavigationController = segue.destination as? UINavigationController {
  266. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  267. segueViewController.metadata = metadataPush
  268. segueViewController.metadatas = sectionDatasource.metadatas as! [tableMetadata]
  269. segueViewController.mediaFilterImage = true
  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. viewController.showOpenInternalViewer = false
  288. return viewController
  289. }
  290. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  291. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  292. collectionView(collectionView, didSelectItemAt: indexPath)
  293. }
  294. }
  295. // MARK: - Collection View
  296. extension NCMedia: UICollectionViewDelegate {
  297. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  298. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  299. return
  300. }
  301. metadataPush = metadata
  302. if isEditMode {
  303. if let index = selectocId.firstIndex(of: metadata.ocId) {
  304. selectocId.remove(at: index)
  305. } else {
  306. selectocId.append(metadata.ocId)
  307. }
  308. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  309. collectionView.reloadItems(at: [indexPath])
  310. }
  311. return
  312. }
  313. performSegue(withIdentifier: "segueDetail", sender: self)
  314. }
  315. }
  316. extension NCMedia: UICollectionViewDataSource {
  317. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  318. if kind == UICollectionView.elementKindSectionHeader {
  319. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionMediaHeader
  320. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  321. header.labelSection.textColor = .white
  322. header.labelHeightConstraint.constant = 20
  323. header.labelSection.layer.cornerRadius = 10
  324. header.labelSection.layer.backgroundColor = UIColor(red: 152.0/255.0, green: 167.0/255.0, blue: 181.0/255.0, alpha: 0.8).cgColor
  325. let width = header.labelSection.intrinsicContentSize.width + 30
  326. let leading = collectionView.bounds.width / 2 - width / 2
  327. header.labelWidthConstraint.constant = width
  328. header.labelLeadingConstraint.constant = leading
  329. return header
  330. } else {
  331. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  332. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  333. return footer
  334. }
  335. }
  336. func numberOfSections(in collectionView: UICollectionView) -> Int {
  337. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  338. return sections
  339. }
  340. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  341. var numberOfItemsInSection: Int = 0
  342. if section < sectionDatasource.sections.count {
  343. let key = sectionDatasource.sections.object(at: section)
  344. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  345. numberOfItemsInSection = datasource.count
  346. }
  347. return numberOfItemsInSection
  348. }
  349. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  350. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  351. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  352. }
  353. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridMediaCell
  354. 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)
  355. return cell
  356. }
  357. }
  358. extension NCMedia: UICollectionViewDelegateFlowLayout {
  359. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  360. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  361. }
  362. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  363. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  364. if (section == sections - 1) {
  365. return CGSize(width: collectionView.frame.width, height: footerHeight)
  366. } else {
  367. return CGSize(width: collectionView.frame.width, height: 0)
  368. }
  369. }
  370. }
  371. // MARK: - NC API & Algorithm
  372. extension NCMedia {
  373. public func reloadDataSource(loadNetworkDatasource: Bool) {
  374. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  375. return
  376. }
  377. DispatchQueue.global().async {
  378. let metadatas = NCManageDatabase.sharedInstance.getMedias(account: self.appDelegate.activeAccount, predicate: NSPredicate(format: "account == %@", self.appDelegate.activeAccount))
  379. 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)
  380. DispatchQueue.main.async {
  381. self.collectionView?.reloadData()
  382. if loadNetworkDatasource {
  383. self.loadNetworkDatasource()
  384. }
  385. self.collectionView?.reloadDataThenPerform {
  386. self.downloadThumbnail()
  387. }
  388. }
  389. }
  390. }
  391. func deleteItems() {
  392. self.isEditMode = false
  393. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  394. return
  395. }
  396. for ocId in selectocId {
  397. if let metadata = NCManageDatabase.sharedInstance.getMedia(predicate: NSPredicate(format: "ocId == %@", ocId)) {
  398. NCNetworking.sharedInstance.deleteMetadata(metadata) { (errorCode, errorDescription) in }
  399. }
  400. }
  401. }
  402. func search(lteDate: Date, gteDate: Date, addPast: Bool, insertPrevius: Int,setDistantPast: Bool, debug: String) {
  403. // ----- DEBUG -----
  404. #if DEBUG
  405. let dateFormatter = DateFormatter()
  406. dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
  407. print("[LOG] Search: addPast \(addPast), distantPass: \(setDistantPast), Lte: " + dateFormatter.string(from: lteDate) + " - Gte: " + dateFormatter.string(from: gteDate) + " DEBUG: " + debug)
  408. #endif
  409. // -----------------
  410. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  411. return
  412. }
  413. if addPast && loadingSearch {
  414. return
  415. }
  416. if setDistantPast {
  417. isDistantPast = true
  418. }
  419. if addPast {
  420. //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)
  421. NCUtility.sharedInstance.startActivityIndicator(view: self.view, bottom: 50)
  422. }
  423. loadingSearch = true
  424. let startDirectory = NCManageDatabase.sharedInstance.getAccountStartDirectoryMediaTabView(CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl))
  425. OCNetworking.sharedManager()?.search(withAccount: appDelegate.activeAccount, fileName: "", serverUrl: startDirectory, contentType: ["image/%", "video/%"], lteDateLastModified: lteDate, gteDateLastModified: gteDate, depth: "infinity", completion: { (account, metadatas, message, errorCode) in
  426. self.refreshControl.endRefreshing()
  427. NCUtility.sharedInstance.stopActivityIndicator()
  428. //self.navigationItem.titleView = nil
  429. //self.navigationItem.title = NSLocalizedString("_media_", comment: "")
  430. if errorCode == 0 && account == self.appDelegate.activeAccount {
  431. var isDifferent: Bool = false
  432. var newInsert: Int = 0
  433. let totalDistance = Calendar.current.dateComponents([Calendar.Component.day], from: gteDate, to: lteDate).value(for: .day) ?? 0
  434. let difference = NCManageDatabase.sharedInstance.createTableMedia(metadatas as! [tableMetadata], lteDate: lteDate, gteDate: gteDate, account: account!)
  435. isDifferent = difference.isDifferent
  436. newInsert = difference.newInsert
  437. self.loadingSearch = false
  438. print("[LOG] Search: Totale Distance \(totalDistance) - It's Different \(isDifferent) - New insert \(newInsert)")
  439. if isDifferent {
  440. self.reloadDataSource(loadNetworkDatasource: false)
  441. }
  442. if (isDifferent == false || newInsert+insertPrevius < 100) && addPast && setDistantPast == false {
  443. switch totalDistance {
  444. case 0...89:
  445. if var gteDate90 = Calendar.current.date(byAdding: .day, value: -90, to: gteDate) {
  446. gteDate90 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate90) ?? Date()
  447. self.search(lteDate: lteDate, gteDate: gteDate90, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -90 gg")
  448. }
  449. case 90...179:
  450. if var gteDate180 = Calendar.current.date(byAdding: .day, value: -180, to: gteDate) {
  451. gteDate180 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate180) ?? Date()
  452. self.search(lteDate: lteDate, gteDate: gteDate180, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -180 gg")
  453. }
  454. case 180...364:
  455. if var gteDate365 = Calendar.current.date(byAdding: .day, value: -365, to: gteDate) {
  456. gteDate365 = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: gteDate365) ?? Date()
  457. self.search(lteDate: lteDate, gteDate: gteDate365, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: false, debug: "search recursive -365 gg")
  458. }
  459. default:
  460. self.search(lteDate: lteDate, gteDate: NSDate.distantPast, addPast: addPast, insertPrevius: newInsert+insertPrevius, setDistantPast: true, debug: "search recursive distant pass")
  461. }
  462. }
  463. self.collectionView?.reloadDataThenPerform {
  464. self.downloadThumbnail()
  465. }
  466. } else {
  467. self.loadingSearch = false
  468. self.reloadDataSource(loadNetworkDatasource: false)
  469. }
  470. })
  471. }
  472. @objc private func loadNetworkDatasource() {
  473. isDistantPast = false
  474. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  475. return
  476. }
  477. if sectionDatasource.allRecordsDataSource.count == 0 {
  478. let gteDate = Calendar.current.date(byAdding: .day, value: -30, to: Date())
  479. search(lteDate: Date(), gteDate: gteDate!, addPast: true, insertPrevius: 0, setDistantPast: false, debug: "search (add past) today, -30 gg")
  480. } else {
  481. let gteDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedAscending)
  482. search(lteDate: Date(), gteDate: gteDate, addPast: false, insertPrevius: 0, setDistantPast: false, debug: "search today, first date record")
  483. }
  484. collectionView?.reloadDataThenPerform {
  485. self.downloadThumbnail()
  486. }
  487. }
  488. private func selectSearchSections() {
  489. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  490. return
  491. }
  492. let sections = NSMutableSet()
  493. let lastDate = NCManageDatabase.sharedInstance.getTableMediaDate(account: self.appDelegate.activeAccount, order: .orderedDescending)
  494. var gteDate: Date?
  495. for item in collectionView.indexPathsForVisibleItems {
  496. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: sectionDatasource) {
  497. if let date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: metadata.date as Date) {
  498. sections.add(date)
  499. }
  500. }
  501. }
  502. let sortedSections = sections.sorted { (date1, date2) -> Bool in
  503. (date1 as! Date).compare(date2 as! Date) == .orderedDescending
  504. }
  505. if sortedSections.count >= 1 {
  506. let lteDate = Calendar.current.date(byAdding: .day, value: 1, to: sortedSections.first as! Date)!
  507. if lastDate == sortedSections.last as! Date {
  508. gteDate = Calendar.current.date(byAdding: .day, value: -30, to: sortedSections.last as! Date)!
  509. search(lteDate: lteDate, gteDate: gteDate!, addPast: true, insertPrevius: 0, setDistantPast: false, debug: "search (add past) last record, -30 gg")
  510. } else {
  511. gteDate = Calendar.current.date(byAdding: .day, value: -1, to: sortedSections.last as! Date)!
  512. search(lteDate: lteDate, gteDate: gteDate!, addPast: false, insertPrevius: 0, setDistantPast: false, debug: "search [refresh window]")
  513. }
  514. }
  515. }
  516. private func downloadThumbnail() {
  517. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  518. for item in self.collectionView.indexPathsForVisibleItems {
  519. if let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(item, sectionDataSource: self.sectionDatasource) {
  520. NCNetworkingMain.sharedInstance.downloadThumbnail(with: metadata, view: self.collectionView as Any, indexPath: item)
  521. }
  522. }
  523. }
  524. }
  525. }
  526. // MARK: - FastScroll - ScrollView
  527. extension NCMedia: UIScrollViewDelegate {
  528. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  529. collectionView.scrollViewDidScroll(scrollView)
  530. }
  531. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  532. collectionView.scrollViewWillBeginDragging(scrollView)
  533. }
  534. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  535. collectionView.scrollViewDidEndDecelerating(scrollView)
  536. }
  537. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  538. collectionView.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
  539. }
  540. func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
  541. selectSearchSections()
  542. }
  543. }
  544. extension NCMedia: FastScrollCollectionViewDelegate {
  545. fileprivate func configFastScroll() {
  546. collectionView.fastScrollDelegate = self
  547. //bubble
  548. collectionView.deactivateBubble = true
  549. collectionView.bubbleFocus = .dynamic
  550. collectionView.bubbleTextSize = 14.0
  551. collectionView.bubbleMarginRight = 50.0
  552. collectionView.bubbleColor = UIColor(red: 38.0 / 255.0, green: 48.0 / 255.0, blue: 60.0 / 255.0, alpha: 1.0)
  553. //handle
  554. /*
  555. collectionView.handleHeight = 40.0
  556. collectionView.handleWidth = 40.0
  557. collectionView.handleRadius = 20.0
  558. */
  559. collectionView.handleTimeToDisappear = 1
  560. collectionView.handleMarginRight = 3
  561. collectionView.handleColor = NCBrandColor.sharedInstance.brand
  562. collectionView.handle?.backgroundColor = NCBrandColor.sharedInstance.brand
  563. //scrollbar
  564. collectionView.scrollbarWidth = 0.0
  565. collectionView.scrollbarMarginTop = 43.0
  566. collectionView.scrollbarMarginBottom = 5.0
  567. collectionView.scrollbarMarginRight = 10.0
  568. //callback action to display bubble name
  569. /*
  570. collectionView.bubbleNameForIndexPath = { indexPath in
  571. let visibleSection: Section = self.data[indexPath.section]
  572. return visibleSection.sectionTitle
  573. }
  574. */
  575. }
  576. func hideHandle() {
  577. selectSearchSections()
  578. }
  579. }
  580. extension FastScrollCollectionView
  581. {
  582. /// Calls reloadsData() on self, and ensures that the given closure is
  583. /// called after reloadData() has been completed.
  584. ///
  585. /// Discussion: reloadData() appears to be asynchronous. i.e. the
  586. /// reloading actually happens during the next layout pass. So, doing
  587. /// things like scrolling the collectionView immediately after a
  588. /// call to reloadData() can cause trouble.
  589. ///
  590. /// This method uses CATransaction to schedule the closure.
  591. func reloadDataThenPerform(_ closure: @escaping (() -> Void))
  592. {
  593. CATransaction.begin()
  594. CATransaction.setCompletionBlock(closure)
  595. self.reloadData()
  596. CATransaction.commit()
  597. }
  598. }