NCSelect.swift 38 KB

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