NCSelect.swift 36 KB

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