NCSelect.swift 36 KB

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