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