NCSelect.swift 36 KB

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