NCSelect.swift 35 KB

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