NCSelect.swift 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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 isEditMode = false
  51. private var networkInProgress = false
  52. private var selectFileID = [String]()
  53. private var sectionDatasource = CCSectionDataSourceMetadata()
  54. private var typeLayout = ""
  55. private var datasourceSorted = ""
  56. private var datasourceAscending = true
  57. private var datasourceGroupBy = ""
  58. private var datasourceDirectoryOnTop = false
  59. private var listLayout: NCListLayout!
  60. private var gridLayout: NCGridLayout!
  61. private var actionSheet: ActionSheet?
  62. private let headerMenuHeight: CGFloat = 50
  63. private let sectionHeaderHeight: CGFloat = 20
  64. private let footerHeight: CGFloat = 50
  65. private let refreshControl = UIRefreshControl()
  66. //BKPasscodeViewController
  67. private var failedAttempts: Double = 0
  68. private var lockUntilDate: NSDate?
  69. override func viewDidLoad() {
  70. super.viewDidLoad()
  71. // Cell
  72. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  73. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  74. // Header
  75. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  76. collectionView.register(UINib.init(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  77. // Footer
  78. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  79. collectionView.alwaysBounceVertical = true
  80. listLayout = NCListLayout()
  81. gridLayout = NCGridLayout()
  82. // Add Refresh Control
  83. if #available(iOS 10.0, *) {
  84. collectionView.refreshControl = refreshControl
  85. } else {
  86. collectionView.addSubview(refreshControl)
  87. }
  88. // Configure Refresh Control
  89. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  90. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  91. refreshControl.addTarget(self, action: #selector(loadDatasource), for: .valueChanged)
  92. // empty Data Source
  93. self.collectionView.emptyDataSetDelegate = self;
  94. self.collectionView.emptyDataSetSource = self;
  95. // title button
  96. buttonCancel.title = NSLocalizedString("_cancel_", comment: "")
  97. buttonCreateFolder.title = NSLocalizedString("_create_folder_", comment: "")
  98. }
  99. override func viewWillAppear(_ animated: Bool) {
  100. super.viewWillAppear(animated)
  101. // Color
  102. appDelegate.aspectNavigationControllerBar(self.navigationController?.navigationBar, online: appDelegate.reachability.isReachable(), hidden: false)
  103. toolbar.barTintColor = NCBrandColor.sharedInstance.tabBar
  104. toolbar.tintColor = NCBrandColor.sharedInstance.brandElement
  105. self.navigationItem.title = titleCurrentFolder
  106. buttonDone.title = titleButtonDone
  107. if selectFile {
  108. buttonDone.isEnabled = false
  109. buttonDone.tintColor = UIColor.clear
  110. }
  111. if hideButtonCreateFolder {
  112. buttonCreateFolder.isEnabled = false
  113. buttonCreateFolder.tintColor = UIColor.clear
  114. }
  115. (typeLayout, datasourceSorted, datasourceAscending, datasourceGroupBy, datasourceDirectoryOnTop) = NCUtility.sharedInstance.getLayoutForView(key: layoutViewSelect)
  116. if typeLayout == "list" {
  117. collectionView.collectionViewLayout = listLayout
  118. } else {
  119. collectionView.collectionViewLayout = gridLayout
  120. }
  121. loadDatasource(withLoadFolder: true)
  122. }
  123. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  124. super.viewWillTransition(to: size, with: coordinator)
  125. coordinator.animate(alongsideTransition: nil) { _ in
  126. self.collectionView.collectionViewLayout.invalidateLayout()
  127. self.actionSheet?.viewDidLayoutSubviews()
  128. }
  129. }
  130. // MARK: DZNEmpty
  131. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  132. return NCBrandColor.sharedInstance.backgroundView
  133. }
  134. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  135. if networkInProgress {
  136. return CCGraphics.changeThemingColorImage(UIImage.init(named: "networkInProgress"), multiplier: 2, color: UIColor.lightGray)
  137. } else {
  138. return CCGraphics.changeThemingColorImage(UIImage.init(named: "filesNoFiles"), multiplier: 2, color: NCBrandColor.sharedInstance.brandElement)
  139. }
  140. }
  141. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  142. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  143. if networkInProgress {
  144. return NSAttributedString.init(string: "\n"+NSLocalizedString("_request_in_progress_", comment: ""), attributes: attributes)
  145. } else if includeImages {
  146. return NSAttributedString.init(string: "\n"+NSLocalizedString("_files_no_files_", comment: ""), attributes: attributes)
  147. } else {
  148. return NSAttributedString.init(string: "\n"+NSLocalizedString("_files_no_folders_", comment: ""), attributes: attributes)
  149. }
  150. }
  151. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  152. return true
  153. }
  154. // MARK: BKPASSCODEVIEWCONTROLLER
  155. func passcodeViewController(_ aViewController: BKPasscodeViewController!, didFinishWithPasscode aPasscode: String!) {
  156. aViewController.dismiss(animated: true, completion: nil)
  157. performSegueDirectoryWithControlPasscode(controlPasscode: false)
  158. }
  159. func passcodeViewController(_ aViewController: BKPasscodeViewController!, authenticatePasscode aPasscode: String!, resultHandler aResultHandler: ((Bool) -> Void)!) {
  160. if aPasscode == CCUtility.getBlockCode() {
  161. failedAttempts = 0
  162. lockUntilDate = nil
  163. aResultHandler(true)
  164. } else {
  165. aResultHandler(false)
  166. }
  167. }
  168. func passcodeViewControllerDidFailAttempt(_ aViewController: BKPasscodeViewController!) {
  169. failedAttempts += 1
  170. if failedAttempts > 5 {
  171. var timeInterval: TimeInterval = 60
  172. if failedAttempts > 6 {
  173. let multiplier: Double = failedAttempts - 6
  174. timeInterval = (5 * 60) * multiplier
  175. if timeInterval > 3600 * 24 {
  176. timeInterval = 3600 * 24
  177. }
  178. }
  179. lockUntilDate = NSDate.init(timeIntervalSinceNow: timeInterval)
  180. }
  181. }
  182. func passcodeViewControllerNumber(ofFailedAttempts aViewController: BKPasscodeViewController!) -> UInt {
  183. return UInt(failedAttempts)
  184. }
  185. func passcodeViewControllerLock(untilDate aViewController: BKPasscodeViewController!) -> Date? {
  186. return lockUntilDate as Date?
  187. }
  188. @objc func passcodeViewCloseButtonPressed(_ sender: Any) {
  189. self.dismiss(animated: true, completion: nil)
  190. }
  191. // MARK: ACTION
  192. @IBAction func actionCancel(_ sender: Any) {
  193. delegate?.dismissSelect(serverUrl: nil, metadata: nil, type: type)
  194. self.dismiss(animated: true, completion: nil)
  195. }
  196. @IBAction func actionDone(_ sender: Any) {
  197. delegate?.dismissSelect(serverUrl: serverUrl, metadata: nil, type: type)
  198. self.dismiss(animated: true, completion: nil)
  199. }
  200. @IBAction func actionCreateFolder(_ sender: Any) {
  201. let alertController = UIAlertController(title: NSLocalizedString("_create_folder_", comment: ""), message:"", preferredStyle: .alert)
  202. alertController.addTextField { (textField) in
  203. textField.autocapitalizationType = UITextAutocapitalizationType.words
  204. }
  205. let actionSave = UIAlertAction(title: NSLocalizedString("_save_", comment: ""), style: .default) { (action:UIAlertAction) in
  206. if let fileName = alertController.textFields?.first?.text {
  207. self.createFolder(with: fileName)
  208. }
  209. }
  210. let actionCancel = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  211. print("You've pressed cancel button")
  212. }
  213. alertController.addAction(actionSave)
  214. alertController.addAction(actionCancel)
  215. self.present(alertController, animated: true, completion:nil)
  216. }
  217. // MARK: TAP EVENT
  218. func tapSwitchHeader(sender: Any) {
  219. if collectionView.collectionViewLayout == gridLayout {
  220. // list layout
  221. UIView.animate(withDuration: 0.0, animations: {
  222. self.collectionView.collectionViewLayout.invalidateLayout()
  223. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  224. self.collectionView.reloadData()
  225. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  226. })
  227. })
  228. typeLayout = "list"
  229. NCUtility.sharedInstance.setLayoutForView(key: layoutViewSelect, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  230. } else {
  231. // grid layout
  232. UIView.animate(withDuration: 0.0, animations: {
  233. self.collectionView.collectionViewLayout.invalidateLayout()
  234. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  235. self.collectionView.reloadData()
  236. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  237. })
  238. })
  239. typeLayout = "grid"
  240. NCUtility.sharedInstance.setLayoutForView(key: layoutViewSelect, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  241. }
  242. }
  243. func tapOrderHeader(sender: Any) {
  244. var menuView: DropdownMenu?
  245. var selectedIndexPath = [IndexPath()]
  246. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameAZ"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_a_z_", comment: ""))
  247. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameZA"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_z_a_", comment: ""))
  248. let item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateMoreRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_more_recent_", comment: ""))
  249. let item4 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateLessRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_less_recent_", comment: ""))
  250. let item5 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortSmallest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_smallest_", comment: ""))
  251. let item6 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortLargest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_largest_", comment: ""))
  252. switch datasourceSorted {
  253. case "fileName":
  254. if datasourceAscending == true { item1.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 0)) }
  255. if datasourceAscending == false { item2.style = .highlight; selectedIndexPath.append(IndexPath(row: 1, section: 0)) }
  256. case "date":
  257. if datasourceAscending == false { item3.style = .highlight; selectedIndexPath.append(IndexPath(row: 2, section: 0)) }
  258. if datasourceAscending == true { item4.style = .highlight; selectedIndexPath.append(IndexPath(row: 3, section: 0)) }
  259. case "size":
  260. if datasourceAscending == true { item5.style = .highlight; selectedIndexPath.append(IndexPath(row: 4, section: 0)) }
  261. if datasourceAscending == false { item6.style = .highlight; selectedIndexPath.append(IndexPath(row: 5, section: 0)) }
  262. default:
  263. ()
  264. }
  265. let item7 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByAlphabetic"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_alphabetic_no_", comment: ""))
  266. let item8 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByFile"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_typefile_no_", comment: ""))
  267. let item9 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByDate"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_date_no_", comment: ""))
  268. switch datasourceGroupBy {
  269. case "alphabetic":
  270. item7.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 1))
  271. case "typefile":
  272. item8.style = .highlight; selectedIndexPath.append(IndexPath(row: 1, section: 1))
  273. case "date":
  274. item9.style = .highlight; selectedIndexPath.append(IndexPath(row: 2, section: 1))
  275. default:
  276. ()
  277. }
  278. let item10 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "foldersOnTop"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_directory_on_top_no_", comment: ""))
  279. if datasourceDirectoryOnTop {
  280. item10.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 2))
  281. }
  282. let sectionOrder = DropdownSection(sectionIdentifier: "", items: [item1, item2, item3, item4, item5, item6])
  283. let sectionGroupBy = DropdownSection(sectionIdentifier: "", items: [item7, item8, item9])
  284. let sectionFolderOnTop = DropdownSection(sectionIdentifier: "", items: [item10])
  285. menuView = DropdownMenu(navigationController: self.navigationController!, sections: [sectionOrder, sectionGroupBy, sectionFolderOnTop], selectedIndexPath: selectedIndexPath)
  286. menuView?.token = "tapOrderHeaderMenu"
  287. menuView?.delegate = self
  288. menuView?.rowHeight = 45
  289. menuView?.sectionHeaderHeight = 8
  290. menuView?.highlightColor = NCBrandColor.sharedInstance.brand
  291. menuView?.tableView.alwaysBounceVertical = false
  292. menuView?.tableViewBackgroundColor = UIColor.white
  293. let header = (sender as? UIButton)?.superview
  294. let headerRect = self.collectionView.convert(header!.bounds, from: self.view)
  295. let menuOffsetY = headerRect.height - headerRect.origin.y - 2
  296. menuView?.topOffsetY = CGFloat(menuOffsetY)
  297. menuView?.showMenu()
  298. }
  299. func tapMoreHeader(sender: Any) {
  300. }
  301. func tapMoreListItem(with fileID: String, sender: Any) {
  302. }
  303. func tapMoreGridItem(with fileID: String, sender: Any) {
  304. }
  305. // MARK: DROP-DOWN-MENU
  306. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  307. if dropdownMenu.token == "tapOrderHeaderMenu" {
  308. switch indexPath.section {
  309. case 0: switch indexPath.row {
  310. case 0: datasourceSorted = "fileName"; datasourceAscending = true
  311. case 1: datasourceSorted = "fileName"; datasourceAscending = false
  312. case 2: datasourceSorted = "date"; datasourceAscending = false
  313. case 3: datasourceSorted = "date"; datasourceAscending = true
  314. case 4: datasourceSorted = "size"; datasourceAscending = true
  315. case 5: datasourceSorted = "size"; datasourceAscending = false
  316. default: ()
  317. }
  318. case 1: switch indexPath.row {
  319. case 0:
  320. if datasourceGroupBy == "alphabetic" {
  321. datasourceGroupBy = "none"
  322. } else {
  323. datasourceGroupBy = "alphabetic"
  324. }
  325. case 1:
  326. if datasourceGroupBy == "typefile" {
  327. datasourceGroupBy = "none"
  328. } else {
  329. datasourceGroupBy = "typefile"
  330. }
  331. case 2:
  332. if datasourceGroupBy == "date" {
  333. datasourceGroupBy = "none"
  334. } else {
  335. datasourceGroupBy = "date"
  336. }
  337. default: ()
  338. }
  339. case 2:
  340. if datasourceDirectoryOnTop {
  341. datasourceDirectoryOnTop = false
  342. } else {
  343. datasourceDirectoryOnTop = true
  344. }
  345. default: ()
  346. }
  347. NCUtility.sharedInstance.setLayoutForView(key: layoutViewSelect, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  348. loadDatasource(withLoadFolder: false)
  349. }
  350. if dropdownMenu.token == "tapMoreHeaderMenu" {
  351. }
  352. if dropdownMenu.token == "tapMoreHeaderMenuSelect" {
  353. }
  354. }
  355. // MARK: NC API
  356. func createFolder(with fileName: String) {
  357. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  358. ocNetworking?.createFolder(fileName, serverUrl: serverUrl, account: appDelegate.activeAccount, success: { (fileID, date) in
  359. self.loadDatasource(withLoadFolder: true)
  360. }, failure: { (message, errorCode) in
  361. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  362. })
  363. }
  364. func downloadThumbnail(with metadata: tableMetadata, indexPath: IndexPath) {
  365. let width = NCUtility.sharedInstance.getScreenWidthForPreview()
  366. let height = NCUtility.sharedInstance.getScreenHeightForPreview()
  367. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  368. ocNetworking?.downloadPreview(with: metadata, serverUrl: serverUrl, withWidth: width, andHeight: height, completion: { (message, errorCode) in
  369. if errorCode == 0 && CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) {
  370. self.collectionView.reloadItems(at: [indexPath])
  371. }
  372. })
  373. }
  374. func loadFolder() {
  375. networkInProgress = true
  376. collectionView.reloadData()
  377. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  378. ocNetworking?.readFolder(serverUrl, depth: "1", account: appDelegate.activeAccount, success: { (metadatas, metadataFolder, directoryID) in
  379. // Update directory etag
  380. NCManageDatabase.sharedInstance.setDirectory(serverUrl: self.serverUrl, serverUrlTo: nil, etag: metadataFolder?.etag, fileID: metadataFolder?.fileID, encrypted: metadataFolder!.e2eEncrypted)
  381. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "directoryID == %@ AND (status == %d OR status == %d)", directoryID!, k_metadataStatusNormal, k_metadataStatusHide), clearDateReadDirectoryID: directoryID)
  382. NCManageDatabase.sharedInstance.setDateReadDirectory(directoryID: directoryID!)
  383. _ = NCManageDatabase.sharedInstance.addMetadatas(metadatas as! [tableMetadata], serverUrl: self.serverUrl)
  384. 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) {
  385. _ = NCManageDatabase.sharedInstance.addMetadatas(metadatasInDownload, serverUrl: self.serverUrl)
  386. }
  387. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  388. self.networkInProgress = false
  389. self.loadDatasource(withLoadFolder: false)
  390. }
  391. }, failure: { (message, errorCode) in
  392. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  393. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  394. self.networkInProgress = false
  395. self.loadDatasource(withLoadFolder: false)
  396. }
  397. })
  398. }
  399. // MARK: DATASOURCE
  400. @objc func loadDatasource(withLoadFolder: Bool) {
  401. sectionDatasource = CCSectionDataSourceMetadata()
  402. var predicate: NSPredicate?
  403. if directoryID == "" {
  404. serverUrl = CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl)
  405. directoryID = NCManageDatabase.sharedInstance.getDirectoryID(serverUrl) ?? ""
  406. }
  407. if includeDirectoryE2EEncryption {
  408. if includeImages {
  409. predicate = NSPredicate(format: "directoryID == %@ AND (directory == true OR typeFile == 'image')", directoryID)
  410. } else {
  411. predicate = NSPredicate(format: "directoryID == %@ AND directory == true", directoryID)
  412. }
  413. } else {
  414. if includeImages {
  415. predicate = NSPredicate(format: "directoryID == %@ AND e2eEncrypted == false AND (directory == true OR typeFile == 'image')", directoryID)
  416. } else {
  417. predicate = NSPredicate(format: "directoryID == %@ AND e2eEncrypted == false AND directory == true", directoryID)
  418. }
  419. }
  420. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: predicate!, sorted: datasourceSorted, ascending: datasourceAscending) {
  421. sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: datasourceGroupBy, filterFileID: nil, filterTypeFileImage: false, filterTypeFileVideo: false, activeAccount: appDelegate.activeAccount)
  422. }
  423. if withLoadFolder {
  424. loadFolder()
  425. } else {
  426. self.refreshControl.endRefreshing()
  427. }
  428. collectionView.reloadData()
  429. }
  430. // MARK: COLLECTIONVIEW METHODS
  431. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  432. if (indexPath.section == 0) {
  433. if kind == UICollectionView.elementKindSectionHeader {
  434. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  435. if collectionView.collectionViewLayout == gridLayout {
  436. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  437. } else {
  438. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  439. }
  440. header.delegate = self
  441. header.setStatusButton(count: sectionDatasource.allFileID.count)
  442. header.setTitleOrder(datasourceSorted: datasourceSorted, datasourceAscending: datasourceAscending)
  443. if datasourceGroupBy == "none" {
  444. header.labelSection.isHidden = true
  445. header.labelSectionHeightConstraint.constant = 0
  446. } else {
  447. header.labelSection.isHidden = false
  448. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  449. header.labelSectionHeightConstraint.constant = sectionHeaderHeight
  450. }
  451. return header
  452. } else {
  453. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  454. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  455. return footer
  456. }
  457. } else {
  458. if kind == UICollectionView.elementKindSectionHeader {
  459. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  460. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  461. return header
  462. } else {
  463. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  464. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  465. return footer
  466. }
  467. }
  468. }
  469. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  470. if section == 0 {
  471. if datasourceGroupBy == "none" {
  472. return CGSize(width: collectionView.frame.width, height: headerMenuHeight)
  473. } else {
  474. return CGSize(width: collectionView.frame.width, height: headerMenuHeight + sectionHeaderHeight)
  475. }
  476. } else {
  477. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  478. }
  479. }
  480. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  481. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  482. if (section == sections - 1) {
  483. return CGSize(width: collectionView.frame.width, height: footerHeight)
  484. } else {
  485. return CGSize(width: collectionView.frame.width, height: 0)
  486. }
  487. }
  488. func numberOfSections(in collectionView: UICollectionView) -> Int {
  489. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  490. return sections
  491. }
  492. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  493. let key = sectionDatasource.sections.object(at: section)
  494. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  495. return datasource.count
  496. }
  497. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  498. var image: UIImage?
  499. var imagePreview = false
  500. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  501. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  502. }
  503. if metadata.iconName.count > 0 {
  504. image = UIImage.init(named: metadata.iconName)
  505. } else {
  506. image = UIImage.init(named: "file")
  507. }
  508. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileName)) {
  509. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileName))
  510. imagePreview = true
  511. } else {
  512. if metadata.hasPreview == 1 && !CCUtility.fileProviderStorageIconExists(metadata.fileID, fileNameView: metadata.fileName) {
  513. downloadThumbnail(with: metadata, indexPath: indexPath)
  514. }
  515. }
  516. if collectionView.collectionViewLayout == listLayout {
  517. // LIST
  518. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  519. cell.delegate = self
  520. // hide button more
  521. cell.hideButtonMore()
  522. cell.fileID = metadata.fileID
  523. cell.indexPath = indexPath
  524. cell.labelTitle.text = metadata.fileNameView
  525. cell.imageStatus.image = nil
  526. cell.imageLocal.image = nil
  527. cell.imageFavorite.image = nil
  528. if metadata.directory {
  529. cell.imageItem.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  530. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  531. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  532. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  533. // Status image: passcode
  534. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  535. cell.imageStatus.image = UIImage.init(named: "passcode")
  536. }
  537. // Local image: offline
  538. if tableDirectory != nil && tableDirectory!.offline {
  539. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  540. }
  541. } else {
  542. cell.imageItem.image = image
  543. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " " + CCUtility.transformedSize(metadata.size)
  544. // image Local
  545. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  546. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  547. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  548. else { cell.imageLocal.image = UIImage.init(named: "local") }
  549. }
  550. }
  551. // image Favorite
  552. if metadata.favorite {
  553. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  554. }
  555. if isEditMode {
  556. cell.imageItemLeftConstraint.constant = 45
  557. cell.imageSelect.isHidden = false
  558. if selectFileID.contains(metadata.fileID) {
  559. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: NCBrandColor.sharedInstance.brand)
  560. cell.backgroundView = cellBlurEffect(with: cell.bounds)
  561. } else {
  562. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedNo"), multiplier: 2, color: NCBrandColor.sharedInstance.optionItem)
  563. cell.backgroundView = nil
  564. }
  565. } else {
  566. cell.imageItemLeftConstraint.constant = 10
  567. cell.imageSelect.isHidden = true
  568. cell.backgroundView = nil
  569. }
  570. // Remove last separator
  571. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  572. cell.separator.isHidden = true
  573. } else {
  574. cell.separator.isHidden = false
  575. }
  576. return cell
  577. } else {
  578. // GRID
  579. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  580. cell.delegate = self
  581. // hide button more
  582. cell.hideButtonMore()
  583. cell.fileID = metadata.fileID
  584. cell.indexPath = indexPath
  585. cell.labelTitle.text = metadata.fileNameView
  586. cell.imageStatus.image = nil
  587. cell.imageLocal.image = nil
  588. cell.imageFavorite.image = nil
  589. if metadata.directory {
  590. image = UIImage.init(named: "folder")
  591. cell.imageItem.image = CCGraphics.changeThemingColorImage(image, width: image!.size.width*6, height: image!.size.height*6, scale: 3.0, color: NCBrandColor.sharedInstance.brandElement)
  592. cell.imageItem.contentMode = .center
  593. let lockServerUrl = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName)!
  594. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl))
  595. // Status image: passcode
  596. if tableDirectory != nil && tableDirectory!.lock && CCUtility.getBlockCode() != nil {
  597. cell.imageStatus.image = UIImage.init(named: "passcode")
  598. }
  599. // Local image: offline
  600. if tableDirectory != nil && tableDirectory!.offline {
  601. cell.imageLocal.image = UIImage.init(named: "offlineFlag")
  602. }
  603. } else {
  604. cell.imageItem.image = image
  605. if imagePreview == false {
  606. let width = cell.imageItem.image!.size.width * 2
  607. //let scale = UIScreen.main.scale
  608. cell.imageItem.image = NCUtility.sharedInstance.resizeImage(image: image!, newWidth: width)
  609. cell.imageItem.contentMode = .center
  610. }
  611. // image Local
  612. let tableLocalFile = NCManageDatabase.sharedInstance.getTableLocalFile(predicate: NSPredicate(format: "fileID == %@", metadata.fileID))
  613. if tableLocalFile != nil && CCUtility.fileProviderStorageExists(metadata.fileID, fileNameView: metadata.fileNameView) {
  614. if tableLocalFile!.offline { cell.imageLocal.image = UIImage.init(named: "offlineFlag") }
  615. else { cell.imageLocal.image = UIImage.init(named: "local") }
  616. }
  617. }
  618. // image Favorite
  619. if metadata.favorite {
  620. cell.imageFavorite.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "favorite"), multiplier: 2, color: NCBrandColor.sharedInstance.yellowFavorite)
  621. }
  622. if isEditMode {
  623. cell.imageSelect.isHidden = false
  624. if selectFileID.contains(metadata.fileID) {
  625. cell.imageSelect.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "checkedYes"), multiplier: 2, color: UIColor.white)
  626. cell.backgroundView = cellBlurEffect(with: cell.bounds)
  627. } else {
  628. cell.imageSelect.isHidden = true
  629. cell.backgroundView = nil
  630. }
  631. } else {
  632. cell.imageSelect.isHidden = true
  633. cell.backgroundView = nil
  634. }
  635. return cell
  636. }
  637. }
  638. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  639. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  640. return
  641. }
  642. if isEditMode {
  643. if let index = selectFileID.index(of: metadata.fileID) {
  644. selectFileID.remove(at: index)
  645. } else {
  646. selectFileID.append(metadata.fileID)
  647. }
  648. collectionView.reloadItems(at: [indexPath])
  649. return
  650. }
  651. if metadata.directory {
  652. guard let serverUrl = NCManageDatabase.sharedInstance.getServerUrl(metadata.directoryID) else {
  653. return
  654. }
  655. guard let serverUrlPush = CCUtility.stringAppendServerUrl(serverUrl, addFileName: metadata.fileName) else {
  656. return
  657. }
  658. guard let directoryIDPush = NCManageDatabase.sharedInstance.getDirectoryID(serverUrlPush) else {
  659. return
  660. }
  661. self.serverUrlPush = serverUrlPush
  662. self.directoryIDPush = directoryIDPush
  663. self.metadataPush = metadata
  664. performSegueDirectoryWithControlPasscode(controlPasscode: true)
  665. } else {
  666. delegate?.dismissSelect(serverUrl: serverUrl, metadata: metadata, type: type)
  667. self.dismiss(animated: true, completion: nil)
  668. }
  669. }
  670. // MARK: NAVIGATION
  671. private func performSegueDirectoryWithControlPasscode(controlPasscode: Bool) {
  672. guard let directoryPush = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "directoryID == %@", directoryIDPush)) else {
  673. return
  674. }
  675. if directoryPush.lock == true && CCUtility.getBlockCode() != nil && (CCUtility.getBlockCode()?.count)! > 0 && controlPasscode {
  676. let viewController = CCBKPasscode.init(nibName: nil, bundle: nil)
  677. guard let touchIDManager = BKTouchIDManager.init(keychainServiceName: k_serviceShareKeyChain) else {
  678. return
  679. }
  680. touchIDManager.promptText = NSLocalizedString("_scan_fingerprint_", comment: "")
  681. viewController.delegate = self
  682. viewController.type = BKPasscodeViewControllerCheckPasscodeType
  683. viewController.inputViewTitlePassword = true
  684. if CCUtility.getSimplyBlockCode() {
  685. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle
  686. viewController.passcodeInputView.maximumLength = 6
  687. } else {
  688. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle
  689. viewController.passcodeInputView.maximumLength = 64
  690. }
  691. viewController.touchIDManager = touchIDManager
  692. viewController.title = NSLocalizedString("_folder_blocked_", comment: "")
  693. viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: #selector(passcodeViewCloseButtonPressed(_:)))
  694. viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor.black
  695. let navigationController = UINavigationController.init(rootViewController: viewController)
  696. self.present(navigationController, animated: true, completion: nil)
  697. return
  698. }
  699. guard let visualController = UIStoryboard(name: "NCSelect", bundle: nil).instantiateViewController(withIdentifier: "NCSelect.storyboard") as? NCSelect else {
  700. return
  701. }
  702. visualController.delegate = delegate
  703. visualController.hideButtonCreateFolder = hideButtonCreateFolder
  704. visualController.selectFile = selectFile
  705. visualController.includeDirectoryE2EEncryption = includeDirectoryE2EEncryption
  706. visualController.includeImages = includeImages
  707. visualController.type = type
  708. visualController.titleButtonDone = titleButtonDone
  709. visualController.layoutViewSelect = layoutViewSelect
  710. visualController.titleCurrentFolder = metadataPush!.fileNameView
  711. visualController.serverUrl = serverUrlPush
  712. visualController.directoryID = directoryIDPush
  713. self.navigationController?.pushViewController(visualController, animated: true)
  714. }
  715. // MARK: UTILITY
  716. private func cellBlurEffect(with frame: CGRect) -> UIView {
  717. let blurEffect = UIBlurEffect(style: .extraLight)
  718. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  719. blurEffectView.frame = frame
  720. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  721. blurEffectView.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.2)
  722. return blurEffectView
  723. }
  724. private func actionSheetHeader(with metadata: tableMetadata) -> UIView? {
  725. var image: UIImage?
  726. // Header
  727. if metadata.directory {
  728. image = CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 3, color: NCBrandColor.sharedInstance.brandElement)
  729. } else if metadata.iconName.count > 0 {
  730. image = UIImage.init(named: metadata.iconName)
  731. } else {
  732. image = UIImage.init(named: "file")
  733. }
  734. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView)) {
  735. image = UIImage.init(contentsOfFile: CCUtility.getDirectoryProviderStorageIconFileID(metadata.fileID, fileNameView: metadata.fileNameView))
  736. }
  737. let headerView = UINib(nibName: "NCActionSheetHeaderView", bundle: nil).instantiate(withOwner: self, options: nil).first as! NCActionSheetHeaderView
  738. headerView.imageItem.image = image
  739. headerView.label.text = metadata.fileNameView
  740. headerView.label.textColor = NCBrandColor.sharedInstance.icon
  741. return headerView
  742. }
  743. }