NCSelect.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. //
  2. // NCSelect.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 06/11/2018.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. import NCCommunication
  25. @objc protocol NCSelectDelegate {
  26. @objc func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, array: [Any], buttonType: String, overwrite: Bool)
  27. }
  28. class NCSelect: UIViewController, UIGestureRecognizerDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
  29. @IBOutlet fileprivate weak var collectionView: UICollectionView!
  30. @IBOutlet fileprivate weak var toolbar: UIView!
  31. @IBOutlet fileprivate weak var overwriteView: UIView!
  32. @IBOutlet fileprivate weak var buttonCancel: UIBarButtonItem!
  33. @IBOutlet fileprivate weak var buttonCreateFolder: UIButton!
  34. @IBOutlet fileprivate weak var buttonDone: UIButton!
  35. @IBOutlet fileprivate weak var buttonDone1: UIButton!
  36. @IBOutlet fileprivate weak var overwriteSwitch: UISwitch!
  37. @IBOutlet fileprivate weak var overwriteLabel: UILabel!
  38. @IBOutlet fileprivate weak var toolBarTop: NSLayoutConstraint!
  39. // ------ external settings ------------------------------------
  40. @objc var delegate: NCSelectDelegate?
  41. @objc var hideButtonCreateFolder = false
  42. @objc var selectFile = false
  43. @objc var includeDirectoryE2EEncryption = false
  44. @objc var includeImages = false
  45. @objc var type = ""
  46. @objc var titleButtonDone = NSLocalizedString("_move_", comment: "")
  47. @objc var titleButtonDone1 = NSLocalizedString("_copy_", comment: "")
  48. @objc var isButtonDone1Hide = true
  49. @objc var isOverwriteHide = true
  50. @objc var array: [Any] = []
  51. var titleCurrentFolder = NCBrandOptions.sharedInstance.brand
  52. var serverUrl = ""
  53. // -------------------------------------------------------------
  54. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  55. private let keyLayout = k_layout_view_move
  56. private var serverUrlPush = ""
  57. private var metadataTouch: tableMetadata?
  58. private var metadataFolder = tableMetadata()
  59. private var isEditMode = false
  60. private var networkInProgress = false
  61. private var selectocId: [String] = []
  62. private var overwrite = false
  63. private var dataSource = NCDataSource()
  64. internal var richWorkspaceText: String?
  65. private var layout = ""
  66. private var groupBy = ""
  67. private var titleButton = ""
  68. private var itemForLine = 0
  69. private var autoUploadFileName = ""
  70. private var autoUploadDirectory = ""
  71. private var listLayout: NCListLayout!
  72. private var gridLayout: NCGridLayout!
  73. private let headerHeight: CGFloat = 50
  74. private var headerRichWorkspaceHeight: CGFloat = 0
  75. private let footerHeight: CGFloat = 50
  76. private var shares: [tableShare]?
  77. private let refreshControl = UIRefreshControl()
  78. override func viewDidLoad() {
  79. super.viewDidLoad()
  80. self.navigationController?.navigationBar.prefersLargeTitles = true
  81. // Cell
  82. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  83. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  84. // Header
  85. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  86. // Footer
  87. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  88. collectionView.alwaysBounceVertical = true
  89. listLayout = NCListLayout()
  90. gridLayout = NCGridLayout()
  91. // Add Refresh Control
  92. collectionView.addSubview(refreshControl)
  93. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  94. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brandElement
  95. refreshControl.addTarget(self, action: #selector(loadDatasource), for: .valueChanged)
  96. // empty Data Source
  97. self.collectionView.emptyDataSetDelegate = self;
  98. self.collectionView.emptyDataSetSource = self;
  99. // title button
  100. buttonCancel.title = NSLocalizedString("_cancel_", comment: "")
  101. buttonCreateFolder.setTitle(NSLocalizedString("_create_folder_", comment: ""), for: .normal)
  102. overwriteLabel.text = NSLocalizedString("_overwrite_", comment: "")
  103. // button
  104. buttonCreateFolder.layer.cornerRadius = 15
  105. buttonCreateFolder.layer.masksToBounds = true
  106. buttonCreateFolder.layer.backgroundColor = NCBrandColor.sharedInstance.graySoft.withAlphaComponent(0.5).cgColor
  107. buttonCreateFolder.setTitleColor(.black, for: .normal)
  108. buttonDone.layer.cornerRadius = 15
  109. buttonDone.layer.masksToBounds = true
  110. buttonDone.layer.backgroundColor = NCBrandColor.sharedInstance.graySoft.withAlphaComponent(0.5).cgColor
  111. buttonDone.setTitleColor(.black, for: .normal)
  112. buttonDone1.layer.cornerRadius = 15
  113. buttonDone1.layer.masksToBounds = true
  114. buttonDone1.layer.backgroundColor = NCBrandColor.sharedInstance.graySoft.withAlphaComponent(0.5).cgColor
  115. buttonDone1.setTitleColor(.black, for: .normal)
  116. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  118. changeTheming()
  119. }
  120. override func viewWillAppear(_ animated: Bool) {
  121. super.viewWillAppear(animated)
  122. self.navigationItem.title = titleCurrentFolder
  123. toolBarTop.constant = -100
  124. buttonDone.setTitle(titleButtonDone, for: .normal)
  125. buttonDone1.setTitle(titleButtonDone1, for: .normal)
  126. buttonDone1.isHidden = isButtonDone1Hide
  127. overwriteSwitch.isOn = overwrite
  128. overwriteView.isHidden = isOverwriteHide
  129. if selectFile {
  130. buttonDone.isHidden = true
  131. }
  132. if hideButtonCreateFolder {
  133. buttonCreateFolder.isHidden = true
  134. }
  135. // set the serverUrl
  136. if serverUrl == "" {
  137. serverUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  138. }
  139. // get auto upload folder
  140. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  141. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  142. (layout, _, _, groupBy, _, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: keyLayout,serverUrl: serverUrl)
  143. gridLayout.itemForLine = CGFloat(itemForLine)
  144. if layout == k_layout_list {
  145. collectionView.collectionViewLayout = listLayout
  146. } else {
  147. collectionView.collectionViewLayout = gridLayout
  148. }
  149. loadDatasource(withLoadFolder: true)
  150. shares = NCManageDatabase.sharedInstance.getTableShares(account: appDelegate.account, serverUrl: serverUrl)
  151. }
  152. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  153. super.viewWillTransition(to: size, with: coordinator)
  154. coordinator.animate(alongsideTransition: nil) { _ in
  155. self.collectionView?.collectionViewLayout.invalidateLayout()
  156. }
  157. }
  158. @objc func changeTheming() {
  159. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  160. refreshControl.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  161. toolbar.backgroundColor = NCBrandColor.sharedInstance.tabBar
  162. //toolbar.tintColor = .gray
  163. }
  164. // MARK: DZNEmpty
  165. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  166. return NCBrandColor.sharedInstance.backgroundView
  167. }
  168. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  169. if networkInProgress {
  170. return CCGraphics.changeThemingColorImage(UIImage.init(named: "networkInProgress"), width: 300, height: 300, color: .gray)
  171. } else {
  172. return CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  173. }
  174. }
  175. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  176. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  177. if networkInProgress {
  178. return NSAttributedString.init(string: "\n"+NSLocalizedString("_request_in_progress_", comment: ""), attributes: attributes)
  179. } else if includeImages {
  180. return NSAttributedString.init(string: "\n"+NSLocalizedString("_files_no_files_", comment: ""), attributes: attributes)
  181. } else {
  182. return NSAttributedString.init(string: "\n"+NSLocalizedString("_files_no_folders_", comment: ""), attributes: attributes)
  183. }
  184. }
  185. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  186. return true
  187. }
  188. // MARK: ACTION
  189. @IBAction func actionCancel(_ sender: Any) {
  190. delegate?.dismissSelect(serverUrl: nil, metadata: nil, type: type, array: array, buttonType: "cancel", overwrite: overwrite)
  191. self.dismiss(animated: true, completion: nil)
  192. }
  193. @IBAction func actionDone(_ sender: Any) {
  194. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadataFolder, type: type, array: array, buttonType: "done", overwrite: overwrite)
  195. self.dismiss(animated: true, completion: nil)
  196. }
  197. @IBAction func actionDone1(_ sender: Any) {
  198. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadataFolder, type: type, array: array, buttonType: "done1", overwrite: overwrite)
  199. self.dismiss(animated: true, completion: nil)
  200. }
  201. @IBAction func actionCreateFolder(_ sender: Any) {
  202. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_", comment: ""), message:"", preferredStyle: .alert)
  203. alertController.addTextField { (textField) in
  204. textField.autocapitalizationType = UITextAutocapitalizationType.words
  205. }
  206. let actionSave = UIAlertAction(title: NSLocalizedString("_save_", comment: ""), style: .default) { (action:UIAlertAction) in
  207. if let fileName = alertController.textFields?.first?.text {
  208. self.createFolder(with: fileName)
  209. }
  210. }
  211. let actionCancel = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  212. print("You've pressed cancel button")
  213. }
  214. alertController.addAction(actionSave)
  215. alertController.addAction(actionCancel)
  216. self.present(alertController, animated: true, completion:nil)
  217. }
  218. @IBAction func valueChangedSwitchOverwrite(_ sender: Any) {
  219. if let viewControllers = self.navigationController?.viewControllers {
  220. for viewController in viewControllers {
  221. if viewController is NCSelect {
  222. (viewController as! NCSelect).overwrite = overwriteSwitch.isOn
  223. }
  224. }
  225. }
  226. }
  227. // MARK: TAP EVENT
  228. func tapSwitchHeader(sender: Any) {
  229. if collectionView.collectionViewLayout == gridLayout {
  230. // list layout
  231. UIView.animate(withDuration: 0.0, animations: {
  232. self.collectionView.collectionViewLayout.invalidateLayout()
  233. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  234. self.collectionView.reloadData()
  235. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  236. })
  237. })
  238. layout = k_layout_list
  239. NCUtility.shared.setLayoutForView(key: keyLayout, serverUrl: serverUrl, layout: layout)
  240. } else {
  241. // grid layout
  242. UIView.animate(withDuration: 0.0, animations: {
  243. self.collectionView.collectionViewLayout.invalidateLayout()
  244. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  245. self.collectionView.reloadData()
  246. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  247. })
  248. })
  249. layout = k_layout_grid
  250. NCUtility.shared.setLayoutForView(key: keyLayout, serverUrl: serverUrl, layout: layout)
  251. }
  252. }
  253. func tapOrderHeader(sender: Any) {
  254. let sortMenu = NCSortMenu()
  255. sortMenu.toggleMenu(viewController: self, key: keyLayout, sortButton: sender as? UIButton, serverUrl: serverUrl)
  256. }
  257. func tapMoreHeader(sender: Any) {
  258. }
  259. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  260. }
  261. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  262. }
  263. func tapShareListItem(with objectId: String, sender: Any) {
  264. }
  265. func tapRichWorkspace(sender: Any) {
  266. }
  267. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  268. }
  269. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  270. }
  271. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  272. }
  273. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  274. }
  275. }
  276. // MARK: - Collection View
  277. extension NCSelect: UICollectionViewDelegate {
  278. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  279. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  280. if isEditMode {
  281. if let index = selectocId.firstIndex(of: metadata.ocId) {
  282. selectocId.remove(at: index)
  283. } else {
  284. selectocId.append(metadata.ocId)
  285. }
  286. collectionView.reloadItems(at: [indexPath])
  287. return
  288. }
  289. if metadata.directory {
  290. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  291. guard let visualController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect else { return }
  292. self.serverUrlPush = serverUrlPush
  293. self.metadataTouch = metadata
  294. visualController.delegate = delegate
  295. visualController.hideButtonCreateFolder = hideButtonCreateFolder
  296. visualController.selectFile = selectFile
  297. visualController.includeDirectoryE2EEncryption = includeDirectoryE2EEncryption
  298. visualController.includeImages = includeImages
  299. visualController.type = type
  300. visualController.titleButtonDone = titleButtonDone
  301. visualController.titleButtonDone1 = titleButtonDone1
  302. visualController.isButtonDone1Hide = isButtonDone1Hide
  303. visualController.isOverwriteHide = isOverwriteHide
  304. visualController.overwrite = overwrite
  305. visualController.array = array
  306. visualController.titleCurrentFolder = metadataTouch!.fileNameView
  307. visualController.serverUrl = serverUrlPush
  308. self.navigationController?.pushViewController(visualController, animated: true)
  309. } else {
  310. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadata, type: type, array: array, buttonType: "select", overwrite: overwrite)
  311. self.dismiss(animated: true, completion: nil)
  312. }
  313. }
  314. }
  315. extension NCSelect: UICollectionViewDataSource {
  316. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  317. if kind == UICollectionView.elementKindSectionHeader {
  318. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  319. if collectionView.collectionViewLayout == gridLayout {
  320. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  321. } else {
  322. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  323. }
  324. header.delegate = self
  325. header.setStatusButton(count: dataSource.metadatas.count)
  326. header.setTitleSorted(datasourceTitleButton: titleButton)
  327. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  328. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  329. return header
  330. } else {
  331. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  332. let info = dataSource.getFilesInformation()
  333. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  334. return footer
  335. }
  336. }
  337. func numberOfSections(in collectionView: UICollectionView) -> Int {
  338. return 1
  339. }
  340. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  341. return dataSource.numberOfItems()
  342. }
  343. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  344. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  345. return UICollectionViewCell()
  346. }
  347. var tableShare: tableShare?
  348. var isShare = false
  349. var isMounted = false
  350. // Download preview
  351. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  352. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder.permissions.contains(k_permission_shared)
  353. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder.permissions.contains(k_permission_mounted)
  354. if dataSource.metadataShare[metadata.ocId] != nil {
  355. tableShare = dataSource.metadataShare[metadata.ocId]
  356. }
  357. // LAYOUT LIST
  358. if layout == k_layout_list {
  359. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  360. cell.delegate = self
  361. cell.objectId = metadata.ocId
  362. cell.indexPath = indexPath
  363. cell.labelTitle.text = metadata.fileNameView
  364. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  365. cell.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  366. cell.imageSelect.image = nil
  367. cell.imageStatus.image = nil
  368. cell.imageLocal.image = nil
  369. cell.imageFavorite.image = nil
  370. cell.imageShared.image = nil
  371. cell.imageMore.image = nil
  372. cell.imageItem.image = nil
  373. cell.imageItem.backgroundColor = nil
  374. cell.progressView.progress = 0.0
  375. if metadata.directory {
  376. if metadata.e2eEncrypted {
  377. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  378. } else if isShare {
  379. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  380. } else if (tableShare != nil && tableShare?.shareType != 3) {
  381. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  382. } else if (tableShare != nil && tableShare?.shareType == 3) {
  383. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  384. } else if metadata.mountType == "group" {
  385. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  386. } else if isMounted {
  387. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  388. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  389. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  390. } else {
  391. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  392. }
  393. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  394. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  395. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  396. // Local image: offline
  397. if tableDirectory != nil && tableDirectory!.offline {
  398. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  399. }
  400. } else {
  401. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  402. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  403. } else {
  404. if metadata.hasPreview {
  405. cell.imageItem.backgroundColor = .lightGray
  406. } else {
  407. if metadata.iconName.count > 0 {
  408. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  409. } else {
  410. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  411. }
  412. }
  413. }
  414. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  415. // image local
  416. if dataSource.metadataLocalImage[metadata.ocId] == "offlineFlag" {
  417. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  418. } else if dataSource.metadataLocalImage[metadata.ocId] == "local" {
  419. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  420. }
  421. }
  422. // image Favorite
  423. if metadata.favorite {
  424. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  425. }
  426. // Share image
  427. if (isShare) {
  428. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  429. } else if (tableShare != nil && tableShare?.shareType == 3) {
  430. cell.imageShared.image = NCCollectionCommon.images.cellShareByLinkImage
  431. } else if (tableShare != nil && tableShare?.shareType != 3) {
  432. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  433. } else {
  434. cell.imageShared.image = NCCollectionCommon.images.cellCanShareImage
  435. }
  436. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userID {
  437. // Load avatar
  438. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  439. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-avatar-" + metadata.ownerId + ".png"
  440. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  441. cell.imageShared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  442. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  443. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  444. } else {
  445. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  446. if errorCode == 0 && account == self.appDelegate.account {
  447. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  448. }
  449. }
  450. }
  451. }
  452. cell.imageItemLeftConstraint.constant = 10
  453. cell.imageSelect.isHidden = true
  454. cell.backgroundView = nil
  455. // Transfer
  456. var progress: Float = 0.0
  457. var totalBytes: Double = 0.0
  458. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  459. if progressArray != nil && progressArray?.count == 3 {
  460. progress = progressArray?.object(at: 0) as? Float ?? 0
  461. totalBytes = progressArray?.object(at: 1) as? Double ?? 0
  462. }
  463. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  464. cell.progressView.isHidden = false
  465. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  466. } else {
  467. cell.progressView.isHidden = true
  468. cell.progressView.progress = progress
  469. cell.setButtonMore(named: k_buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  470. }
  471. // Write status on Label Info
  472. switch metadata.status {
  473. case Int(k_metadataStatusWaitDownload):
  474. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  475. break
  476. case Int(k_metadataStatusInDownload):
  477. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  478. break
  479. case Int(k_metadataStatusDownloading):
  480. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  481. break
  482. case Int(k_metadataStatusWaitUpload):
  483. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  484. break
  485. case Int(k_metadataStatusInUpload):
  486. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  487. break
  488. case Int(k_metadataStatusUploading):
  489. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  490. break
  491. default:
  492. break
  493. }
  494. // Live Photo
  495. if metadata.livePhoto {
  496. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  497. }
  498. // E2EE
  499. if metadata.e2eEncrypted {
  500. cell.hideButtonShare(true)
  501. } else {
  502. cell.hideButtonShare(false)
  503. }
  504. // Remove last separator
  505. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  506. cell.separator.isHidden = true
  507. } else {
  508. cell.separator.isHidden = false
  509. }
  510. return cell
  511. }
  512. // LAYOUT GRID
  513. if layout == k_layout_grid {
  514. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  515. cell.delegate = self
  516. cell.objectId = metadata.ocId
  517. cell.indexPath = indexPath
  518. cell.labelTitle.text = metadata.fileNameView
  519. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  520. cell.imageSelect.image = nil
  521. cell.imageStatus.image = nil
  522. cell.imageLocal.image = nil
  523. cell.imageFavorite.image = nil
  524. cell.imageItem.image = nil
  525. cell.imageItem.backgroundColor = nil
  526. cell.progressView.progress = 0.0
  527. if metadata.directory {
  528. if metadata.e2eEncrypted {
  529. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  530. } else if isShare {
  531. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  532. } else if (tableShare != nil && tableShare!.shareType != 3) {
  533. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  534. } else if (tableShare != nil && tableShare!.shareType == 3) {
  535. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  536. } else if metadata.mountType == "group" {
  537. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  538. } else if isMounted {
  539. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  540. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  541. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  542. } else {
  543. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  544. }
  545. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  546. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  547. // Local image: offline
  548. if tableDirectory != nil && tableDirectory!.offline {
  549. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  550. }
  551. } else {
  552. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  553. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  554. } else {
  555. if metadata.hasPreview {
  556. cell.imageItem.backgroundColor = .lightGray
  557. } else {
  558. if metadata.iconName.count > 0 {
  559. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  560. } else {
  561. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  562. }
  563. }
  564. }
  565. // image Local
  566. if dataSource.metadataLocalImage[metadata.ocId] == "offlineFlag" {
  567. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  568. } else if dataSource.metadataLocalImage[metadata.ocId] == "local" {
  569. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  570. }
  571. }
  572. // image Favorite
  573. if metadata.favorite {
  574. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  575. }
  576. cell.imageSelect.isHidden = true
  577. cell.backgroundView = nil
  578. // Transfer
  579. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  580. cell.progressView.isHidden = false
  581. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  582. } else {
  583. cell.progressView.isHidden = true
  584. cell.progressView.progress = 0.0
  585. cell.setButtonMore(named: k_buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  586. }
  587. // Live Photo
  588. if metadata.livePhoto {
  589. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  590. }
  591. return cell
  592. }
  593. return UICollectionViewCell()
  594. }
  595. }
  596. extension NCSelect: UICollectionViewDelegateFlowLayout {
  597. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  598. if richWorkspaceText?.count ?? 0 == 0 {
  599. headerRichWorkspaceHeight = 0
  600. } else {
  601. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  602. }
  603. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  604. }
  605. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  606. return CGSize(width: collectionView.frame.width, height: footerHeight)
  607. }
  608. }
  609. // MARK: - NC API & Algorithm
  610. extension NCSelect {
  611. @objc func reloadDataSource() {
  612. loadDatasource(withLoadFolder: false)
  613. }
  614. @objc func loadDatasource(withLoadFolder: Bool) {
  615. var predicate: NSPredicate?
  616. var sort: String
  617. var ascending: Bool
  618. var directoryOnTop: Bool
  619. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: keyLayout, serverUrl: serverUrl)
  620. if includeDirectoryE2EEncryption {
  621. if includeImages {
  622. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND (directory == true OR typeFile == 'image')", appDelegate.account, serverUrl)
  623. } else {
  624. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", appDelegate.account, serverUrl)
  625. }
  626. } else {
  627. if includeImages {
  628. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND (directory == true OR typeFile == 'image')", appDelegate.account, serverUrl)
  629. } else {
  630. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND directory == true", appDelegate.account, serverUrl)
  631. }
  632. }
  633. let metadatasSource = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicate!, page: 0, limit: 0, sorted: sort, ascending: ascending)
  634. self.dataSource = NCDataSource.init(metadatasSource: metadatasSource, directoryOnTop: directoryOnTop, filterLivePhoto: true)
  635. if withLoadFolder {
  636. loadFolder()
  637. } else {
  638. self.refreshControl.endRefreshing()
  639. }
  640. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account,serverUrl))
  641. richWorkspaceText = directory?.richWorkspace
  642. collectionView.reloadData()
  643. }
  644. func createFolder(with fileName: String) {
  645. NCNetworking.shared.createFolder(fileName: fileName, serverUrl: serverUrl, account: appDelegate.account, urlBase: appDelegate.urlBase) { (errorCode, errorDescription) in
  646. if errorCode == 0 {
  647. self.loadDatasource(withLoadFolder: true)
  648. } else {
  649. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  650. }
  651. }
  652. }
  653. func loadFolder() {
  654. networkInProgress = true
  655. collectionView.reloadData()
  656. NCNetworking.shared.readFolder(serverUrl: serverUrl, account: appDelegate.account) { (_, _, _, _, _, errorCode, errorDescription) in
  657. if errorCode != 0 {
  658. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  659. }
  660. self.networkInProgress = false
  661. self.loadDatasource(withLoadFolder: false)
  662. }
  663. }
  664. }