NCSelect.swift 38 KB

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