NCSelect.swift 35 KB

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