NCOffline.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. //
  2. // NCOffline.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 24/10/2018.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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. import Sheeeeeeeeet
  25. class NCOffline: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, BKPasscodeViewControllerDelegate {
  26. @IBOutlet fileprivate weak var collectionView: UICollectionView!
  27. var titleCurrentFolder = NSLocalizedString("_manage_file_offline_", comment: "")
  28. var serverUrl = ""
  29. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  30. private var metadataPush: tableMetadata?
  31. private var isEditMode = false
  32. private var selectFileID = [String]()
  33. private var sectionDatasource = CCSectionDataSourceMetadata()
  34. private var typeLayout = ""
  35. private var datasourceSorted = ""
  36. private var datasourceAscending = true
  37. private var datasourceGroupBy = ""
  38. private var datasourceDirectoryOnTop = false
  39. private var autoUploadFileName = ""
  40. private var autoUploadDirectory = ""
  41. private var listLayout: NCListLayout!
  42. private var gridLayout: NCGridLayout!
  43. private var actionSheet: ActionSheet?
  44. private let headerMenuHeight: CGFloat = 50
  45. private let sectionHeaderHeight: CGFloat = 20
  46. private let footerHeight: CGFloat = 50
  47. private let refreshControl = UIRefreshControl()
  48. //BKPasscodeViewController
  49. private var failedAttempts: Double = 0
  50. private var lockUntilDate: NSDate?
  51. override func viewDidLoad() {
  52. super.viewDidLoad()
  53. // Cell
  54. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  55. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  56. // Header
  57. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  58. collectionView.register(UINib.init(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  59. // Footer
  60. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  61. collectionView.alwaysBounceVertical = true
  62. listLayout = NCListLayout()
  63. gridLayout = NCGridLayout()
  64. // Add Refresh Control
  65. if #available(iOS 10.0, *) {
  66. collectionView.refreshControl = refreshControl
  67. } else {
  68. collectionView.addSubview(refreshControl)
  69. }
  70. // Configure Refresh Control
  71. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  72. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  73. refreshControl.addTarget(self, action: #selector(loadDatasource), for: .valueChanged)
  74. // empty Data Source
  75. self.collectionView.emptyDataSetDelegate = self;
  76. self.collectionView.emptyDataSetSource = self;
  77. }
  78. override func viewWillAppear(_ animated: Bool) {
  79. super.viewWillAppear(animated)
  80. // Color
  81. appDelegate.aspectNavigationControllerBar(self.navigationController?.navigationBar, online: appDelegate.reachability.isReachable(), hidden: false)
  82. appDelegate.aspectTabBar(self.tabBarController?.tabBar, hidden: false)
  83. self.navigationItem.title = titleCurrentFolder
  84. (typeLayout, datasourceSorted, datasourceAscending, datasourceGroupBy, datasourceDirectoryOnTop) = NCUtility.sharedInstance.getLayoutForView(key: k_layout_view_offline)
  85. // get auto upload folder
  86. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  87. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(appDelegate.activeUrl)
  88. if typeLayout == k_layout_list {
  89. collectionView.collectionViewLayout = listLayout
  90. } else {
  91. collectionView.collectionViewLayout = gridLayout
  92. }
  93. loadDatasource()
  94. }
  95. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  96. super.viewWillTransition(to: size, with: coordinator)
  97. coordinator.animate(alongsideTransition: nil) { _ in
  98. self.collectionView.collectionViewLayout.invalidateLayout()
  99. self.actionSheet?.viewDidLayoutSubviews()
  100. }
  101. }
  102. // MARK: DZNEmpty
  103. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  104. return NCBrandColor.sharedInstance.backgroundView
  105. }
  106. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  107. return CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), multiplier: 1, color: NCBrandColor.sharedInstance.brandElement)
  108. }
  109. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  110. let text = "\n"+NSLocalizedString("_files_no_files_", comment: "")
  111. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  112. return NSAttributedString.init(string: text, attributes: attributes)
  113. }
  114. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  115. return true
  116. }
  117. // MARK: BKPASSCODEVIEWCONTROLLER
  118. func passcodeViewController(_ aViewController: BKPasscodeViewController!, didFinishWithPasscode aPasscode: String!) {
  119. aViewController.dismiss(animated: true, completion: nil)
  120. performSegueDirectoryWithControlPasscode(controlPasscode: false)
  121. }
  122. func passcodeViewController(_ aViewController: BKPasscodeViewController!, authenticatePasscode aPasscode: String!, resultHandler aResultHandler: ((Bool) -> Void)!) {
  123. if aPasscode == CCUtility.getBlockCode() {
  124. failedAttempts = 0
  125. lockUntilDate = nil
  126. aResultHandler(true)
  127. } else {
  128. aResultHandler(false)
  129. }
  130. }
  131. func passcodeViewControllerDidFailAttempt(_ aViewController: BKPasscodeViewController!) {
  132. failedAttempts += 1
  133. if failedAttempts > 5 {
  134. var timeInterval: TimeInterval = 60
  135. if failedAttempts > 6 {
  136. let multiplier: Double = failedAttempts - 6
  137. timeInterval = (5 * 60) * multiplier
  138. if timeInterval > 3600 * 24 {
  139. timeInterval = 3600 * 24
  140. }
  141. }
  142. lockUntilDate = NSDate.init(timeIntervalSinceNow: timeInterval)
  143. }
  144. }
  145. func passcodeViewControllerNumber(ofFailedAttempts aViewController: BKPasscodeViewController!) -> UInt {
  146. return UInt(failedAttempts)
  147. }
  148. func passcodeViewControllerLock(untilDate aViewController: BKPasscodeViewController!) -> Date? {
  149. return lockUntilDate as Date?
  150. }
  151. @objc func passcodeViewCloseButtonPressed(_ sender: Any) {
  152. self.dismiss(animated: true, completion: nil)
  153. }
  154. // MARK: TAP EVENT
  155. func tapSwitchHeader(sender: Any) {
  156. if collectionView.collectionViewLayout == gridLayout {
  157. // list layout
  158. UIView.animate(withDuration: 0.0, animations: {
  159. self.collectionView.collectionViewLayout.invalidateLayout()
  160. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  161. self.collectionView.reloadData()
  162. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  163. })
  164. })
  165. typeLayout = k_layout_list
  166. NCUtility.sharedInstance.setLayoutForView(key: k_layout_view_offline, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  167. } else {
  168. // grid layout
  169. UIView.animate(withDuration: 0.0, animations: {
  170. self.collectionView.collectionViewLayout.invalidateLayout()
  171. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  172. self.collectionView.reloadData()
  173. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  174. })
  175. })
  176. typeLayout = k_layout_grid
  177. NCUtility.sharedInstance.setLayoutForView(key: k_layout_view_offline, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  178. }
  179. }
  180. func tapOrderHeader(sender: Any) {
  181. var menuView: DropdownMenu?
  182. var selectedIndexPath = [IndexPath()]
  183. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameAZ"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_a_z_", comment: ""))
  184. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameZA"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_z_a_", comment: ""))
  185. let item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateMoreRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_more_recent_", comment: ""))
  186. let item4 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateLessRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_less_recent_", comment: ""))
  187. let item5 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortSmallest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_smallest_", comment: ""))
  188. let item6 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortLargest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_largest_", comment: ""))
  189. switch datasourceSorted {
  190. case "fileName":
  191. if datasourceAscending == true { item1.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 0)) }
  192. if datasourceAscending == false { item2.style = .highlight; selectedIndexPath.append(IndexPath(row: 1, section: 0)) }
  193. case "date":
  194. if datasourceAscending == false { item3.style = .highlight; selectedIndexPath.append(IndexPath(row: 2, section: 0)) }
  195. if datasourceAscending == true { item4.style = .highlight; selectedIndexPath.append(IndexPath(row: 3, section: 0)) }
  196. case "size":
  197. if datasourceAscending == true { item5.style = .highlight; selectedIndexPath.append(IndexPath(row: 4, section: 0)) }
  198. if datasourceAscending == false { item6.style = .highlight; selectedIndexPath.append(IndexPath(row: 5, section: 0)) }
  199. default:
  200. ()
  201. }
  202. let item7 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByAlphabetic"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_alphabetic_no_", comment: ""))
  203. let item8 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByFile"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_typefile_no_", comment: ""))
  204. let item9 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByDate"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_date_no_", comment: ""))
  205. switch datasourceGroupBy {
  206. case "alphabetic":
  207. item7.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 1))
  208. case "typefile":
  209. item8.style = .highlight; selectedIndexPath.append(IndexPath(row: 1, section: 1))
  210. case "date":
  211. item9.style = .highlight; selectedIndexPath.append(IndexPath(row: 2, section: 1))
  212. default:
  213. ()
  214. }
  215. let item10 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "foldersOnTop"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_directory_on_top_no_", comment: ""))
  216. if datasourceDirectoryOnTop {
  217. item10.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 2))
  218. }
  219. let sectionOrder = DropdownSection(sectionIdentifier: "", items: [item1, item2, item3, item4, item5, item6])
  220. let sectionGroupBy = DropdownSection(sectionIdentifier: "", items: [item7, item8, item9])
  221. let sectionFolderOnTop = DropdownSection(sectionIdentifier: "", items: [item10])
  222. menuView = DropdownMenu(navigationController: self.navigationController!, sections: [sectionOrder, sectionGroupBy, sectionFolderOnTop], selectedIndexPath: selectedIndexPath)
  223. menuView?.token = "tapOrderHeaderMenu"
  224. menuView?.delegate = self
  225. menuView?.rowHeight = 45
  226. menuView?.sectionHeaderHeight = 8
  227. menuView?.highlightColor = NCBrandColor.sharedInstance.brand
  228. menuView?.tableView.alwaysBounceVertical = false
  229. menuView?.tableViewBackgroundColor = UIColor.white
  230. let header = (sender as? UIButton)?.superview
  231. let headerRect = self.collectionView.convert(header!.bounds, from: self.view)
  232. let menuOffsetY = headerRect.height - headerRect.origin.y - 2
  233. menuView?.topOffsetY = CGFloat(menuOffsetY)
  234. menuView?.showMenu()
  235. }
  236. func tapMoreHeader(sender: Any) {
  237. }
  238. func tapMoreListItem(with fileID: String, sender: Any) {
  239. tapMoreGridItem(with: fileID, sender: sender)
  240. }
  241. func tapMoreGridItem(with fileID: String, sender: Any) {
  242. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileID == %@", fileID)) else {
  243. return
  244. }
  245. if !isEditMode {
  246. var items = [ActionSheetItem]()
  247. let appearanceDelete = ActionSheetItemAppearance.init()
  248. appearanceDelete.textColor = UIColor.red
  249. // 0 == CCMore, 1 = first NCOffline ....
  250. if (self == self.navigationController?.viewControllers[1]) {
  251. items.append(ActionSheetItem(title: NSLocalizedString("_remove_available_offline_", comment: ""), value: 0, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "offline"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)))
  252. }
  253. items.append(ActionSheetItem(title: NSLocalizedString("_share_", comment: ""), value: 1, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "share"), multiplier: 2, color: NCBrandColor.sharedInstance.icon)))
  254. let itemDelete = ActionSheetItem(title: NSLocalizedString("_delete_", comment: ""), value: 2, image: CCGraphics.changeThemingColorImage(UIImage.init(named: "trash75"), multiplier: 1, color: UIColor.red))
  255. itemDelete.customAppearance = appearanceDelete
  256. items.append(itemDelete)
  257. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  258. actionSheet = ActionSheet(items: items) { sheet, item in
  259. if item.value as? Int == 0 {
  260. if metadata.directory {
  261. NCManageDatabase.sharedInstance.setDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!, offline: false, account: self.appDelegate.activeAccount)
  262. } else {
  263. NCManageDatabase.sharedInstance.setLocalFile(fileID: metadata.fileID, offline: false)
  264. }
  265. self.loadDatasource()
  266. }
  267. if item.value as? Int == 1 { self.appDelegate.activeMain.readShare(withAccount: self.appDelegate.activeAccount, openWindow: true, metadata: metadata) }
  268. if item.value as? Int == 2 { self.deleteItem(with: metadata, sender: sender) }
  269. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  270. }
  271. let headerView = NCActionSheetHeader.sharedInstance.actionSheetHeader(isDirectory: metadata.directory, iconName: metadata.iconName, fileID: metadata.fileID, fileNameView: metadata.fileNameView, text: metadata.fileNameView)
  272. actionSheet?.headerView = headerView
  273. actionSheet?.headerView?.frame.size.height = 50
  274. actionSheet?.present(in: self, from: sender as! UIButton)
  275. } else {
  276. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  277. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  278. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  279. }
  280. }
  281. // MARK: DROP-DOWN-MENU
  282. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  283. if dropdownMenu.token == "tapOrderHeaderMenu" {
  284. switch indexPath.section {
  285. case 0: switch indexPath.row {
  286. case 0: datasourceSorted = "fileName"; datasourceAscending = true
  287. case 1: datasourceSorted = "fileName"; datasourceAscending = false
  288. case 2: datasourceSorted = "date"; datasourceAscending = false
  289. case 3: datasourceSorted = "date"; datasourceAscending = true
  290. case 4: datasourceSorted = "size"; datasourceAscending = true
  291. case 5: datasourceSorted = "size"; datasourceAscending = false
  292. default: ()
  293. }
  294. case 1: switch indexPath.row {
  295. case 0:
  296. if datasourceGroupBy == "alphabetic" {
  297. datasourceGroupBy = "none"
  298. } else {
  299. datasourceGroupBy = "alphabetic"
  300. }
  301. case 1:
  302. if datasourceGroupBy == "typefile" {
  303. datasourceGroupBy = "none"
  304. } else {
  305. datasourceGroupBy = "typefile"
  306. }
  307. case 2:
  308. if datasourceGroupBy == "date" {
  309. datasourceGroupBy = "none"
  310. } else {
  311. datasourceGroupBy = "date"
  312. }
  313. default: ()
  314. }
  315. case 2:
  316. if datasourceDirectoryOnTop {
  317. datasourceDirectoryOnTop = false
  318. } else {
  319. datasourceDirectoryOnTop = true
  320. }
  321. default: ()
  322. }
  323. NCUtility.sharedInstance.setLayoutForView(key: k_layout_view_offline, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  324. loadDatasource()
  325. }
  326. if dropdownMenu.token == "tapMoreHeaderMenu" {
  327. }
  328. if dropdownMenu.token == "tapMoreHeaderMenuSelect" {
  329. }
  330. }
  331. // MARK: NC API
  332. func deleteItem(with metadata: tableMetadata, sender: Any) {
  333. var items = [ActionSheetItem]()
  334. guard let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == serverUrl", appDelegate.activeAccount, metadata.serverUrl)) else {
  335. return
  336. }
  337. items.append(ActionSheetDangerButton(title: NSLocalizedString("_delete_", comment: "")))
  338. items.append(ActionSheetCancelButton(title: NSLocalizedString("_cancel_", comment: "")))
  339. actionSheet = ActionSheet(items: items) { sheet, item in
  340. if item is ActionSheetDangerButton {
  341. NCMainCommon.sharedInstance.deleteFile(metadatas: [metadata], e2ee: tableDirectory.e2eEncrypted, serverUrl: tableDirectory.serverUrl, folderFileID: tableDirectory.fileID) { (errorCode, message) in
  342. self.loadDatasource()
  343. }
  344. }
  345. if item is ActionSheetCancelButton { print("Cancel buttons has the value `true`") }
  346. }
  347. let headerView = NCActionSheetHeader.sharedInstance.actionSheetHeader(isDirectory: metadata.directory, iconName: metadata.iconName, fileID: metadata.fileID, fileNameView: metadata.fileNameView, text: metadata.fileNameView)
  348. actionSheet?.headerView = headerView
  349. actionSheet?.headerView?.frame.size.height = 50
  350. actionSheet?.present(in: self, from: sender as! UIButton)
  351. }
  352. // MARK: DATASOURCE
  353. @objc func loadDatasource() {
  354. var fileIDs = [String]()
  355. sectionDatasource = CCSectionDataSourceMetadata()
  356. if serverUrl == "" {
  357. if let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true) {
  358. for directory: tableDirectory in directories {
  359. fileIDs.append(directory.fileID)
  360. }
  361. }
  362. if let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true) {
  363. for file: tableLocalFile in files {
  364. fileIDs.append(file.fileID)
  365. }
  366. }
  367. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND fileID IN %@", appDelegate.activeAccount, fileIDs), sorted: nil, ascending: false) {
  368. sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: datasourceGroupBy, filterFileID: nil, filterTypeFileImage: false, filterTypeFileVideo: false, sorted: datasourceSorted, ascending: datasourceAscending, activeAccount: appDelegate.activeAccount)
  369. }
  370. } else {
  371. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl), sorted: nil, ascending: false) {
  372. sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: datasourceGroupBy, filterFileID: nil, filterTypeFileImage: false, filterTypeFileVideo: false, sorted: datasourceSorted, ascending: datasourceAscending, activeAccount: appDelegate.activeAccount)
  373. }
  374. }
  375. self.refreshControl.endRefreshing()
  376. collectionView.reloadData()
  377. }
  378. // MARK: COLLECTIONVIEW METHODS
  379. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  380. if (indexPath.section == 0) {
  381. if kind == UICollectionView.elementKindSectionHeader {
  382. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  383. if collectionView.collectionViewLayout == gridLayout {
  384. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  385. } else {
  386. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  387. }
  388. header.delegate = self
  389. header.setStatusButton(count: sectionDatasource.allFileID.count)
  390. header.setTitleOrder(datasourceSorted: datasourceSorted, datasourceAscending: datasourceAscending)
  391. if datasourceGroupBy == "none" {
  392. header.labelSection.isHidden = true
  393. header.labelSectionHeightConstraint.constant = 0
  394. } else {
  395. header.labelSection.isHidden = false
  396. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  397. header.labelSectionHeightConstraint.constant = sectionHeaderHeight
  398. }
  399. return header
  400. } else {
  401. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  402. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  403. return footer
  404. }
  405. } else {
  406. if kind == UICollectionView.elementKindSectionHeader {
  407. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  408. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  409. return header
  410. } else {
  411. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  412. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  413. return footer
  414. }
  415. }
  416. }
  417. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  418. if section == 0 {
  419. if datasourceGroupBy == "none" {
  420. return CGSize(width: collectionView.frame.width, height: headerMenuHeight)
  421. } else {
  422. return CGSize(width: collectionView.frame.width, height: headerMenuHeight + sectionHeaderHeight)
  423. }
  424. } else {
  425. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  426. }
  427. }
  428. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  429. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  430. if (section == sections - 1) {
  431. return CGSize(width: collectionView.frame.width, height: footerHeight)
  432. } else {
  433. return CGSize(width: collectionView.frame.width, height: 0)
  434. }
  435. }
  436. func numberOfSections(in collectionView: UICollectionView) -> Int {
  437. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  438. return sections
  439. }
  440. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  441. let key = sectionDatasource.sections.object(at: section)
  442. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  443. return datasource.count
  444. }
  445. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  446. let cell: UICollectionViewCell
  447. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  448. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  449. }
  450. if typeLayout == k_layout_grid {
  451. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  452. } else {
  453. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  454. }
  455. NCMainCommon.sharedInstance.collectionViewCellForItemAt(indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: nil, serverUrl: metadata.serverUrl, isEditMode: isEditMode, selectFileID: selectFileID, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: false, downloadThumbnail: true, source: self)
  456. return cell
  457. }
  458. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  459. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  460. return
  461. }
  462. metadataPush = metadata
  463. if isEditMode {
  464. if let index = selectFileID.index(of: metadata.fileID) {
  465. selectFileID.remove(at: index)
  466. } else {
  467. selectFileID.append(metadata.fileID)
  468. }
  469. collectionView.reloadItems(at: [indexPath])
  470. return
  471. }
  472. if metadata.directory {
  473. performSegueDirectoryWithControlPasscode(controlPasscode: true)
  474. } else {
  475. performSegue(withIdentifier: "segueDetail", sender: self)
  476. }
  477. }
  478. // MARK: SEGUE
  479. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  480. let photoDataSource: NSMutableArray = []
  481. for fileID: String in sectionDatasource.allFileID as! [String] {
  482. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: fileID) as! tableMetadata
  483. if metadata.typeFile == k_metadataTypeFile_image {
  484. photoDataSource.add(metadata)
  485. }
  486. }
  487. if let segueNavigationController = segue.destination as? UINavigationController {
  488. if let segueViewController = segueNavigationController.topViewController as? CCDetail {
  489. segueViewController.metadataDetail = metadataPush
  490. segueViewController.dateFilterQuery = nil
  491. segueViewController.photoDataSource = photoDataSource
  492. segueViewController.title = metadataPush!.fileNameView
  493. }
  494. }
  495. }
  496. // MARK: NAVIGATION
  497. private func performSegueDirectoryWithControlPasscode(controlPasscode: Bool) {
  498. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataPush!.serverUrl, addFileName: metadataPush!.fileName) else {
  499. return
  500. }
  501. guard let directoryPush = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrlPush)) else {
  502. return
  503. }
  504. if directoryPush.lock == true && CCUtility.getBlockCode() != nil && (CCUtility.getBlockCode()?.count)! > 0 && controlPasscode {
  505. let viewController = CCBKPasscode.init(nibName: nil, bundle: nil)
  506. guard let touchIDManager = BKTouchIDManager.init(keychainServiceName: k_serviceShareKeyChain) else {
  507. return
  508. }
  509. touchIDManager.promptText = NSLocalizedString("_scan_fingerprint_", comment: "")
  510. viewController.delegate = self
  511. viewController.type = BKPasscodeViewControllerCheckPasscodeType
  512. viewController.inputViewTitlePassword = true
  513. if CCUtility.getSimplyBlockCode() {
  514. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle
  515. viewController.passcodeInputView.maximumLength = 6
  516. } else {
  517. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle
  518. viewController.passcodeInputView.maximumLength = 64
  519. }
  520. viewController.touchIDManager = touchIDManager
  521. viewController.title = NSLocalizedString("_folder_blocked_", comment: "")
  522. viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: #selector(passcodeViewCloseButtonPressed(_:)))
  523. viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor.black
  524. let navigationController = UINavigationController.init(rootViewController: viewController)
  525. self.present(navigationController, animated: true, completion: nil)
  526. return
  527. }
  528. let ncOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  529. ncOffline.serverUrl = serverUrlPush
  530. ncOffline.titleCurrentFolder = metadataPush!.fileNameView
  531. self.navigationController?.pushViewController(ncOffline, animated: true)
  532. }
  533. }