NCSelect.swift 40 KB

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