NCSelect.swift 38 KB

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