NCSelect.swift 38 KB

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