NCSelect.swift 39 KB

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