NCSelect.swift 36 KB

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