NCSelect.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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. @objc protocol NCSelectDelegate {
  25. @objc func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String)
  26. }
  27. class NCSelect: UIViewController, UIGestureRecognizerDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, BKPasscodeViewControllerDelegate {
  28. @IBOutlet fileprivate weak var collectionView: UICollectionView!
  29. @IBOutlet fileprivate weak var toolbar: UIToolbar!
  30. @IBOutlet fileprivate weak var buttonCancel: UIBarButtonItem!
  31. @IBOutlet fileprivate weak var buttonCreateFolder: UIBarButtonItem!
  32. @IBOutlet fileprivate weak var buttonDone: UIBarButtonItem!
  33. // ------ external settings ------------------------------------
  34. @objc var delegate: NCSelectDelegate?
  35. @objc var hideButtonCreateFolder = false
  36. @objc var selectFile = false
  37. @objc var includeDirectoryE2EEncryption = false
  38. @objc var includeImages = false
  39. @objc var type = ""
  40. @objc var titleButtonDone = NSLocalizedString("_move_", comment: "")
  41. @objc var layoutViewSelect = k_layout_view_move
  42. var titleCurrentFolder = NCBrandOptions.sharedInstance.brand
  43. var serverUrl = ""
  44. // -------------------------------------------------------------
  45. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  46. private var serverUrlPush = ""
  47. private var metadataPush: tableMetadata?
  48. private var metadataFolder: tableMetadata?
  49. private var isEditMode = false
  50. private var networkInProgress = false
  51. private var selectocId = [String]()
  52. private var sectionDatasource = CCSectionDataSourceMetadata()
  53. private var typeLayout = ""
  54. private var datasourceSorted = ""
  55. private var datasourceAscending = true
  56. private var datasourceGroupBy = ""
  57. private var datasourceDirectoryOnTop = false
  58. private var autoUploadFileName = ""
  59. private var autoUploadDirectory = ""
  60. private var listLayout: NCListLayout!
  61. private var gridLayout: NCGridLayout!
  62. private let headerMenuHeight: CGFloat = 50
  63. private let sectionHeaderHeight: CGFloat = 20
  64. private let footerHeight: CGFloat = 50
  65. private var shares: [tableShare]?
  66. private let refreshControl = UIRefreshControl()
  67. //BKPasscodeViewController
  68. private var failedAttempts: Double = 0
  69. private var lockUntilDate: NSDate?
  70. override func viewDidLoad() {
  71. super.viewDidLoad()
  72. // Cell
  73. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  74. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  75. // Header
  76. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  77. collectionView.register(UINib.init(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  78. // Footer
  79. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  80. collectionView.alwaysBounceVertical = true
  81. collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm
  82. listLayout = NCListLayout()
  83. gridLayout = NCGridLayout()
  84. // Add Refresh Control
  85. if #available(iOS 10.0, *) {
  86. collectionView.refreshControl = refreshControl
  87. } else {
  88. collectionView.addSubview(refreshControl)
  89. }
  90. // Configure Refresh Control
  91. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  92. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  93. refreshControl.addTarget(self, action: #selector(loadDatasource), for: .valueChanged)
  94. // empty Data Source
  95. self.collectionView.emptyDataSetDelegate = self;
  96. self.collectionView.emptyDataSetSource = self;
  97. // title button
  98. buttonCancel.title = NSLocalizedString("_cancel_", comment: "")
  99. buttonCreateFolder.title = NSLocalizedString("_create_folder_", comment: "")
  100. // changeTheming
  101. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  102. changeTheming()
  103. }
  104. override func viewWillAppear(_ animated: Bool) {
  105. super.viewWillAppear(animated)
  106. self.navigationItem.title = titleCurrentFolder
  107. buttonDone.title = titleButtonDone
  108. if selectFile {
  109. buttonDone.isEnabled = false
  110. buttonDone.tintColor = UIColor.clear
  111. }
  112. if hideButtonCreateFolder {
  113. buttonCreateFolder.isEnabled = false
  114. buttonCreateFolder.tintColor = UIColor.clear
  115. }
  116. (typeLayout, datasourceSorted, datasourceAscending, datasourceGroupBy, datasourceDirectoryOnTop) = NCUtility.sharedInstance.getLayoutForView(key: layoutViewSelect)
  117. // get auto upload folder
  118. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  119. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(appDelegate.activeUrl)
  120. if typeLayout == k_layout_list {
  121. collectionView.collectionViewLayout = listLayout
  122. } else {
  123. collectionView.collectionViewLayout = gridLayout
  124. }
  125. loadDatasource(withLoadFolder: true)
  126. shares = NCManageDatabase.sharedInstance.getTableShares(account: appDelegate.activeAccount, serverUrl: serverUrl)
  127. }
  128. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  129. super.viewWillTransition(to: size, with: coordinator)
  130. coordinator.animate(alongsideTransition: nil) { _ in
  131. self.collectionView.collectionViewLayout.invalidateLayout()
  132. }
  133. }
  134. @objc func changeTheming() {
  135. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  136. toolbar.barTintColor = NCBrandColor.sharedInstance.tabBar
  137. toolbar.tintColor = .gray
  138. }
  139. // MARK: DZNEmpty
  140. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  141. return NCBrandColor.sharedInstance.backgroundView
  142. }
  143. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  144. if networkInProgress {
  145. return CCGraphics.changeThemingColorImage(UIImage.init(named: "networkInProgress"), width: 300, height: 300, color: UIColor.lightGray)
  146. } else {
  147. return CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  148. }
  149. }
  150. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  151. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  152. if networkInProgress {
  153. return NSAttributedString.init(string: "\n"+NSLocalizedString("_request_in_progress_", comment: ""), attributes: attributes)
  154. } else if includeImages {
  155. return NSAttributedString.init(string: "\n"+NSLocalizedString("_files_no_files_", comment: ""), attributes: attributes)
  156. } else {
  157. return NSAttributedString.init(string: "\n"+NSLocalizedString("_files_no_folders_", comment: ""), attributes: attributes)
  158. }
  159. }
  160. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  161. return true
  162. }
  163. // MARK: BKPASSCODEVIEWCONTROLLER
  164. func passcodeViewController(_ aViewController: BKPasscodeViewController!, didFinishWithPasscode aPasscode: String!) {
  165. aViewController.dismiss(animated: true, completion: nil)
  166. performSegueDirectoryWithControlPasscode(controlPasscode: false)
  167. }
  168. func passcodeViewController(_ aViewController: BKPasscodeViewController!, authenticatePasscode aPasscode: String!, resultHandler aResultHandler: ((Bool) -> Void)!) {
  169. if aPasscode == CCUtility.getBlockCode() {
  170. failedAttempts = 0
  171. lockUntilDate = nil
  172. aResultHandler(true)
  173. } else {
  174. aResultHandler(false)
  175. }
  176. }
  177. func passcodeViewControllerDidFailAttempt(_ aViewController: BKPasscodeViewController!) {
  178. failedAttempts += 1
  179. if failedAttempts > 5 {
  180. var timeInterval: TimeInterval = 60
  181. if failedAttempts > 6 {
  182. let multiplier: Double = failedAttempts - 6
  183. timeInterval = (5 * 60) * multiplier
  184. if timeInterval > 3600 * 24 {
  185. timeInterval = 3600 * 24
  186. }
  187. }
  188. lockUntilDate = NSDate.init(timeIntervalSinceNow: timeInterval)
  189. }
  190. }
  191. func passcodeViewControllerNumber(ofFailedAttempts aViewController: BKPasscodeViewController!) -> UInt {
  192. return UInt(failedAttempts)
  193. }
  194. func passcodeViewControllerLock(untilDate aViewController: BKPasscodeViewController!) -> Date? {
  195. return lockUntilDate as Date?
  196. }
  197. @objc func passcodeViewCloseButtonPressed(_ sender: Any) {
  198. self.dismiss(animated: true, completion: nil)
  199. }
  200. // MARK: ACTION
  201. @IBAction func actionCancel(_ sender: Any) {
  202. delegate?.dismissSelect(serverUrl: nil, metadata: nil, type: type)
  203. self.dismiss(animated: true, completion: nil)
  204. }
  205. @IBAction func actionDone(_ sender: Any) {
  206. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadataFolder, type: type)
  207. self.dismiss(animated: true, completion: nil)
  208. }
  209. @IBAction func actionCreateFolder(_ sender: Any) {
  210. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_", comment: ""), message:"", preferredStyle: .alert)
  211. alertController.addTextField { (textField) in
  212. textField.autocapitalizationType = UITextAutocapitalizationType.words
  213. }
  214. let actionSave = UIAlertAction(title: NSLocalizedString("_save_", comment: ""), style: .default) { (action:UIAlertAction) in
  215. if let fileName = alertController.textFields?.first?.text {
  216. self.createFolder(with: fileName)
  217. }
  218. }
  219. let actionCancel = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  220. print("You've pressed cancel button")
  221. }
  222. alertController.addAction(actionSave)
  223. alertController.addAction(actionCancel)
  224. self.present(alertController, animated: true, completion:nil)
  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. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  235. })
  236. })
  237. typeLayout = k_layout_list
  238. NCUtility.sharedInstance.setLayoutForView(key: layoutViewSelect, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  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. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  246. })
  247. })
  248. typeLayout = k_layout_grid
  249. NCUtility.sharedInstance.setLayoutForView(key: layoutViewSelect, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  250. }
  251. }
  252. func tapOrderHeader(sender: Any) {
  253. var menuView: DropdownMenu?
  254. var selectedIndexPath = [IndexPath()]
  255. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameAZ"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_a_z_", comment: ""))
  256. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameZA"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_z_a_", comment: ""))
  257. let item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateMoreRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_more_recent_", comment: ""))
  258. let item4 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateLessRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_less_recent_", comment: ""))
  259. let item5 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortSmallest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_smallest_", comment: ""))
  260. let item6 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortLargest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_largest_", comment: ""))
  261. switch datasourceSorted {
  262. case "fileName":
  263. if datasourceAscending == true { item1.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 0)) }
  264. if datasourceAscending == false { item2.style = .highlight; selectedIndexPath.append(IndexPath(row: 1, section: 0)) }
  265. case "date":
  266. if datasourceAscending == false { item3.style = .highlight; selectedIndexPath.append(IndexPath(row: 2, section: 0)) }
  267. if datasourceAscending == true { item4.style = .highlight; selectedIndexPath.append(IndexPath(row: 3, section: 0)) }
  268. case "size":
  269. if datasourceAscending == true { item5.style = .highlight; selectedIndexPath.append(IndexPath(row: 4, section: 0)) }
  270. if datasourceAscending == false { item6.style = .highlight; selectedIndexPath.append(IndexPath(row: 5, section: 0)) }
  271. default:
  272. ()
  273. }
  274. let item7 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByAlphabetic"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_alphabetic_no_", comment: ""))
  275. let item8 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByFile"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_typefile_no_", comment: ""))
  276. let item9 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByDate"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_date_no_", comment: ""))
  277. switch datasourceGroupBy {
  278. case "alphabetic":
  279. item7.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 1))
  280. case "typefile":
  281. item8.style = .highlight; selectedIndexPath.append(IndexPath(row: 1, section: 1))
  282. case "date":
  283. item9.style = .highlight; selectedIndexPath.append(IndexPath(row: 2, section: 1))
  284. default:
  285. ()
  286. }
  287. let item10 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "foldersOnTop"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_directory_on_top_no_", comment: ""))
  288. if datasourceDirectoryOnTop {
  289. item10.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 2))
  290. }
  291. let sectionOrder = DropdownSection(sectionIdentifier: "", items: [item1, item2, item3, item4, item5, item6])
  292. let sectionGroupBy = DropdownSection(sectionIdentifier: "", items: [item7, item8, item9])
  293. let sectionFolderOnTop = DropdownSection(sectionIdentifier: "", items: [item10])
  294. menuView = DropdownMenu(navigationController: self.navigationController!, sections: [sectionOrder, sectionGroupBy, sectionFolderOnTop], selectedIndexPath: selectedIndexPath)
  295. menuView?.token = "tapOrderHeaderMenu"
  296. menuView?.delegate = self
  297. menuView?.rowHeight = 45
  298. menuView?.sectionHeaderHeight = 8
  299. menuView?.highlightColor = NCBrandColor.sharedInstance.brand
  300. menuView?.tableView.alwaysBounceVertical = false
  301. menuView?.tableViewSeperatorColor = NCBrandColor.sharedInstance.separator
  302. menuView?.tableViewBackgroundColor = NCBrandColor.sharedInstance.backgroundForm
  303. menuView?.cellBackgroundColor = NCBrandColor.sharedInstance.backgroundForm
  304. menuView?.textColor = NCBrandColor.sharedInstance.textView
  305. let header = (sender as? UIButton)?.superview
  306. let headerRect = self.collectionView.convert(header!.bounds, from: self.view)
  307. let menuOffsetY = headerRect.height - headerRect.origin.y - 2
  308. menuView?.topOffsetY = CGFloat(menuOffsetY)
  309. menuView?.showMenu()
  310. }
  311. func tapMoreHeader(sender: Any) {
  312. }
  313. func tapMoreListItem(with objectId: String, sender: Any) {
  314. }
  315. func tapMoreGridItem(with objectId: String, sender: Any) {
  316. }
  317. func tapShareListItem(with objectId: String, sender: Any) {
  318. }
  319. // MARK: DROP-DOWN-MENU
  320. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  321. if dropdownMenu.token == "tapOrderHeaderMenu" {
  322. switch indexPath.section {
  323. case 0: switch indexPath.row {
  324. case 0: datasourceSorted = "fileName"; datasourceAscending = true
  325. case 1: datasourceSorted = "fileName"; datasourceAscending = false
  326. case 2: datasourceSorted = "date"; datasourceAscending = false
  327. case 3: datasourceSorted = "date"; datasourceAscending = true
  328. case 4: datasourceSorted = "size"; datasourceAscending = true
  329. case 5: datasourceSorted = "size"; datasourceAscending = false
  330. default: ()
  331. }
  332. case 1: switch indexPath.row {
  333. case 0:
  334. if datasourceGroupBy == "alphabetic" {
  335. datasourceGroupBy = "none"
  336. } else {
  337. datasourceGroupBy = "alphabetic"
  338. }
  339. case 1:
  340. if datasourceGroupBy == "typefile" {
  341. datasourceGroupBy = "none"
  342. } else {
  343. datasourceGroupBy = "typefile"
  344. }
  345. case 2:
  346. if datasourceGroupBy == "date" {
  347. datasourceGroupBy = "none"
  348. } else {
  349. datasourceGroupBy = "date"
  350. }
  351. default: ()
  352. }
  353. case 2:
  354. if datasourceDirectoryOnTop {
  355. datasourceDirectoryOnTop = false
  356. } else {
  357. datasourceDirectoryOnTop = true
  358. }
  359. default: ()
  360. }
  361. NCUtility.sharedInstance.setLayoutForView(key: layoutViewSelect, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  362. loadDatasource(withLoadFolder: false)
  363. }
  364. if dropdownMenu.token == "tapMoreHeaderMenu" {
  365. }
  366. if dropdownMenu.token == "tapMoreHeaderMenuSelect" {
  367. }
  368. }
  369. // MARK: NAVIGATION
  370. private func performSegueDirectoryWithControlPasscode(controlPasscode: Bool) {
  371. guard let directoryPush = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrlPush)) else {
  372. return
  373. }
  374. if directoryPush.lock == true && CCUtility.getBlockCode() != nil && (CCUtility.getBlockCode()?.count)! > 0 && controlPasscode {
  375. let viewController = CCBKPasscode.init(nibName: nil, bundle: nil)
  376. guard let touchIDManager = BKTouchIDManager.init(keychainServiceName: k_serviceShareKeyChain) else {
  377. return
  378. }
  379. touchIDManager.promptText = NSLocalizedString("_scan_fingerprint_", comment: "")
  380. viewController.delegate = self
  381. viewController.type = BKPasscodeViewControllerCheckPasscodeType
  382. viewController.inputViewTitlePassword = true
  383. if CCUtility.getSimplyBlockCode() {
  384. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle
  385. viewController.passcodeInputView.maximumLength = 6
  386. } else {
  387. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle
  388. viewController.passcodeInputView.maximumLength = 64
  389. }
  390. viewController.touchIDManager = touchIDManager
  391. viewController.title = NSLocalizedString("_folder_blocked_", comment: "")
  392. viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: #selector(passcodeViewCloseButtonPressed(_:)))
  393. viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor.black
  394. let navigationController = UINavigationController.init(rootViewController: viewController)
  395. navigationController.modalPresentationStyle = .fullScreen
  396. self.present(navigationController, animated: true, completion: nil)
  397. return
  398. }
  399. guard let visualController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect else {
  400. return
  401. }
  402. visualController.delegate = delegate
  403. visualController.hideButtonCreateFolder = hideButtonCreateFolder
  404. visualController.selectFile = selectFile
  405. visualController.includeDirectoryE2EEncryption = includeDirectoryE2EEncryption
  406. visualController.includeImages = includeImages
  407. visualController.type = type
  408. visualController.titleButtonDone = titleButtonDone
  409. visualController.layoutViewSelect = layoutViewSelect
  410. visualController.titleCurrentFolder = metadataPush!.fileNameView
  411. visualController.serverUrl = serverUrlPush
  412. self.navigationController?.pushViewController(visualController, animated: true)
  413. }
  414. }
  415. // MARK: - Collection View
  416. extension NCSelect: UICollectionViewDelegate {
  417. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  418. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  419. return
  420. }
  421. if isEditMode {
  422. if let index = selectocId.firstIndex(of: metadata.ocId) {
  423. selectocId.remove(at: index)
  424. } else {
  425. selectocId.append(metadata.ocId)
  426. }
  427. collectionView.reloadItems(at: [indexPath])
  428. return
  429. }
  430. if metadata.directory {
  431. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else {
  432. return
  433. }
  434. self.serverUrlPush = serverUrlPush
  435. self.metadataPush = metadata
  436. performSegueDirectoryWithControlPasscode(controlPasscode: true)
  437. } else {
  438. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadata, type: type)
  439. self.dismiss(animated: true, completion: nil)
  440. }
  441. }
  442. }
  443. extension NCSelect: UICollectionViewDataSource {
  444. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  445. if (indexPath.section == 0) {
  446. if kind == UICollectionView.elementKindSectionHeader {
  447. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  448. if collectionView.collectionViewLayout == gridLayout {
  449. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  450. } else {
  451. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  452. }
  453. header.delegate = self
  454. header.setStatusButton(count: sectionDatasource.allOcId.count)
  455. header.setTitleOrder(datasourceSorted: datasourceSorted, datasourceAscending: datasourceAscending)
  456. if datasourceGroupBy == "none" {
  457. header.labelSection.isHidden = true
  458. header.labelSectionHeightConstraint.constant = 0
  459. } else {
  460. header.labelSection.isHidden = false
  461. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  462. header.labelSectionHeightConstraint.constant = sectionHeaderHeight
  463. }
  464. return header
  465. } else {
  466. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  467. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  468. return footer
  469. }
  470. } else {
  471. if kind == UICollectionView.elementKindSectionHeader {
  472. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  473. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  474. return header
  475. } else {
  476. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  477. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  478. return footer
  479. }
  480. }
  481. }
  482. func numberOfSections(in collectionView: UICollectionView) -> Int {
  483. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  484. return sections
  485. }
  486. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  487. let key = sectionDatasource.sections.object(at: section)
  488. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  489. return datasource.count
  490. }
  491. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  492. let cell: UICollectionViewCell
  493. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  494. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  495. }
  496. if typeLayout == k_layout_grid {
  497. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  498. } else {
  499. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  500. }
  501. NCMainCommon.sharedInstance.collectionViewCellForItemAt(indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: metadataFolder, serverUrl: serverUrl, isEditMode: isEditMode, selectocId: selectocId, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory ,hideButtonMore: true, downloadThumbnail: true, shares: shares, source: self)
  502. if typeLayout == k_layout_grid {
  503. let cell = cell as! NCGridCell
  504. cell.buttonMore.isHidden = true
  505. return cell
  506. } else {
  507. let cell = cell as! NCListCell
  508. cell.imageMore.isHidden = true
  509. cell.sharedLeftConstraint.constant = 15
  510. return cell
  511. }
  512. }
  513. }
  514. extension NCSelect: UICollectionViewDelegateFlowLayout {
  515. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  516. if section == 0 {
  517. if datasourceGroupBy == "none" {
  518. return CGSize(width: collectionView.frame.width, height: headerMenuHeight)
  519. } else {
  520. return CGSize(width: collectionView.frame.width, height: headerMenuHeight + sectionHeaderHeight)
  521. }
  522. } else {
  523. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  524. }
  525. }
  526. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  527. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  528. if (section == sections - 1) {
  529. return CGSize(width: collectionView.frame.width, height: footerHeight)
  530. } else {
  531. return CGSize(width: collectionView.frame.width, height: 0)
  532. }
  533. }
  534. }
  535. // MARK: - NC API & Algorithm
  536. extension NCSelect {
  537. @objc func loadDatasource(withLoadFolder: Bool) {
  538. sectionDatasource = CCSectionDataSourceMetadata()
  539. var predicate: NSPredicate?
  540. if serverUrl == "" {
  541. serverUrl = CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl)
  542. }
  543. if includeDirectoryE2EEncryption {
  544. if includeImages {
  545. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND (directory == true OR typeFile == 'image')", appDelegate.activeAccount, serverUrl)
  546. } else {
  547. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND directory == true", appDelegate.activeAccount, serverUrl)
  548. }
  549. } else {
  550. if includeImages {
  551. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND (directory == true OR typeFile == 'image')", appDelegate.activeAccount, serverUrl)
  552. } else {
  553. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@ AND e2eEncrypted == false AND directory == true", appDelegate.activeAccount, serverUrl)
  554. }
  555. }
  556. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicate!, sorted: nil, ascending: false) {
  557. sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: datasourceGroupBy, filterocId: nil, filterTypeFileImage: false, filterTypeFileVideo: false, sorted: datasourceSorted, ascending: datasourceAscending, activeAccount: appDelegate.activeAccount)
  558. }
  559. if withLoadFolder {
  560. loadFolder()
  561. } else {
  562. self.refreshControl.endRefreshing()
  563. }
  564. collectionView.reloadData()
  565. }
  566. func createFolder(with fileName: String) {
  567. OCNetworking.sharedManager().createFolder(withAccount: appDelegate.activeAccount, serverUrl: serverUrl, fileName: fileName, completion: { (account, ocId, date, message, errorCode) in
  568. if errorCode == 0 && account == self.appDelegate.activeAccount {
  569. self.loadDatasource(withLoadFolder: true)
  570. } else if errorCode != 0 {
  571. NCContentPresenter.shared.messageNotification("_error_", description: message, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  572. } else {
  573. print("[LOG] It has been changed user during networking process, error.")
  574. }
  575. })
  576. }
  577. func loadFolder() {
  578. networkInProgress = true
  579. collectionView.reloadData()
  580. OCNetworking.sharedManager().readFolder(withAccount: appDelegate.activeAccount, serverUrl: serverUrl, depth: "1", completion: { (account, metadatas, metadataFolder, message, errorCode) in
  581. if errorCode == 0 && account == self.appDelegate.activeAccount {
  582. self.metadataFolder = metadataFolder
  583. // Update directory etag
  584. NCManageDatabase.sharedInstance.setDirectory(serverUrl: self.serverUrl, serverUrlTo: nil, etag: metadataFolder?.etag, ocId: metadataFolder?.ocId, encrypted: metadataFolder!.e2eEncrypted, richWorkspace: nil, account: self.appDelegate.activeAccount)
  585. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", self.appDelegate.activeAccount ,self.serverUrl, k_metadataStatusNormal))
  586. NCManageDatabase.sharedInstance.setDateReadDirectory(serverUrl: self.serverUrl, account: self.appDelegate.activeAccount)
  587. _ = NCManageDatabase.sharedInstance.addMetadatas(metadatas as! [tableMetadata])
  588. if let metadatasInDownload = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND (status == %d OR status == %d OR status == %d OR status == %d)", self.appDelegate.activeAccount ,self.serverUrl, k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading, k_metadataStatusDownloadError), sorted: nil, ascending: false) {
  589. _ = NCManageDatabase.sharedInstance.addMetadatas(metadatasInDownload)
  590. }
  591. } else if errorCode != 0 {
  592. NCContentPresenter.shared.messageNotification("_error_", description: message, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  593. } else {
  594. print("[LOG] It has been changed user during networking process, error.")
  595. }
  596. self.networkInProgress = false
  597. self.loadDatasource(withLoadFolder: false)
  598. })
  599. }
  600. }