NCSelect.swift 36 KB

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