NCSelect.swift 39 KB

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