NCSelect.swift 36 KB

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