NCSelect.swift 36 KB

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