NCSelect.swift 36 KB

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