NCSelect.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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 Foundation
  24. import NCCommunication
  25. @objc protocol NCSelectDelegate {
  26. @objc func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], cancel: Bool, overwrite: Bool, select: Bool, copy: Bool, move: Bool)
  27. }
  28. class NCSelect: UIViewController, UIGestureRecognizerDelegate, UIAdaptivePresentationControllerDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, NCEmptyDataSetDelegate {
  29. @IBOutlet fileprivate weak var collectionView: UICollectionView!
  30. @IBOutlet fileprivate weak var buttonCancel: UIBarButtonItem!
  31. private var selectCommandViewSelect: NCSelectCommandView?
  32. @objc enum selectType: Int {
  33. case select
  34. case selectCreateFolder
  35. case copyMove
  36. }
  37. // ------ external settings ------------------------------------
  38. @objc var delegate: NCSelectDelegate?
  39. @objc var typeOfCommandView: selectType = .select
  40. @objc var includeDirectoryE2EEncryption = false
  41. @objc var includeImages = false
  42. @objc var enableSelectFile = false
  43. @objc var type = ""
  44. @objc var items: [Any] = []
  45. /*
  46. @objc var selectFile = false
  47. @objc var hideButtonCreateFolder = false
  48. @objc var titleButtonDone = NSLocalizedString("_move_", comment: "")
  49. @objc var titleButtonDone1 = NSLocalizedString("_copy_", comment: "")
  50. @objc var isButtonDone1Hide = true
  51. @objc var isOverwriteHide = true
  52. */
  53. var titleCurrentFolder = NCBrandOptions.shared.brand
  54. var serverUrl = ""
  55. // -------------------------------------------------------------
  56. private var emptyDataSet: NCEmptyDataSet?
  57. private let keyLayout = NCGlobal.shared.layoutViewMove
  58. private var serverUrlPush = ""
  59. private var metadataTouch: tableMetadata?
  60. private var metadataFolder = tableMetadata()
  61. private var isEditMode = false
  62. private var networkInProgress = false
  63. private var selectOcId: [String] = []
  64. private var overwrite = false
  65. private var dataSource = NCDataSource()
  66. internal var richWorkspaceText: String?
  67. private var sort: String = ""
  68. private var ascending: Bool = true
  69. private var directoryOnTop: Bool = true
  70. private var layout = ""
  71. private var groupBy = ""
  72. private var titleButton = ""
  73. private var itemForLine = 0
  74. private var autoUploadFileName = ""
  75. private var autoUploadDirectory = ""
  76. private var listLayout: NCListLayout!
  77. private var gridLayout: NCGridLayout!
  78. private let headerHeight: CGFloat = 50
  79. private var headerRichWorkspaceHeight: CGFloat = 0
  80. private let footerHeight: CGFloat = 100
  81. private var shares: [tableShare]?
  82. private let refreshControl = UIRefreshControl()
  83. private var activeAccount: tableAccount!
  84. override func viewDidLoad() {
  85. super.viewDidLoad()
  86. self.navigationController?.navigationBar.prefersLargeTitles = true
  87. self.navigationController?.presentationController?.delegate = self
  88. activeAccount = NCManageDatabase.shared.getAccountActive()
  89. // Cell
  90. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  91. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  92. // Header
  93. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  94. // Footer
  95. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  96. collectionView.alwaysBounceVertical = true
  97. listLayout = NCListLayout()
  98. gridLayout = NCGridLayout()
  99. // Add Refresh Control
  100. collectionView.addSubview(refreshControl)
  101. refreshControl.tintColor = NCBrandColor.shared.brandText
  102. refreshControl.backgroundColor = NCBrandColor.shared.brandElement
  103. refreshControl.addTarget(self, action: #selector(loadDatasource), for: .valueChanged)
  104. // Empty
  105. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: 0, delegate: self)
  106. // Type of command view
  107. if typeOfCommandView == .select || typeOfCommandView == .selectCreateFolder {
  108. if typeOfCommandView == .select {
  109. selectCommandViewSelect = Bundle.main.loadNibNamed("NCSelectCommandViewSelect", owner: self, options: nil)?.first as? NCSelectCommandView
  110. } else {
  111. selectCommandViewSelect = Bundle.main.loadNibNamed("NCSelectCommandViewSelect+CreateFolder", owner: self, options: nil)?.first as? NCSelectCommandView
  112. }
  113. self.view.addSubview(selectCommandViewSelect!)
  114. selectCommandViewSelect?.selectView = self
  115. selectCommandViewSelect?.translatesAutoresizingMaskIntoConstraints = false
  116. selectCommandViewSelect?.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  117. selectCommandViewSelect?.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  118. selectCommandViewSelect?.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  119. selectCommandViewSelect?.heightAnchor.constraint(equalToConstant: 80).isActive = true
  120. }
  121. /*
  122. // title button
  123. buttonCancel.title = NSLocalizedString("_cancel_", comment: "")
  124. buttonCreateFolder.setTitle(NSLocalizedString("_create_folder_", comment: ""), for: .normal)
  125. overwriteLabel.text = NSLocalizedString("_overwrite_", comment: "")
  126. // button
  127. buttonCreateFolder.layer.cornerRadius = 15
  128. buttonCreateFolder.layer.masksToBounds = true
  129. buttonCreateFolder.layer.backgroundColor = NCBrandColor.shared.graySoft.withAlphaComponent(0.5).cgColor
  130. buttonCreateFolder.setTitleColor(.black, for: .normal)
  131. buttonDone.layer.cornerRadius = 15
  132. buttonDone.layer.masksToBounds = true
  133. buttonDone.layer.backgroundColor = NCBrandColor.shared.graySoft.withAlphaComponent(0.5).cgColor
  134. buttonDone.setTitleColor(.black, for: .normal)
  135. buttonDone1.layer.cornerRadius = 15
  136. buttonDone1.layer.masksToBounds = true
  137. buttonDone1.layer.backgroundColor = NCBrandColor.shared.graySoft.withAlphaComponent(0.5).cgColor
  138. buttonDone1.setTitleColor(.black, for: .normal)
  139. */
  140. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  141. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  142. changeTheming()
  143. }
  144. override func viewWillAppear(_ animated: Bool) {
  145. super.viewWillAppear(animated)
  146. self.navigationItem.title = titleCurrentFolder
  147. /*
  148. buttonDone.setTitle(titleButtonDone, for: .normal)
  149. buttonDone1.setTitle(titleButtonDone1, for: .normal)
  150. buttonDone1.isHidden = isButtonDone1Hide
  151. overwriteSwitch.isOn = overwrite
  152. overwriteView.isHidden = isOverwriteHide
  153. if selectFile {
  154. buttonDone.isHidden = true
  155. }
  156. if hideButtonCreateFolder {
  157. buttonCreateFolder.isHidden = true
  158. }
  159. */
  160. // set the serverUrl
  161. if serverUrl == "" {
  162. serverUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: activeAccount.urlBase, account: activeAccount.account)
  163. }
  164. // get auto upload folder
  165. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  166. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: activeAccount.urlBase, account: activeAccount.account)
  167. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: keyLayout,serverUrl: serverUrl)
  168. gridLayout.itemForLine = CGFloat(itemForLine)
  169. if layout == NCGlobal.shared.layoutList {
  170. collectionView.collectionViewLayout = listLayout
  171. } else {
  172. collectionView.collectionViewLayout = gridLayout
  173. }
  174. loadDatasource(withLoadFolder: true)
  175. shares = NCManageDatabase.shared.getTableShares(account: activeAccount.account, serverUrl: serverUrl)
  176. }
  177. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  178. super.viewWillTransition(to: size, with: coordinator)
  179. coordinator.animate(alongsideTransition: nil) { _ in
  180. self.collectionView?.collectionViewLayout.invalidateLayout()
  181. }
  182. }
  183. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  184. super.traitCollectionDidChange(previousTraitCollection)
  185. if traitCollection.userInterfaceStyle == .dark {
  186. } else {
  187. }
  188. }
  189. @objc func changeTheming() {
  190. view.backgroundColor = NCBrandColor.shared.backgroundView
  191. collectionView.backgroundColor = NCBrandColor.shared.backgroundView
  192. collectionView.reloadData()
  193. refreshControl.backgroundColor = NCBrandColor.shared.backgroundView
  194. //toolbar.backgroundColor = NCBrandColor.shared.tabBar
  195. //separator.backgroundColor = NCBrandColor.shared.graySoft
  196. }
  197. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  198. delegate?.dismissSelect(serverUrl: nil, metadata: nil, type: type, items: items, cancel: true, overwrite: overwrite, select: false, copy: false, move: false)
  199. }
  200. // MARK: - Empty
  201. func emptyDataSetView(_ view: NCEmptyView) {
  202. if networkInProgress {
  203. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  204. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  205. view.emptyDescription.text = ""
  206. } else {
  207. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  208. if includeImages {
  209. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  210. } else {
  211. view.emptyTitle.text = NSLocalizedString("_files_no_folders_", comment: "")
  212. }
  213. view.emptyDescription.text = ""
  214. }
  215. }
  216. // MARK: ACTION
  217. @IBAction func actionCancel(_ sender: Any) {
  218. delegate?.dismissSelect(serverUrl: nil, metadata: nil, type: type, items: items, cancel: true, overwrite: overwrite, select: false, copy: false, move: false)
  219. self.dismiss(animated: true, completion: nil)
  220. }
  221. func selectButtonPressed(_ sender: UIButton) {
  222. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadataFolder, type: type, items: items, cancel: false, overwrite: overwrite, select: true, copy: false, move: false)
  223. self.dismiss(animated: true, completion: nil)
  224. }
  225. func createFolderButtonPressed(_ sender: UIButton) {
  226. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_", comment: ""), message:"", preferredStyle: .alert)
  227. alertController.addTextField { (textField) in
  228. textField.autocapitalizationType = UITextAutocapitalizationType.words
  229. }
  230. let actionSave = UIAlertAction(title: NSLocalizedString("_save_", comment: ""), style: .default) { (action:UIAlertAction) in
  231. if let fileName = alertController.textFields?.first?.text {
  232. self.createFolder(with: fileName)
  233. }
  234. }
  235. let actionCancel = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  236. print("You've pressed cancel button")
  237. }
  238. alertController.addAction(actionSave)
  239. alertController.addAction(actionCancel)
  240. self.present(alertController, animated: true, completion:nil)
  241. }
  242. @IBAction func valueChangedSwitchOverwrite(_ sender: Any) {
  243. if let viewControllers = self.navigationController?.viewControllers {
  244. for viewController in viewControllers {
  245. if viewController is NCSelect {
  246. //(viewController as! NCSelect).overwrite = overwriteSwitch.isOn
  247. }
  248. }
  249. }
  250. }
  251. // MARK: TAP EVENT
  252. func tapSwitchHeader(sender: Any) {
  253. if collectionView.collectionViewLayout == gridLayout {
  254. // list layout
  255. UIView.animate(withDuration: 0.0, animations: {
  256. self.collectionView.collectionViewLayout.invalidateLayout()
  257. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  258. self.collectionView.reloadData()
  259. })
  260. })
  261. layout = NCGlobal.shared.layoutList
  262. } else {
  263. // grid layout
  264. UIView.animate(withDuration: 0.0, animations: {
  265. self.collectionView.collectionViewLayout.invalidateLayout()
  266. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  267. self.collectionView.reloadData()
  268. })
  269. })
  270. layout = NCGlobal.shared.layoutGrid
  271. }
  272. }
  273. func tapOrderHeader(sender: Any) {
  274. let sortMenu = NCSortMenu()
  275. sortMenu.toggleMenu(viewController: self, key: keyLayout, sortButton: sender as? UIButton, serverUrl: serverUrl)
  276. }
  277. func tapMoreHeader(sender: Any) {
  278. }
  279. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  280. }
  281. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  282. }
  283. func tapShareListItem(with objectId: String, sender: Any) {
  284. }
  285. func tapRichWorkspace(sender: Any) {
  286. }
  287. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  288. }
  289. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  290. }
  291. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  292. }
  293. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  294. }
  295. }
  296. // MARK: - Collection View
  297. extension NCSelect: UICollectionViewDelegate {
  298. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  299. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  300. if isEditMode {
  301. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  302. selectOcId.remove(at: index)
  303. } else {
  304. selectOcId.append(metadata.ocId)
  305. }
  306. collectionView.reloadItems(at: [indexPath])
  307. return
  308. }
  309. if metadata.directory {
  310. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  311. guard let visualController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect else { return }
  312. self.serverUrlPush = serverUrlPush
  313. self.metadataTouch = metadata
  314. visualController.delegate = delegate
  315. visualController.typeOfCommandView = typeOfCommandView
  316. visualController.includeDirectoryE2EEncryption = includeDirectoryE2EEncryption
  317. visualController.includeImages = includeImages
  318. visualController.enableSelectFile = enableSelectFile
  319. visualController.type = type
  320. visualController.overwrite = overwrite
  321. visualController.items = items
  322. visualController.titleCurrentFolder = metadataTouch!.fileNameView
  323. visualController.serverUrl = serverUrlPush
  324. self.navigationController?.pushViewController(visualController, animated: true)
  325. } else {
  326. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadata, type: type, items: items, cancel: false, overwrite: overwrite, select: true, copy: false, move: false)
  327. self.dismiss(animated: true, completion: nil)
  328. }
  329. }
  330. }
  331. extension NCSelect: UICollectionViewDataSource {
  332. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  333. if kind == UICollectionView.elementKindSectionHeader {
  334. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  335. if collectionView.collectionViewLayout == gridLayout {
  336. header.buttonSwitch.setImage(UIImage.init(named: "switchList")?.image(color: NCBrandColor.shared.icon, size: 25), for: .normal)
  337. } else {
  338. header.buttonSwitch.setImage(UIImage.init(named: "switchGrid")?.image(color: NCBrandColor.shared.icon, size: 25), for: .normal)
  339. }
  340. header.delegate = self
  341. header.setStatusButton(count: dataSource.metadatas.count)
  342. header.setTitleSorted(datasourceTitleButton: titleButton)
  343. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  344. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  345. return header
  346. } else {
  347. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  348. let info = dataSource.getFilesInformation()
  349. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  350. return footer
  351. }
  352. }
  353. func numberOfSections(in collectionView: UICollectionView) -> Int {
  354. return 1
  355. }
  356. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  357. let numberOfItems = dataSource.numberOfItems()
  358. emptyDataSet?.numberOfItemsInSection(numberOfItems, section:section)
  359. return numberOfItems
  360. }
  361. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  362. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  363. if layout == NCGlobal.shared.layoutList {
  364. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  365. } else {
  366. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  367. }
  368. }
  369. var tableShare: tableShare?
  370. var isShare = false
  371. var isMounted = false
  372. // Download preview
  373. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: activeAccount.urlBase, view: collectionView, indexPath: indexPath)
  374. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionShared)
  375. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder.permissions.contains(NCGlobal.shared.permissionMounted)
  376. if dataSource.metadataShare[metadata.ocId] != nil {
  377. tableShare = dataSource.metadataShare[metadata.ocId]
  378. }
  379. // LAYOUT LIST
  380. if layout == NCGlobal.shared.layoutList {
  381. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  382. cell.delegate = self
  383. cell.objectId = metadata.ocId
  384. cell.indexPath = indexPath
  385. cell.labelTitle.text = metadata.fileNameView
  386. cell.labelTitle.textColor = NCBrandColor.shared.textView
  387. cell.separator.backgroundColor = NCBrandColor.shared.separator
  388. cell.imageSelect.image = nil
  389. cell.imageStatus.image = nil
  390. cell.imageLocal.image = nil
  391. cell.imageFavorite.image = nil
  392. cell.imageShared.image = nil
  393. cell.imageMore.image = nil
  394. cell.imageItem.image = nil
  395. cell.imageItem.backgroundColor = nil
  396. cell.progressView.progress = 0.0
  397. if metadata.directory {
  398. if metadata.e2eEncrypted {
  399. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  400. } else if isShare {
  401. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  402. } else if (tableShare != nil && tableShare?.shareType != 3) {
  403. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  404. } else if (tableShare != nil && tableShare?.shareType == 3) {
  405. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  406. } else if metadata.mountType == "group" {
  407. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  408. } else if isMounted {
  409. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  410. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  411. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  412. } else {
  413. cell.imageItem.image = NCBrandColor.cacheImages.folder
  414. }
  415. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  416. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  417. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, lockServerUrl))
  418. // Local image: offline
  419. if tableDirectory != nil && tableDirectory!.offline {
  420. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  421. }
  422. } else {
  423. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  424. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  425. } else {
  426. if metadata.hasPreview {
  427. cell.imageItem.backgroundColor = .lightGray
  428. } else {
  429. if metadata.iconName.count > 0 {
  430. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  431. } else {
  432. cell.imageItem.image = NCBrandColor.cacheImages.file
  433. }
  434. }
  435. }
  436. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  437. // image local
  438. if dataSource.metadataOffLine.contains(metadata.ocId) {
  439. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  440. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  441. cell.imageLocal.image = NCBrandColor.cacheImages.local
  442. }
  443. }
  444. // image Favorite
  445. if metadata.favorite {
  446. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  447. }
  448. // Share image
  449. if (isShare) {
  450. cell.imageShared.image = NCBrandColor.cacheImages.shared
  451. } else if (tableShare != nil && tableShare?.shareType == 3) {
  452. cell.imageShared.image = NCBrandColor.cacheImages.shareByLink
  453. } else if (tableShare != nil && tableShare?.shareType != 3) {
  454. cell.imageShared.image = NCBrandColor.cacheImages.shared
  455. } else {
  456. cell.imageShared.image = NCBrandColor.cacheImages.canShare
  457. }
  458. if metadata.ownerId.count > 0 && metadata.ownerId != activeAccount.userId {
  459. let fileNameUser = String(CCUtility.getDirectoryUserData()) + "/" + String(CCUtility.getStringUser(activeAccount.user, urlBase: activeAccount.urlBase)) + "-" + metadata.ownerId + ".png"
  460. if FileManager.default.fileExists(atPath: fileNameUser) {
  461. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  462. } else {
  463. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  464. if errorCode == 0 && account == self.activeAccount.account {
  465. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  466. }
  467. }
  468. }
  469. }
  470. cell.imageSelect.isHidden = true
  471. cell.backgroundView = nil
  472. cell.hideButtonMore(true)
  473. cell.hideButtonShare(true)
  474. cell.selectMode(false)
  475. // Live Photo
  476. if metadata.livePhoto {
  477. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  478. }
  479. // Remove last separator
  480. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  481. cell.separator.isHidden = true
  482. } else {
  483. cell.separator.isHidden = false
  484. }
  485. return cell
  486. }
  487. // LAYOUT GRID
  488. if layout == NCGlobal.shared.layoutGrid {
  489. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  490. cell.delegate = self
  491. cell.objectId = metadata.ocId
  492. cell.indexPath = indexPath
  493. cell.labelTitle.text = metadata.fileNameView
  494. cell.labelTitle.textColor = NCBrandColor.shared.textView
  495. cell.imageSelect.image = nil
  496. cell.imageStatus.image = nil
  497. cell.imageLocal.image = nil
  498. cell.imageFavorite.image = nil
  499. cell.imageItem.image = nil
  500. cell.imageItem.backgroundColor = nil
  501. cell.progressView.progress = 0.0
  502. if metadata.directory {
  503. if metadata.e2eEncrypted {
  504. cell.imageItem.image = NCBrandColor.cacheImages.folderEncrypted
  505. } else if isShare {
  506. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  507. } else if (tableShare != nil && tableShare!.shareType != 3) {
  508. cell.imageItem.image = NCBrandColor.cacheImages.folderSharedWithMe
  509. } else if (tableShare != nil && tableShare!.shareType == 3) {
  510. cell.imageItem.image = NCBrandColor.cacheImages.folderPublic
  511. } else if metadata.mountType == "group" {
  512. cell.imageItem.image = NCBrandColor.cacheImages.folderGroup
  513. } else if isMounted {
  514. cell.imageItem.image = NCBrandColor.cacheImages.folderExternal
  515. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  516. cell.imageItem.image = NCBrandColor.cacheImages.folderAutomaticUpload
  517. } else {
  518. cell.imageItem.image = NCBrandColor.cacheImages.folder
  519. }
  520. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  521. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account, lockServerUrl))
  522. // Local image: offline
  523. if tableDirectory != nil && tableDirectory!.offline {
  524. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  525. }
  526. } else {
  527. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  528. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  529. } else {
  530. if metadata.hasPreview {
  531. cell.imageItem.backgroundColor = .lightGray
  532. } else {
  533. if metadata.iconName.count > 0 {
  534. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  535. } else {
  536. cell.imageItem.image = NCBrandColor.cacheImages.file
  537. }
  538. }
  539. }
  540. // image Local
  541. if dataSource.metadataOffLine.contains(metadata.ocId) {
  542. cell.imageLocal.image = NCBrandColor.cacheImages.offlineFlag
  543. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  544. cell.imageLocal.image = NCBrandColor.cacheImages.local
  545. }
  546. }
  547. // image Favorite
  548. if metadata.favorite {
  549. cell.imageFavorite.image = NCBrandColor.cacheImages.favorite
  550. }
  551. cell.imageSelect.isHidden = true
  552. cell.backgroundView = nil
  553. cell.hideButtonMore(true)
  554. // Live Photo
  555. if metadata.livePhoto {
  556. cell.imageStatus.image = NCBrandColor.cacheImages.livePhoto
  557. }
  558. return cell
  559. }
  560. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  561. }
  562. }
  563. extension NCSelect: UICollectionViewDelegateFlowLayout {
  564. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  565. headerRichWorkspaceHeight = 0
  566. if let richWorkspaceText = richWorkspaceText {
  567. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  568. if trimmed.count > 0 {
  569. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  570. }
  571. }
  572. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  573. }
  574. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  575. return CGSize(width: collectionView.frame.width, height: footerHeight)
  576. }
  577. }
  578. // MARK: - NC API & Algorithm
  579. extension NCSelect {
  580. @objc func reloadDataSource() {
  581. loadDatasource(withLoadFolder: false)
  582. }
  583. @objc func loadDatasource(withLoadFolder: Bool) {
  584. var predicate: NSPredicate?
  585. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: keyLayout, serverUrl: serverUrl)
  586. if includeDirectoryE2EEncryption {
  587. if includeImages {
  588. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND (directory == true OR typeFile == 'image')", activeAccount.account, serverUrl)
  589. } else {
  590. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", activeAccount.account, serverUrl)
  591. }
  592. } else {
  593. if includeImages {
  594. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND (directory == true OR typeFile == 'image')", activeAccount.account, serverUrl)
  595. } else {
  596. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND directory == true", activeAccount.account, serverUrl)
  597. }
  598. }
  599. let metadatasSource = NCManageDatabase.shared.getMetadatas(predicate: predicate!)
  600. self.dataSource = NCDataSource.init(metadatasSource: metadatasSource, sort: sort, ascending: ascending, directoryOnTop: directoryOnTop, favoriteOnTop: true, filterLivePhoto: true)
  601. if withLoadFolder {
  602. loadFolder()
  603. } else {
  604. self.refreshControl.endRefreshing()
  605. }
  606. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", activeAccount.account,serverUrl))
  607. richWorkspaceText = directory?.richWorkspace
  608. collectionView.reloadData()
  609. }
  610. func createFolder(with fileName: String) {
  611. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: activeAccount.account, urlBase: activeAccount.urlBase) { (errorCode, errorDescription) in
  612. if errorCode == 0 {
  613. self.loadDatasource(withLoadFolder: true)
  614. } else {
  615. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  616. }
  617. }
  618. }
  619. func loadFolder() {
  620. networkInProgress = true
  621. collectionView.reloadData()
  622. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: activeAccount.account) { (_, _, _, _, _, errorCode, errorDescription) in
  623. if errorCode != 0 {
  624. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  625. }
  626. self.networkInProgress = false
  627. self.loadDatasource(withLoadFolder: false)
  628. }
  629. }
  630. }
  631. class NCSelectCommandView: UIView {
  632. @IBOutlet weak var separatorView: UIView!
  633. @IBOutlet weak var createFolderButton: UIButton?
  634. @IBOutlet weak var selectButton: UIButton?
  635. @IBOutlet weak var separatorHeightConstraint: NSLayoutConstraint!
  636. var selectView: NCSelect?
  637. private let gradient: CAGradientLayer = CAGradientLayer()
  638. override func awakeFromNib() {
  639. separatorHeightConstraint.constant = 0.5
  640. separatorView.backgroundColor = NCBrandColor.shared.separator
  641. selectButton?.layer.cornerRadius = 15
  642. selectButton?.layer.masksToBounds = true
  643. selectButton?.layer.backgroundColor = NCBrandColor.shared.graySoft.withAlphaComponent(0.5).cgColor
  644. selectButton?.setTitleColor(.black, for: .normal)
  645. selectButton?.setTitle(NSLocalizedString("_select_", comment: ""), for: .normal)
  646. createFolderButton?.layer.cornerRadius = 15
  647. createFolderButton?.layer.masksToBounds = true
  648. createFolderButton?.layer.backgroundColor = NCBrandColor.shared.graySoft.withAlphaComponent(0.5).cgColor
  649. createFolderButton?.setTitleColor(.black, for: .normal)
  650. createFolderButton?.setTitle(NSLocalizedString("_create_folder_", comment: ""), for: .normal)
  651. }
  652. @IBAction func createFolderButtonPressed(_ sender: UIButton) {
  653. selectView?.createFolderButtonPressed(sender)
  654. }
  655. @IBAction func selectButtonPressed(_ sender: UIButton) {
  656. selectView?.selectButtonPressed(sender)
  657. }
  658. }