NCSelect.swift 36 KB

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