NCSelect.swift 39 KB

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