NCSelect.swift 37 KB

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