NCSelect.swift 38 KB

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