NCSelect.swift 30 KB

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