NCSelect.swift 39 KB

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