NCSelect.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. //
  2. // NCSelect.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 06/11/2018.
  6. // Copyright © 2018 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 UIKit
  24. import SwiftUI
  25. import NextcloudKit
  26. @objc protocol NCSelectDelegate {
  27. @objc func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool)
  28. }
  29. class NCSelect: UIViewController, UIGestureRecognizerDelegate, UIAdaptivePresentationControllerDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate {
  30. @IBOutlet private var collectionView: UICollectionView!
  31. @IBOutlet private var buttonCancel: UIBarButtonItem!
  32. @IBOutlet private var bottomContraint: NSLayoutConstraint?
  33. private let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  34. private var selectCommandViewSelect: NCSelectCommandView?
  35. let utilityFileSystem = NCUtilityFileSystem()
  36. let utility = NCUtility()
  37. @objc enum selectType: Int {
  38. case select
  39. case selectCreateFolder
  40. case copyMove
  41. case nothing
  42. }
  43. // ------ external settings ------------------------------------
  44. @objc weak var delegate: NCSelectDelegate?
  45. @objc var typeOfCommandView: selectType = .select
  46. @objc var includeDirectoryE2EEncryption = false
  47. @objc var includeImages = false
  48. @objc var enableSelectFile = false
  49. @objc var type = ""
  50. @objc var items: [tableMetadata] = []
  51. var titleCurrentFolder = NCBrandOptions.shared.brand
  52. var serverUrl = ""
  53. // -------------------------------------------------------------
  54. private var dataSourceTask: URLSessionTask?
  55. private var serverUrlPush = ""
  56. private var metadataFolder = tableMetadata()
  57. private var overwrite = true
  58. private var dataSource = NCDataSource()
  59. internal var richWorkspaceText: String?
  60. internal var headerMenu: NCSectionHeaderMenu?
  61. private var autoUploadFileName = ""
  62. private var autoUploadDirectory = ""
  63. private var backgroundImageView = UIImageView()
  64. private var activeAccount: tableAccount!
  65. private let window = UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] }.first { $0.isKeyWindow }
  66. // MARK: - View Life Cycle
  67. override func viewDidLoad() {
  68. super.viewDidLoad()
  69. navigationController?.navigationBar.prefersLargeTitles = true
  70. navigationController?.presentationController?.delegate = self
  71. navigationController?.navigationBar.tintColor = NCBrandColor.shared.iconImageColor
  72. view.backgroundColor = .systemBackground
  73. selectCommandViewSelect?.separatorView.backgroundColor = .separator
  74. activeAccount = NCManageDatabase.shared.getActiveAccount()
  75. // Cell
  76. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  77. collectionView.collectionViewLayout = NCListLayout()
  78. // Header
  79. collectionView.register(UINib(nibName: "NCSectionHeaderEmptyData", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderEmptyData")
  80. collectionView.register(UINib(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  81. // Footer
  82. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  83. collectionView.alwaysBounceVertical = true
  84. collectionView.backgroundColor = .systemBackground
  85. buttonCancel.title = NSLocalizedString("_cancel_", comment: "")
  86. bottomContraint?.constant = window?.rootViewController?.view.safeAreaInsets.bottom ?? 0
  87. // Type of command view
  88. if typeOfCommandView == .select || typeOfCommandView == .selectCreateFolder {
  89. if typeOfCommandView == .select {
  90. selectCommandViewSelect = Bundle.main.loadNibNamed("NCSelectCommandViewSelect", owner: self, options: nil)?.first as? NCSelectCommandView
  91. } else {
  92. selectCommandViewSelect = Bundle.main.loadNibNamed("NCSelectCommandViewSelect+CreateFolder", owner: self, options: nil)?.first as? NCSelectCommandView
  93. }
  94. self.view.addSubview(selectCommandViewSelect!)
  95. selectCommandViewSelect?.selectView = self
  96. selectCommandViewSelect?.translatesAutoresizingMaskIntoConstraints = false
  97. selectCommandViewSelect?.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  98. selectCommandViewSelect?.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  99. selectCommandViewSelect?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  100. selectCommandViewSelect?.heightAnchor.constraint(equalToConstant: 80).isActive = true
  101. bottomContraint?.constant = 80
  102. }
  103. if typeOfCommandView == .copyMove {
  104. selectCommandViewSelect = Bundle.main.loadNibNamed("NCSelectCommandViewCopyMove", owner: self, options: nil)?.first as? NCSelectCommandView
  105. self.view.addSubview(selectCommandViewSelect!)
  106. selectCommandViewSelect?.selectView = self
  107. selectCommandViewSelect?.translatesAutoresizingMaskIntoConstraints = false
  108. if items.contains(where: { $0.lock }) {
  109. selectCommandViewSelect?.moveButton?.isEnabled = false
  110. selectCommandViewSelect?.moveButton?.titleLabel?.isEnabled = false
  111. }
  112. selectCommandViewSelect?.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  113. selectCommandViewSelect?.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  114. selectCommandViewSelect?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  115. selectCommandViewSelect?.heightAnchor.constraint(equalToConstant: 150).isActive = true
  116. bottomContraint?.constant = 150
  117. }
  118. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  120. }
  121. override func viewDidAppear(_ animated: Bool) {
  122. super.viewDidAppear(animated)
  123. self.navigationItem.title = titleCurrentFolder
  124. // set the serverUrl
  125. if serverUrl.isEmpty {
  126. serverUrl = utilityFileSystem.getHomeServer(urlBase: activeAccount.urlBase, userId: activeAccount.userId)
  127. }
  128. // get auto upload folder
  129. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  130. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: activeAccount.urlBase, userId: activeAccount.userId, account: activeAccount.account)
  131. loadDatasource(withLoadFolder: true)
  132. }
  133. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  134. super.viewWillTransition(to: size, with: coordinator)
  135. coordinator.animate(alongsideTransition: nil) { _ in
  136. self.collectionView?.collectionViewLayout.invalidateLayout()
  137. }
  138. }
  139. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  140. // Dismission
  141. }
  142. // MARK: - NotificationCenter
  143. @objc func createFolder(_ notification: NSNotification) {
  144. guard let userInfo = notification.userInfo as NSDictionary?,
  145. let ocId = userInfo["ocId"] as? String,
  146. let serverUrl = userInfo["serverUrl"] as? String,
  147. serverUrl == self.serverUrl,
  148. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  149. else { return }
  150. pushMetadata(metadata)
  151. }
  152. // MARK: ACTION
  153. @IBAction func actionCancel(_ sender: UIBarButtonItem) {
  154. self.dismiss(animated: true, completion: nil)
  155. }
  156. func selectButtonPressed(_ sender: UIButton) {
  157. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadataFolder, type: type, items: items, overwrite: overwrite, copy: false, move: false)
  158. self.dismiss(animated: true, completion: nil)
  159. }
  160. func copyButtonPressed(_ sender: UIButton) {
  161. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadataFolder, type: type, items: items, overwrite: overwrite, copy: true, move: false)
  162. self.dismiss(animated: true, completion: nil)
  163. }
  164. func moveButtonPressed(_ sender: UIButton) {
  165. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadataFolder, type: type, items: items, overwrite: overwrite, copy: false, move: true)
  166. self.dismiss(animated: true, completion: nil)
  167. }
  168. func createFolderButtonPressed(_ sender: UIButton) {
  169. let alertController = UIAlertController.createFolder(serverUrl: serverUrl, urlBase: activeAccount)
  170. self.present(alertController, animated: true, completion: nil)
  171. }
  172. @IBAction func valueChangedSwitchOverwrite(_ sender: UISwitch) {
  173. overwrite = sender.isOn
  174. }
  175. // MARK: - Push metadata
  176. func pushMetadata(_ metadata: tableMetadata) {
  177. let serverUrlPush = utilityFileSystem.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)
  178. guard let viewController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect else { return }
  179. self.serverUrlPush = serverUrlPush
  180. viewController.delegate = delegate
  181. viewController.typeOfCommandView = typeOfCommandView
  182. viewController.includeDirectoryE2EEncryption = includeDirectoryE2EEncryption
  183. viewController.includeImages = includeImages
  184. viewController.enableSelectFile = enableSelectFile
  185. viewController.type = type
  186. viewController.overwrite = overwrite
  187. viewController.items = items
  188. viewController.titleCurrentFolder = metadata.fileNameView
  189. viewController.serverUrl = serverUrlPush
  190. self.navigationController?.pushViewController(viewController, animated: true)
  191. }
  192. }
  193. // MARK: - Collection View
  194. extension NCSelect: UICollectionViewDelegate {
  195. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  196. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  197. if metadata.directory {
  198. pushMetadata(metadata)
  199. } else {
  200. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadata, type: type, items: items, overwrite: overwrite, copy: false, move: false)
  201. self.dismiss(animated: true, completion: nil)
  202. }
  203. }
  204. }
  205. extension NCSelect: UICollectionViewDataSource {
  206. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  207. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  208. // Thumbnail
  209. if !metadata.directory {
  210. if FileManager().fileExists(atPath: utilityFileSystem.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  211. (cell as? NCCellProtocol)?.filePreviewImageView?.image = UIImage(contentsOfFile: utilityFileSystem.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  212. } else {
  213. if metadata.iconName.isEmpty {
  214. (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCImageCache.images.file
  215. } else {
  216. (cell as? NCCellProtocol)?.filePreviewImageView?.image = utility.loadImage(named: metadata.iconName, useTypeIconFile: true)
  217. }
  218. if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!utilityFileSystem.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) {
  219. for case let operation as NCCollectionViewDownloadThumbnail in NCNetworking.shared.downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId { return }
  220. NCNetworking.shared.downloadThumbnailQueue.addOperation(NCCollectionViewDownloadThumbnail(metadata: metadata, cell: (cell as? NCCellProtocol), collectionView: collectionView))
  221. }
  222. }
  223. }
  224. }
  225. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  226. }
  227. func numberOfSections(in collectionView: UICollectionView) -> Int {
  228. return dataSource.numberOfSections()
  229. }
  230. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  231. return dataSource.numberOfItemsInSection(section)
  232. }
  233. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  234. guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as? NCListCell,
  235. let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return UICollectionViewCell() }
  236. var isShare = false
  237. var isMounted = false
  238. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  239. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  240. cell.listCellDelegate = self
  241. cell.fileObjectId = metadata.ocId
  242. cell.fileUser = metadata.ownerId
  243. cell.labelTitle.text = metadata.fileNameView
  244. cell.labelTitle.textColor = NCBrandColor.shared.textColor
  245. cell.imageSelect.image = nil
  246. cell.imageStatus.image = nil
  247. cell.imageLocal.image = nil
  248. cell.imageFavorite.image = nil
  249. cell.imageShared.image = nil
  250. cell.imageMore.image = nil
  251. cell.imageItem.image = nil
  252. cell.imageItem.backgroundColor = nil
  253. cell.progressView.progress = 0.0
  254. if metadata.directory {
  255. if metadata.e2eEncrypted {
  256. cell.imageItem.image = NCImageCache.images.folderEncrypted
  257. } else if isShare {
  258. cell.imageItem.image = NCImageCache.images.folderSharedWithMe
  259. } else if !metadata.shareType.isEmpty {
  260. metadata.shareType.contains(3) ?
  261. (cell.imageItem.image = NCImageCache.images.folderPublic) :
  262. (cell.imageItem.image = NCImageCache.images.folderSharedWithMe)
  263. } else if metadata.mountType == "group" {
  264. cell.imageItem.image = NCImageCache.images.folderGroup
  265. } else if isMounted {
  266. cell.imageItem.image = NCImageCache.images.folderExternal
  267. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  268. cell.imageItem.image = NCImageCache.images.folderAutomaticUpload
  269. } else {
  270. cell.imageItem.image = NCImageCache.images.folder
  271. }
  272. cell.imageItem.image = cell.imageItem.image?.colorizeFolder(metadata: metadata)
  273. cell.labelInfo.text = utility.dateDiff(metadata.date as Date)
  274. } else {
  275. cell.labelInfo.text = utility.dateDiff(metadata.date as Date) + " · " + utilityFileSystem.transformedSize(metadata.size)
  276. // image local
  277. if NCManageDatabase.shared.getTableLocalFile(ocId: metadata.ocId) != nil {
  278. cell.imageLocal.image = NCImageCache.images.offlineFlag
  279. } else if utilityFileSystem.fileProviderStorageExists(metadata) {
  280. cell.imageLocal.image = NCImageCache.images.local
  281. }
  282. }
  283. // image Favorite
  284. if metadata.favorite {
  285. cell.imageFavorite.image = NCImageCache.images.favorite
  286. }
  287. cell.imageSelect.isHidden = true
  288. cell.backgroundView = nil
  289. cell.hideButtonMore(true)
  290. cell.hideButtonShare(true)
  291. cell.selectMode(false)
  292. // Live Photo
  293. if metadata.isLivePhoto {
  294. cell.imageStatus.image = NCImageCache.images.livePhoto
  295. }
  296. // Remove last separator
  297. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  298. cell.separator.isHidden = true
  299. } else {
  300. cell.separator.isHidden = false
  301. }
  302. // Add TAGS
  303. cell.setTags(tags: Array(metadata.tags))
  304. return cell
  305. }
  306. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  307. if kind == UICollectionView.elementKindSectionHeader {
  308. if dataSource.getMetadataSourceForAllSections().isEmpty {
  309. guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderEmptyData", for: indexPath) as? NCSectionHeaderEmptyData else { return NCSectionHeaderEmptyData() }
  310. if self.dataSourceTask?.state == .running {
  311. header.emptyImage.image = utility.loadImage(named: "wifi", colors: [NCBrandColor.shared.brandElement])
  312. header.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  313. header.emptyDescription.text = ""
  314. } else {
  315. header.emptyImage.image = NCImageCache.images.folder
  316. if includeImages {
  317. header.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  318. } else {
  319. header.emptyTitle.text = NSLocalizedString("_files_no_folders_", comment: "")
  320. }
  321. header.emptyDescription.text = ""
  322. }
  323. return header
  324. } else {
  325. guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as? NCSectionHeaderMenu else { return NCSectionHeaderMenu() }
  326. let (_, heightHeaderRichWorkspace, _) = getHeaderHeight(section: indexPath.section)
  327. self.headerMenu = header
  328. header.delegate = self
  329. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  330. header.setRichWorkspaceText(richWorkspaceText)
  331. header.setViewTransfer(isHidden: true)
  332. return header
  333. }
  334. } else {
  335. guard let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as? NCSectionFooter else { return NCSectionFooter() }
  336. let sections = dataSource.numberOfSections()
  337. let section = indexPath.section
  338. footer.setTitleLabel("")
  339. footer.separatorIsHidden(true)
  340. if sections == 1 || section == sections - 1 {
  341. let info = dataSource.getFooterInformationAllMetadatas()
  342. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  343. } else {
  344. footer.separatorIsHidden(false)
  345. }
  346. return footer
  347. }
  348. }
  349. }
  350. extension NCSelect: UICollectionViewDelegateFlowLayout {
  351. func getHeaderHeight(section: Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  352. var headerRichWorkspace: CGFloat = 0
  353. if let richWorkspaceText = richWorkspaceText {
  354. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  355. if trimmed.count > 0 {
  356. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  357. }
  358. }
  359. return (0, headerRichWorkspace, 0)
  360. }
  361. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  362. var height: CGFloat = 0
  363. if dataSource.getMetadataSourceForAllSections().isEmpty {
  364. height = NCGlobal.shared.getHeightHeaderEmptyData(view: view, portraitOffset: 0, landscapeOffset: -20)
  365. } else {
  366. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  367. height = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  368. }
  369. return CGSize(width: collectionView.frame.width, height: height)
  370. }
  371. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  372. let sections = dataSource.numberOfSections()
  373. if section == sections - 1 {
  374. return CGSize(width: collectionView.frame.width, height: NCGlobal.shared.endHeightFooter)
  375. } else {
  376. return CGSize(width: collectionView.frame.width, height: NCGlobal.shared.heightFooter)
  377. }
  378. }
  379. }
  380. // MARK: -
  381. extension NCSelect {
  382. @objc func reloadDataSource() {
  383. loadDatasource(withLoadFolder: false)
  384. }
  385. @objc func loadDatasource(withLoadFolder: Bool) {
  386. var predicate: NSPredicate?
  387. if includeDirectoryE2EEncryption {
  388. if includeImages {
  389. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND (directory == true OR classFile == 'image')", activeAccount.account, serverUrl)
  390. } else {
  391. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl)
  392. }
  393. } else {
  394. if includeImages {
  395. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND (directory == true OR classFile == 'image')", activeAccount.account, serverUrl)
  396. } else if enableSelectFile {
  397. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false", activeAccount.account, serverUrl)
  398. } else {
  399. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND directory == true", activeAccount.account, serverUrl)
  400. }
  401. }
  402. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: predicate!)
  403. self.dataSource = NCDataSource(metadatas: metadatas,
  404. account: activeAccount.account,
  405. sort: "fileName",
  406. ascending: true,
  407. directoryOnTop: true,
  408. favoriteOnTop: true,
  409. groupByField: "none")
  410. if withLoadFolder {
  411. loadFolder()
  412. }
  413. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, serverUrl))
  414. richWorkspaceText = directory?.richWorkspace
  415. DispatchQueue.main.async {
  416. self.collectionView.reloadData()
  417. }
  418. }
  419. func loadFolder() {
  420. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { task in
  421. self.dataSourceTask = task
  422. self.collectionView.reloadData()
  423. } completion: { _, _, _, _, _, error in
  424. if error != .success {
  425. NCContentPresenter().showError(error: error)
  426. }
  427. self.loadDatasource(withLoadFolder: false)
  428. }
  429. }
  430. }
  431. // MARK: -
  432. class NCSelectCommandView: UIView {
  433. @IBOutlet weak var separatorView: UIView!
  434. @IBOutlet weak var createFolderButton: UIButton?
  435. @IBOutlet weak var selectButton: UIButton?
  436. @IBOutlet weak var copyButton: UIButton?
  437. @IBOutlet weak var moveButton: UIButton?
  438. @IBOutlet weak var overwriteSwitch: UISwitch?
  439. @IBOutlet weak var overwriteLabel: UILabel?
  440. @IBOutlet weak var separatorHeightConstraint: NSLayoutConstraint!
  441. var selectView: NCSelect?
  442. private let gradient: CAGradientLayer = CAGradientLayer()
  443. override func awakeFromNib() {
  444. separatorHeightConstraint.constant = 0.5
  445. separatorView.backgroundColor = .separator
  446. overwriteSwitch?.onTintColor = NCBrandColor.shared.brandElement
  447. overwriteLabel?.text = NSLocalizedString("_overwrite_", comment: "")
  448. selectButton?.layer.cornerRadius = 15
  449. selectButton?.layer.masksToBounds = true
  450. selectButton?.setTitle(NSLocalizedString("_select_", comment: ""), for: .normal)
  451. selectButton?.backgroundColor = NCBrandColor.shared.brandElement
  452. selectButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  453. selectButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  454. createFolderButton?.layer.cornerRadius = 15
  455. createFolderButton?.layer.masksToBounds = true
  456. createFolderButton?.setTitle(NSLocalizedString("_create_folder_", comment: ""), for: .normal)
  457. createFolderButton?.backgroundColor = NCBrandColor.shared.brandElement
  458. createFolderButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  459. createFolderButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  460. copyButton?.layer.cornerRadius = 15
  461. copyButton?.layer.masksToBounds = true
  462. copyButton?.setTitle(NSLocalizedString("_copy_", comment: ""), for: .normal)
  463. copyButton?.backgroundColor = NCBrandColor.shared.brandElement
  464. copyButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  465. copyButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  466. moveButton?.layer.cornerRadius = 15
  467. moveButton?.layer.masksToBounds = true
  468. moveButton?.setTitle(NSLocalizedString("_move_", comment: ""), for: .normal)
  469. moveButton?.backgroundColor = NCBrandColor.shared.brandElement
  470. moveButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  471. moveButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  472. }
  473. @IBAction func createFolderButtonPressed(_ sender: UIButton) {
  474. selectView?.createFolderButtonPressed(sender)
  475. }
  476. @IBAction func selectButtonPressed(_ sender: UIButton) {
  477. selectView?.selectButtonPressed(sender)
  478. }
  479. @IBAction func copyButtonPressed(_ sender: UIButton) {
  480. selectView?.copyButtonPressed(sender)
  481. }
  482. @IBAction func moveButtonPressed(_ sender: UIButton) {
  483. selectView?.moveButtonPressed(sender)
  484. }
  485. @IBAction func valueChangedSwitchOverwrite(_ sender: UISwitch) {
  486. selectView?.valueChangedSwitchOverwrite(sender)
  487. }
  488. }
  489. // MARK: - UIViewControllerRepresentable
  490. struct NCSelectViewControllerRepresentable: UIViewControllerRepresentable {
  491. typealias UIViewControllerType = UINavigationController
  492. var delegate: NCSelectDelegate
  493. func makeUIViewController(context: Context) -> UINavigationController {
  494. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  495. let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController
  496. let viewController = navigationController?.topViewController as? NCSelect
  497. viewController?.delegate = delegate
  498. viewController?.typeOfCommandView = .selectCreateFolder
  499. viewController?.includeDirectoryE2EEncryption = true
  500. return navigationController!
  501. }
  502. func updateUIViewController(_ uiViewController: UINavigationController, context: Context) { }
  503. }
  504. struct SelectView: UIViewControllerRepresentable {
  505. typealias UIViewControllerType = UINavigationController
  506. @Binding var serverUrl: String
  507. class Coordinator: NSObject, NCSelectDelegate {
  508. var parent: SelectView
  509. init(_ parent: SelectView) {
  510. self.parent = parent
  511. }
  512. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  513. if let serverUrl = serverUrl {
  514. self.parent.serverUrl = serverUrl
  515. }
  516. }
  517. }
  518. func makeUIViewController(context: Context) -> UINavigationController {
  519. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  520. let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController
  521. let viewController = navigationController?.topViewController as? NCSelect
  522. viewController?.delegate = context.coordinator
  523. viewController?.typeOfCommandView = .selectCreateFolder
  524. viewController?.includeDirectoryE2EEncryption = true
  525. return navigationController!
  526. }
  527. func updateUIViewController(_ uiViewController: UINavigationController, context: Context) { }
  528. func makeCoordinator() -> Coordinator {
  529. Coordinator(self)
  530. }
  531. }