NCSelect.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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, 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. 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 emptyDataSet: NCEmptyDataSet?
  56. private var serverUrlPush = ""
  57. private var metadataFolder = tableMetadata()
  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 viewDidAppear(_ animated: Bool) {
  123. super.viewDidAppear(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 self.dataSourceTask?.state == .running {
  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, 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, 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, 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.titleCurrentFolder = metadata.fileNameView
  206. viewController.serverUrl = serverUrlPush
  207. self.navigationController?.pushViewController(viewController, animated: true)
  208. }
  209. }
  210. // MARK: - Collection View
  211. extension NCSelect: UICollectionViewDelegate {
  212. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  213. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  214. if metadata.directory {
  215. pushMetadata(metadata)
  216. } else {
  217. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadata, type: type, items: items, overwrite: overwrite, copy: false, move: false)
  218. self.dismiss(animated: true, completion: nil)
  219. }
  220. }
  221. }
  222. extension NCSelect: UICollectionViewDataSource {
  223. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  224. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  225. // Thumbnail
  226. if !metadata.directory {
  227. if FileManager().fileExists(atPath: utilityFileSystem.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  228. (cell as? NCCellProtocol)?.filePreviewImageView?.image = UIImage(contentsOfFile: utilityFileSystem.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  229. } else {
  230. if metadata.iconName.isEmpty {
  231. (cell as? NCCellProtocol)?.filePreviewImageView?.image = NCImageCache.images.file
  232. } else {
  233. (cell as? NCCellProtocol)?.filePreviewImageView?.image = UIImage(named: metadata.iconName)
  234. }
  235. if metadata.hasPreview && metadata.status == NCGlobal.shared.metadataStatusNormal && (!utilityFileSystem.fileProviderStoragePreviewIconExists(metadata.ocId, etag: metadata.etag)) {
  236. for case let operation as NCCollectionViewDownloadThumbnail in NCNetworking.shared.downloadThumbnailQueue.operations where operation.metadata.ocId == metadata.ocId { return }
  237. NCNetworking.shared.downloadThumbnailQueue.addOperation(NCCollectionViewDownloadThumbnail(metadata: metadata, cell: (cell as? NCCellProtocol), collectionView: collectionView))
  238. }
  239. }
  240. }
  241. // Avatar
  242. if !metadata.ownerId.isEmpty,
  243. metadata.ownerId != activeAccount.userId,
  244. activeAccount.account == metadata.account,
  245. let cell = cell as? NCCellProtocol {
  246. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  247. NCNetworking.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.fileAvatarImageView)
  248. }
  249. }
  250. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  251. }
  252. func numberOfSections(in collectionView: UICollectionView) -> Int {
  253. return dataSource.numberOfSections()
  254. }
  255. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  256. let numberOfItems = dataSource.numberOfItemsInSection(section)
  257. emptyDataSet?.numberOfItemsInSection(numberOfItems, section: section)
  258. return numberOfItems
  259. }
  260. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  261. guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as? NCListCell,
  262. let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return UICollectionViewCell() }
  263. var isShare = false
  264. var isMounted = false
  265. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  266. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  267. cell.listCellDelegate = self
  268. cell.fileObjectId = metadata.ocId
  269. cell.fileUser = metadata.ownerId
  270. cell.labelTitle.text = metadata.fileNameView
  271. cell.labelTitle.textColor = .label
  272. cell.imageSelect.image = nil
  273. cell.imageStatus.image = nil
  274. cell.imageLocal.image = nil
  275. cell.imageFavorite.image = nil
  276. cell.imageShared.image = nil
  277. cell.imageMore.image = nil
  278. cell.imageItem.image = nil
  279. cell.imageItem.backgroundColor = nil
  280. cell.progressView.progress = 0.0
  281. if metadata.directory {
  282. if metadata.e2eEncrypted {
  283. cell.imageItem.image = NCImageCache.images.folderEncrypted
  284. } else if isShare {
  285. cell.imageItem.image = NCImageCache.images.folderSharedWithMe
  286. } else if !metadata.shareType.isEmpty {
  287. metadata.shareType.contains(3) ?
  288. (cell.imageItem.image = NCImageCache.images.folderPublic) :
  289. (cell.imageItem.image = NCImageCache.images.folderSharedWithMe)
  290. } else if metadata.mountType == "group" {
  291. cell.imageItem.image = NCImageCache.images.folderGroup
  292. } else if isMounted {
  293. cell.imageItem.image = NCImageCache.images.folderExternal
  294. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  295. cell.imageItem.image = NCImageCache.images.folderAutomaticUpload
  296. } else {
  297. cell.imageItem.image = NCImageCache.images.folder
  298. }
  299. cell.imageItem.image = cell.imageItem.image?.colorizeFolder(metadata: metadata)
  300. cell.labelInfo.text = utility.dateDiff(metadata.date as Date)
  301. } else {
  302. cell.labelInfo.text = utility.dateDiff(metadata.date as Date) + " · " + utilityFileSystem.transformedSize(metadata.size)
  303. // image local
  304. if NCManageDatabase.shared.getTableLocalFile(ocId: metadata.ocId) != nil {
  305. cell.imageLocal.image = NCImageCache.images.offlineFlag
  306. } else if utilityFileSystem.fileProviderStorageExists(metadata) {
  307. cell.imageLocal.image = NCImageCache.images.local
  308. }
  309. }
  310. // image Favorite
  311. if metadata.favorite {
  312. cell.imageFavorite.image = NCImageCache.images.favorite
  313. }
  314. cell.imageSelect.isHidden = true
  315. cell.backgroundView = nil
  316. cell.hideButtonMore(true)
  317. cell.hideButtonShare(true)
  318. cell.selectMode(false)
  319. // Live Photo
  320. if metadata.isLivePhoto {
  321. cell.imageStatus.image = NCImageCache.images.livePhoto
  322. }
  323. // Remove last separator
  324. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  325. cell.separator.isHidden = true
  326. } else {
  327. cell.separator.isHidden = false
  328. }
  329. // Add TAGS
  330. cell.setTags(tags: Array(metadata.tags))
  331. return cell
  332. }
  333. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  334. if kind == UICollectionView.elementKindSectionHeader {
  335. guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as? NCSectionHeaderMenu else { return UICollectionReusableView() }
  336. let (_, heightHeaderRichWorkspace, _) = getHeaderHeight(section: indexPath.section)
  337. self.headerMenu = header
  338. header.delegate = self
  339. // header.setButtonsView(height: 0)
  340. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  341. header.setRichWorkspaceText(richWorkspaceText)
  342. header.setViewTransfer(isHidden: true)
  343. return header
  344. } else {
  345. guard let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as? NCSectionFooter else { return UICollectionReusableView() }
  346. let sections = dataSource.numberOfSections()
  347. let section = indexPath.section
  348. footer.setTitleLabel("")
  349. footer.separatorIsHidden(true)
  350. if sections == 1 || section == sections - 1 {
  351. let info = dataSource.getFooterInformationAllMetadatas()
  352. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  353. } else {
  354. footer.separatorIsHidden(false)
  355. }
  356. return footer
  357. }
  358. }
  359. }
  360. extension NCSelect: UICollectionViewDelegateFlowLayout {
  361. func getHeaderHeight(section: Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  362. var headerRichWorkspace: CGFloat = 0
  363. if let richWorkspaceText = richWorkspaceText {
  364. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  365. // swiftlint:disable empty_count
  366. if trimmed.count > 0 {
  367. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  368. }
  369. // swiftlint:enable empty_count
  370. }
  371. return (0, headerRichWorkspace, 0)
  372. }
  373. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  374. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  375. let heightHeader = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  376. return CGSize(width: collectionView.frame.width, height: heightHeader)
  377. }
  378. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  379. let sections = dataSource.numberOfSections()
  380. if section == sections - 1 {
  381. return CGSize(width: collectionView.frame.width, height: NCGlobal.shared.endHeightFooter)
  382. } else {
  383. return CGSize(width: collectionView.frame.width, height: NCGlobal.shared.heightFooter)
  384. }
  385. }
  386. }
  387. // MARK: -
  388. extension NCSelect {
  389. @objc func reloadDataSource() {
  390. loadDatasource(withLoadFolder: false)
  391. }
  392. @objc func loadDatasource(withLoadFolder: Bool) {
  393. var predicate: NSPredicate?
  394. if includeDirectoryE2EEncryption {
  395. if includeImages {
  396. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND (directory == true OR classFile == 'image')", activeAccount.account, serverUrl)
  397. } else {
  398. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl)
  399. }
  400. } else {
  401. if includeImages {
  402. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND (directory == true OR classFile == 'image')", activeAccount.account, serverUrl)
  403. } else if enableSelectFile {
  404. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false", activeAccount.account, serverUrl)
  405. } else {
  406. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND directory == true", activeAccount.account, serverUrl)
  407. }
  408. }
  409. let metadatas = NCManageDatabase.shared.getMetadatas(predicate: predicate!)
  410. self.dataSource = NCDataSource(metadatas: metadatas,
  411. account: activeAccount.account,
  412. sort: "fileName",
  413. ascending: true,
  414. directoryOnTop: true,
  415. favoriteOnTop: true,
  416. groupByField: "none")
  417. if withLoadFolder {
  418. loadFolder()
  419. }
  420. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, serverUrl))
  421. richWorkspaceText = directory?.richWorkspace
  422. DispatchQueue.main.async {
  423. self.collectionView.reloadData()
  424. }
  425. }
  426. func loadFolder() {
  427. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { task in
  428. self.dataSourceTask = task
  429. self.collectionView.reloadData()
  430. } completion: { _, _, _, _, _, error in
  431. if error != .success {
  432. NCContentPresenter().showError(error: error)
  433. }
  434. self.loadDatasource(withLoadFolder: false)
  435. }
  436. }
  437. }
  438. // MARK: -
  439. class NCSelectCommandView: UIView {
  440. @IBOutlet weak var separatorView: UIView!
  441. @IBOutlet weak var createFolderButton: UIButton?
  442. @IBOutlet weak var selectButton: UIButton?
  443. @IBOutlet weak var copyButton: UIButton?
  444. @IBOutlet weak var moveButton: UIButton?
  445. @IBOutlet weak var overwriteSwitch: UISwitch?
  446. @IBOutlet weak var overwriteLabel: UILabel?
  447. @IBOutlet weak var separatorHeightConstraint: NSLayoutConstraint!
  448. var selectView: NCSelect?
  449. private let gradient: CAGradientLayer = CAGradientLayer()
  450. override func awakeFromNib() {
  451. separatorHeightConstraint.constant = 0.5
  452. separatorView.backgroundColor = .separator
  453. overwriteSwitch?.onTintColor = NCBrandColor.shared.brand
  454. overwriteLabel?.text = NSLocalizedString("_overwrite_", comment: "")
  455. selectButton?.layer.cornerRadius = 15
  456. selectButton?.layer.masksToBounds = true
  457. selectButton?.setTitle(NSLocalizedString("_select_", comment: ""), for: .normal)
  458. selectButton?.backgroundColor = NCBrandColor.shared.brand
  459. selectButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  460. selectButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  461. createFolderButton?.layer.cornerRadius = 15
  462. createFolderButton?.layer.masksToBounds = true
  463. createFolderButton?.setTitle(NSLocalizedString("_create_folder_", comment: ""), for: .normal)
  464. createFolderButton?.backgroundColor = NCBrandColor.shared.brand
  465. createFolderButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  466. createFolderButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  467. copyButton?.layer.cornerRadius = 15
  468. copyButton?.layer.masksToBounds = true
  469. copyButton?.setTitle(NSLocalizedString("_copy_", comment: ""), for: .normal)
  470. copyButton?.backgroundColor = NCBrandColor.shared.brand
  471. copyButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  472. copyButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  473. moveButton?.layer.cornerRadius = 15
  474. moveButton?.layer.masksToBounds = true
  475. moveButton?.setTitle(NSLocalizedString("_move_", comment: ""), for: .normal)
  476. moveButton?.backgroundColor = NCBrandColor.shared.brand
  477. moveButton?.setTitleColor(UIColor(white: 1, alpha: 0.3), for: .highlighted)
  478. moveButton?.setTitleColor(NCBrandColor.shared.brandText, for: .normal)
  479. }
  480. @IBAction func createFolderButtonPressed(_ sender: UIButton) {
  481. selectView?.createFolderButtonPressed(sender)
  482. }
  483. @IBAction func selectButtonPressed(_ sender: UIButton) {
  484. selectView?.selectButtonPressed(sender)
  485. }
  486. @IBAction func copyButtonPressed(_ sender: UIButton) {
  487. selectView?.copyButtonPressed(sender)
  488. }
  489. @IBAction func moveButtonPressed(_ sender: UIButton) {
  490. selectView?.moveButtonPressed(sender)
  491. }
  492. @IBAction func valueChangedSwitchOverwrite(_ sender: UISwitch) {
  493. selectView?.valueChangedSwitchOverwrite(sender)
  494. }
  495. }
  496. // MARK: - UIViewControllerRepresentable
  497. struct NCSelectViewControllerRepresentable: UIViewControllerRepresentable {
  498. typealias UIViewControllerType = UINavigationController
  499. var delegate: NCSelectDelegate
  500. func makeUIViewController(context: Context) -> UINavigationController {
  501. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  502. let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController
  503. let viewController = navigationController?.topViewController as? NCSelect
  504. viewController?.delegate = delegate
  505. viewController?.typeOfCommandView = .selectCreateFolder
  506. viewController?.includeDirectoryE2EEncryption = true
  507. return navigationController!
  508. }
  509. func updateUIViewController(_ uiViewController: UINavigationController, context: Context) { }
  510. }
  511. struct SelectView: UIViewControllerRepresentable {
  512. typealias UIViewControllerType = UINavigationController
  513. @Binding var serverUrl: String
  514. class Coordinator: NSObject, NCSelectDelegate {
  515. var parent: SelectView
  516. init(_ parent: SelectView) {
  517. self.parent = parent
  518. }
  519. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  520. if let serverUrl = serverUrl {
  521. self.parent.serverUrl = serverUrl
  522. }
  523. }
  524. }
  525. func makeUIViewController(context: Context) -> UINavigationController {
  526. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  527. let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController
  528. let viewController = navigationController?.topViewController as? NCSelect
  529. viewController?.delegate = context.coordinator
  530. viewController?.typeOfCommandView = .selectCreateFolder
  531. viewController?.includeDirectoryE2EEncryption = true
  532. return navigationController!
  533. }
  534. func updateUIViewController(_ uiViewController: UINavigationController, context: Context) { }
  535. func makeCoordinator() -> Coordinator {
  536. Coordinator(self)
  537. }
  538. }