NCSelect.swift 37 KB

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