NCSelect.swift 36 KB

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