NCSelect.swift 37 KB

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