NCOffline.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. class NCOffline: UIViewController, UIGestureRecognizerDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, DropdownMenuDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, BKPasscodeViewControllerDelegate {
  25. @IBOutlet fileprivate weak var collectionView: UICollectionView!
  26. var titleCurrentFolder = NSLocalizedString("_manage_file_offline_", comment: "")
  27. var serverUrl = ""
  28. private let appDelegate = UIApplication.shared.delegate as! AppDelegate
  29. private var metadataPush: tableMetadata?
  30. private var isEditMode = false
  31. private var selectocId = [String]()
  32. private var sectionDatasource = CCSectionDataSourceMetadata()
  33. private var typeLayout = ""
  34. private var datasourceSorted = ""
  35. private var datasourceAscending = true
  36. private var datasourceGroupBy = ""
  37. private var datasourceDirectoryOnTop = false
  38. private var autoUploadFileName = ""
  39. private var autoUploadDirectory = ""
  40. private var listLayout: NCListLayout!
  41. private var gridLayout: NCGridLayout!
  42. private let headerMenuHeight: CGFloat = 50
  43. private let sectionHeaderHeight: CGFloat = 20
  44. private let footerHeight: CGFloat = 50
  45. private let refreshControl = UIRefreshControl()
  46. //BKPasscodeViewController
  47. private var failedAttempts: Double = 0
  48. private var lockUntilDate: NSDate?
  49. required init?(coder aDecoder: NSCoder) {
  50. super.init(coder: aDecoder)
  51. appDelegate.activeOffline = self
  52. }
  53. override func viewDidLoad() {
  54. super.viewDidLoad()
  55. // Cell
  56. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  57. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  58. // Header
  59. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  60. collectionView.register(UINib.init(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  61. // Footer
  62. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  63. collectionView.alwaysBounceVertical = true
  64. listLayout = NCListLayout()
  65. gridLayout = NCGridLayout()
  66. // Add Refresh Control
  67. if #available(iOS 10.0, *) {
  68. collectionView.refreshControl = refreshControl
  69. } else {
  70. collectionView.addSubview(refreshControl)
  71. }
  72. // Configure Refresh Control
  73. refreshControl.tintColor = NCBrandColor.sharedInstance.brandText
  74. refreshControl.backgroundColor = NCBrandColor.sharedInstance.brand
  75. refreshControl.addTarget(self, action: #selector(loadDatasource), for: .valueChanged)
  76. // empty Data Source
  77. self.collectionView.emptyDataSetDelegate = self;
  78. self.collectionView.emptyDataSetSource = self;
  79. // 3D Touch peek and pop
  80. if traitCollection.forceTouchCapability == .available {
  81. registerForPreviewing(with: self, sourceView: view)
  82. }
  83. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  84. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  85. changeTheming()
  86. }
  87. override func viewWillAppear(_ animated: Bool) {
  88. super.viewWillAppear(animated)
  89. self.navigationItem.title = titleCurrentFolder
  90. (typeLayout, datasourceSorted, datasourceAscending, datasourceGroupBy, datasourceDirectoryOnTop) = NCUtility.sharedInstance.getLayoutForView(key: k_layout_view_offline)
  91. // get auto upload folder
  92. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  93. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(appDelegate.activeUrl)
  94. if typeLayout == k_layout_list {
  95. collectionView.collectionViewLayout = listLayout
  96. } else {
  97. collectionView.collectionViewLayout = gridLayout
  98. }
  99. loadDatasource()
  100. }
  101. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  102. super.viewWillTransition(to: size, with: coordinator)
  103. coordinator.animate(alongsideTransition: nil) { _ in
  104. self.collectionView.collectionViewLayout.invalidateLayout()
  105. }
  106. }
  107. //MARK: - NotificationCenter
  108. @objc func deleteFile(_ notification: NSNotification) {
  109. if self.view?.window == nil { return }
  110. if let userInfo = notification.userInfo as NSDictionary? {
  111. if let errorCode = userInfo["errorCode"] as? Int, let errorDescription = userInfo["errorDescription"] as? String {
  112. if errorCode == 0 {
  113. self.loadDatasource()
  114. } else {
  115. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  116. }
  117. }
  118. }
  119. }
  120. @objc func changeTheming() {
  121. appDelegate.changeTheming(self, tableView: nil, collectionView: collectionView, form: false)
  122. }
  123. // MARK: DZNEmpty
  124. func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
  125. return NCBrandColor.sharedInstance.backgroundView
  126. }
  127. func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
  128. return CCGraphics.changeThemingColorImage(UIImage.init(named: "folder"), width: 300, height: 300, color: NCBrandColor.sharedInstance.brandElement)
  129. }
  130. func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
  131. let text = "\n"+NSLocalizedString("_files_no_files_", comment: "")
  132. let attributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedString.Key.foregroundColor: UIColor.lightGray]
  133. return NSAttributedString.init(string: text, attributes: attributes)
  134. }
  135. func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
  136. return true
  137. }
  138. // MARK: BKPASSCODEVIEWCONTROLLER
  139. func passcodeViewController(_ aViewController: BKPasscodeViewController!, didFinishWithPasscode aPasscode: String!) {
  140. aViewController.dismiss(animated: true, completion: nil)
  141. performSegueDirectoryWithControlPasscode(controlPasscode: false)
  142. }
  143. func passcodeViewController(_ aViewController: BKPasscodeViewController!, authenticatePasscode aPasscode: String!, resultHandler aResultHandler: ((Bool) -> Void)!) {
  144. if aPasscode == CCUtility.getBlockCode() {
  145. failedAttempts = 0
  146. lockUntilDate = nil
  147. aResultHandler(true)
  148. } else {
  149. aResultHandler(false)
  150. }
  151. }
  152. func passcodeViewControllerDidFailAttempt(_ aViewController: BKPasscodeViewController!) {
  153. failedAttempts += 1
  154. if failedAttempts > 5 {
  155. var timeInterval: TimeInterval = 60
  156. if failedAttempts > 6 {
  157. let multiplier: Double = failedAttempts - 6
  158. timeInterval = (5 * 60) * multiplier
  159. if timeInterval > 3600 * 24 {
  160. timeInterval = 3600 * 24
  161. }
  162. }
  163. lockUntilDate = NSDate.init(timeIntervalSinceNow: timeInterval)
  164. }
  165. }
  166. func passcodeViewControllerNumber(ofFailedAttempts aViewController: BKPasscodeViewController!) -> UInt {
  167. return UInt(failedAttempts)
  168. }
  169. func passcodeViewControllerLock(untilDate aViewController: BKPasscodeViewController!) -> Date? {
  170. return lockUntilDate as Date?
  171. }
  172. @objc func passcodeViewCloseButtonPressed(_ sender: Any) {
  173. self.dismiss(animated: true, completion: nil)
  174. }
  175. // MARK: TAP EVENT
  176. func tapSwitchHeader(sender: Any) {
  177. if collectionView.collectionViewLayout == gridLayout {
  178. // list layout
  179. UIView.animate(withDuration: 0.0, animations: {
  180. self.collectionView.collectionViewLayout.invalidateLayout()
  181. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  182. self.collectionView.reloadData()
  183. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  184. })
  185. })
  186. typeLayout = k_layout_list
  187. NCUtility.sharedInstance.setLayoutForView(key: k_layout_view_offline, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  188. } else {
  189. // grid layout
  190. UIView.animate(withDuration: 0.0, animations: {
  191. self.collectionView.collectionViewLayout.invalidateLayout()
  192. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  193. self.collectionView.reloadData()
  194. self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: false)
  195. })
  196. })
  197. typeLayout = k_layout_grid
  198. NCUtility.sharedInstance.setLayoutForView(key: k_layout_view_offline, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  199. }
  200. }
  201. func tapOrderHeader(sender: Any) {
  202. var menuView: DropdownMenu?
  203. var selectedIndexPath = [IndexPath()]
  204. let item1 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameAZ"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_a_z_", comment: ""))
  205. let item2 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortFileNameZA"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_name_z_a_", comment: ""))
  206. let item3 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateMoreRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_more_recent_", comment: ""))
  207. let item4 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortDateLessRecent"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_date_less_recent_", comment: ""))
  208. let item5 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortSmallest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_smallest_", comment: ""))
  209. let item6 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "sortLargest"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_order_by_size_largest_", comment: ""))
  210. switch datasourceSorted {
  211. case "fileName":
  212. if datasourceAscending == true { item1.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 0)) }
  213. if datasourceAscending == false { item2.style = .highlight; selectedIndexPath.append(IndexPath(row: 1, section: 0)) }
  214. case "date":
  215. if datasourceAscending == false { item3.style = .highlight; selectedIndexPath.append(IndexPath(row: 2, section: 0)) }
  216. if datasourceAscending == true { item4.style = .highlight; selectedIndexPath.append(IndexPath(row: 3, section: 0)) }
  217. case "size":
  218. if datasourceAscending == true { item5.style = .highlight; selectedIndexPath.append(IndexPath(row: 4, section: 0)) }
  219. if datasourceAscending == false { item6.style = .highlight; selectedIndexPath.append(IndexPath(row: 5, section: 0)) }
  220. default:
  221. ()
  222. }
  223. let item7 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByAlphabetic"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_alphabetic_no_", comment: ""))
  224. let item8 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByFile"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_typefile_no_", comment: ""))
  225. let item9 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "MenuGroupByDate"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_group_date_no_", comment: ""))
  226. switch datasourceGroupBy {
  227. case "alphabetic":
  228. item7.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 1))
  229. case "typefile":
  230. item8.style = .highlight; selectedIndexPath.append(IndexPath(row: 1, section: 1))
  231. case "date":
  232. item9.style = .highlight; selectedIndexPath.append(IndexPath(row: 2, section: 1))
  233. default:
  234. ()
  235. }
  236. let item10 = DropdownItem(image: CCGraphics.changeThemingColorImage(UIImage.init(named: "foldersOnTop"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), title: NSLocalizedString("_directory_on_top_no_", comment: ""))
  237. if datasourceDirectoryOnTop {
  238. item10.style = .highlight; selectedIndexPath.append(IndexPath(row: 0, section: 2))
  239. }
  240. let sectionOrder = DropdownSection(sectionIdentifier: "", items: [item1, item2, item3, item4, item5, item6])
  241. let sectionGroupBy = DropdownSection(sectionIdentifier: "", items: [item7, item8, item9])
  242. let sectionFolderOnTop = DropdownSection(sectionIdentifier: "", items: [item10])
  243. menuView = DropdownMenu(navigationController: self.navigationController!, sections: [sectionOrder, sectionGroupBy, sectionFolderOnTop], selectedIndexPath: selectedIndexPath)
  244. menuView?.token = "tapOrderHeaderMenu"
  245. menuView?.delegate = self
  246. menuView?.rowHeight = 45
  247. menuView?.sectionHeaderHeight = 0.3
  248. menuView?.highlightColor = NCBrandColor.sharedInstance.brand
  249. menuView?.tableView.alwaysBounceVertical = false
  250. menuView?.tableViewSeperatorColor = NCBrandColor.sharedInstance.separator
  251. menuView?.tableViewBackgroundColor = NCBrandColor.sharedInstance.backgroundForm
  252. menuView?.cellBackgroundColor = NCBrandColor.sharedInstance.backgroundForm
  253. menuView?.textColor = NCBrandColor.sharedInstance.textView
  254. let header = (sender as? UIButton)?.superview
  255. let headerRect = self.collectionView.convert(header!.bounds, from: self.view)
  256. let menuOffsetY = headerRect.height - headerRect.origin.y - 2
  257. menuView?.topOffsetY = CGFloat(menuOffsetY)
  258. menuView?.showMenu()
  259. }
  260. func tapMoreHeader(sender: Any) {
  261. }
  262. func tapMoreListItem(with objectId: String, sender: Any) {
  263. tapMoreGridItem(with: objectId, sender: sender)
  264. }
  265. func tapShareListItem(with objectId: String, sender: Any) {
  266. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", objectId)) else {
  267. return
  268. }
  269. NCMainCommon.sharedInstance.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  270. }
  271. func tapMoreGridItem(with objectId: String, sender: Any) {
  272. guard let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "ocId == %@", objectId)) else {
  273. return
  274. }
  275. if !isEditMode {
  276. let mainMenuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateViewController(withIdentifier: "NCMainMenuTableViewController") as! NCMainMenuTableViewController
  277. var actions = [NCMenuAction]()
  278. var iconHeader: UIImage!
  279. if let icon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, fileNameView: metadata.fileNameView)) {
  280. iconHeader = icon
  281. } else {
  282. iconHeader = UIImage(named: metadata.iconName)
  283. }
  284. actions.append(
  285. NCMenuAction(
  286. title: metadata.fileNameView,
  287. icon: iconHeader,
  288. action: nil
  289. )
  290. )
  291. actions.append(
  292. NCMenuAction(
  293. title: NSLocalizedString("_remove_available_offline_", comment: ""),
  294. icon: CCGraphics.changeThemingColorImage(UIImage(named: "offline"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  295. action: { menuAction in
  296. if metadata.directory {
  297. NCManageDatabase.sharedInstance.setDirectory(serverUrl: CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!, offline: false, account: self.appDelegate.activeAccount)
  298. } else {
  299. NCManageDatabase.sharedInstance.setLocalFile(ocId: metadata.ocId, offline: false)
  300. }
  301. self.loadDatasource()
  302. }
  303. )
  304. )
  305. actions.append(
  306. NCMenuAction(
  307. title: NSLocalizedString("_details_", comment: ""),
  308. icon: CCGraphics.changeThemingColorImage(UIImage(named: "details"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  309. action: { menuAction in
  310. NCMainCommon.sharedInstance.openShare(ViewController: self, metadata: metadata, indexPage: 0)
  311. }
  312. )
  313. )
  314. actions.append(
  315. NCMenuAction(
  316. title: NSLocalizedString("_delete_", comment: ""),
  317. icon: CCGraphics.changeThemingColorImage(UIImage(named: "trash"), width: 50, height: 50, color: .red),
  318. action: { menuAction in
  319. NCNetworking.sharedInstance.deleteMetadata(metadata, user: self.appDelegate.activeUser, userID: self.appDelegate.activeUserID, password: self.appDelegate.activePassword, url: self.appDelegate.activeUrl) { (errorCode, errorDescription) in }
  320. }
  321. )
  322. )
  323. mainMenuViewController.actions = actions
  324. let menuPanelController = NCMenuPanelController()
  325. menuPanelController.parentPresenter = self
  326. menuPanelController.delegate = mainMenuViewController
  327. menuPanelController.set(contentViewController: mainMenuViewController)
  328. menuPanelController.track(scrollView: mainMenuViewController.tableView)
  329. self.present(menuPanelController, animated: true, completion: nil)
  330. } else {
  331. let buttonPosition:CGPoint = (sender as! UIButton).convert(CGPoint.zero, to:collectionView)
  332. let indexPath = collectionView.indexPathForItem(at: buttonPosition)
  333. collectionView(self.collectionView, didSelectItemAt: indexPath!)
  334. }
  335. }
  336. // MARK: DROP-DOWN-MENU
  337. func dropdownMenu(_ dropdownMenu: DropdownMenu, didSelectRowAt indexPath: IndexPath) {
  338. if dropdownMenu.token == "tapOrderHeaderMenu" {
  339. switch indexPath.section {
  340. case 0: switch indexPath.row {
  341. case 0: datasourceSorted = "fileName"; datasourceAscending = true
  342. case 1: datasourceSorted = "fileName"; datasourceAscending = false
  343. case 2: datasourceSorted = "date"; datasourceAscending = false
  344. case 3: datasourceSorted = "date"; datasourceAscending = true
  345. case 4: datasourceSorted = "size"; datasourceAscending = true
  346. case 5: datasourceSorted = "size"; datasourceAscending = false
  347. default: ()
  348. }
  349. case 1: switch indexPath.row {
  350. case 0:
  351. if datasourceGroupBy == "alphabetic" {
  352. datasourceGroupBy = "none"
  353. } else {
  354. datasourceGroupBy = "alphabetic"
  355. }
  356. case 1:
  357. if datasourceGroupBy == "typefile" {
  358. datasourceGroupBy = "none"
  359. } else {
  360. datasourceGroupBy = "typefile"
  361. }
  362. case 2:
  363. if datasourceGroupBy == "date" {
  364. datasourceGroupBy = "none"
  365. } else {
  366. datasourceGroupBy = "date"
  367. }
  368. default: ()
  369. }
  370. case 2:
  371. if datasourceDirectoryOnTop {
  372. datasourceDirectoryOnTop = false
  373. } else {
  374. datasourceDirectoryOnTop = true
  375. }
  376. default: ()
  377. }
  378. NCUtility.sharedInstance.setLayoutForView(key: k_layout_view_offline, layout: typeLayout, sort: datasourceSorted, ascending: datasourceAscending, groupBy: datasourceGroupBy, directoryOnTop: datasourceDirectoryOnTop)
  379. loadDatasource()
  380. }
  381. if dropdownMenu.token == "tapMoreHeaderMenu" {
  382. }
  383. if dropdownMenu.token == "tapMoreHeaderMenuSelect" {
  384. }
  385. }
  386. // MARK: SEGUE
  387. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  388. let photoDataSource: NSMutableArray = []
  389. for ocId: String in sectionDatasource.allOcId as! [String] {
  390. let metadata = sectionDatasource.allRecordsDataSource.object(forKey: ocId) as! tableMetadata
  391. if metadata.typeFile == k_metadataTypeFile_image {
  392. photoDataSource.add(metadata)
  393. }
  394. }
  395. if let segueNavigationController = segue.destination as? UINavigationController {
  396. if let segueViewController = segueNavigationController.topViewController as? NCDetailViewController {
  397. segueViewController.metadata = metadataPush
  398. segueViewController.offlineFilterImage = true
  399. }
  400. }
  401. }
  402. // MARK: NAVIGATION
  403. private func performSegueDirectoryWithControlPasscode(controlPasscode: Bool) {
  404. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataPush!.serverUrl, addFileName: metadataPush!.fileName) else {
  405. return
  406. }
  407. guard let directoryPush = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrlPush)) else {
  408. return
  409. }
  410. if directoryPush.lock == true && CCUtility.getBlockCode() != nil && (CCUtility.getBlockCode()?.count)! > 0 && controlPasscode {
  411. let viewController = CCBKPasscode.init(nibName: nil, bundle: nil)
  412. guard let touchIDManager = BKTouchIDManager.init(keychainServiceName: k_serviceShareKeyChain) else {
  413. return
  414. }
  415. touchIDManager.promptText = NSLocalizedString("_scan_fingerprint_", comment: "")
  416. viewController.delegate = self
  417. viewController.type = BKPasscodeViewControllerCheckPasscodeType
  418. viewController.inputViewTitlePassword = true
  419. if CCUtility.getSimplyBlockCode() {
  420. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle
  421. viewController.passcodeInputView.maximumLength = 6
  422. } else {
  423. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle
  424. viewController.passcodeInputView.maximumLength = 64
  425. }
  426. viewController.touchIDManager = touchIDManager
  427. viewController.title = NSLocalizedString("_folder_blocked_", comment: "")
  428. viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: #selector(passcodeViewCloseButtonPressed(_:)))
  429. viewController.navigationItem.leftBarButtonItem?.tintColor = UIColor.black
  430. let navigationController = UINavigationController.init(rootViewController: viewController)
  431. navigationController.modalPresentationStyle = .fullScreen
  432. self.present(navigationController, animated: true, completion: nil)
  433. return
  434. }
  435. let ncOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  436. ncOffline.serverUrl = serverUrlPush
  437. ncOffline.titleCurrentFolder = metadataPush!.fileNameView
  438. self.navigationController?.pushViewController(ncOffline, animated: true)
  439. }
  440. }
  441. // MARK: - 3D Touch peek and pop
  442. extension NCOffline: UIViewControllerPreviewingDelegate {
  443. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  444. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  445. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  446. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else { return nil }
  447. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  448. viewController.metadata = metadata
  449. if typeLayout == k_layout_grid {
  450. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  451. previewingContext.sourceRect = cell.frame
  452. viewController.imageFile = cell.imageItem.image
  453. } else {
  454. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  455. previewingContext.sourceRect = cell.frame
  456. viewController.imageFile = cell.imageItem.image
  457. }
  458. viewController.showOpenIn = true
  459. if metadata.typeFile == k_metadataTypeFile_document {
  460. viewController.showOpenInternalViewer = true
  461. }
  462. viewController.showShare = false
  463. return viewController
  464. }
  465. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  466. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  467. collectionView(collectionView, didSelectItemAt: indexPath)
  468. }
  469. }
  470. // MARK: - Collection View
  471. extension NCOffline: UICollectionViewDelegate {
  472. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  473. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  474. return
  475. }
  476. metadataPush = metadata
  477. if isEditMode {
  478. if let index = selectocId.firstIndex(of: metadata.ocId) {
  479. selectocId.remove(at: index)
  480. } else {
  481. selectocId.append(metadata.ocId)
  482. }
  483. collectionView.reloadItems(at: [indexPath])
  484. return
  485. }
  486. if metadata.directory {
  487. performSegueDirectoryWithControlPasscode(controlPasscode: true)
  488. } else {
  489. performSegue(withIdentifier: "segueDetail", sender: self)
  490. }
  491. }
  492. }
  493. extension NCOffline: UICollectionViewDataSource {
  494. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  495. if (indexPath.section == 0) {
  496. if kind == UICollectionView.elementKindSectionHeader {
  497. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  498. if collectionView.collectionViewLayout == gridLayout {
  499. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  500. } else {
  501. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), multiplier: 2, color: NCBrandColor.sharedInstance.icon), for: .normal)
  502. }
  503. header.delegate = self
  504. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  505. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  506. header.setStatusButton(count: sectionDatasource.allOcId.count)
  507. header.setTitleOrder(datasourceSorted: datasourceSorted, datasourceAscending: datasourceAscending)
  508. if datasourceGroupBy == "none" {
  509. header.labelSection.isHidden = true
  510. header.labelSectionHeightConstraint.constant = 0
  511. } else {
  512. header.labelSection.isHidden = false
  513. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  514. header.labelSectionHeightConstraint.constant = sectionHeaderHeight
  515. }
  516. return header
  517. } else {
  518. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  519. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  520. return footer
  521. }
  522. } else {
  523. if kind == UICollectionView.elementKindSectionHeader {
  524. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  525. header.setTitleLabel(sectionDatasource: sectionDatasource, section: indexPath.section)
  526. return header
  527. } else {
  528. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  529. footer.setTitleLabel(sectionDatasource: sectionDatasource)
  530. return footer
  531. }
  532. }
  533. }
  534. func numberOfSections(in collectionView: UICollectionView) -> Int {
  535. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  536. return sections
  537. }
  538. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  539. let key = sectionDatasource.sections.object(at: section)
  540. let datasource = sectionDatasource.sectionArrayRow.object(forKey: key) as! [tableMetadata]
  541. return datasource.count
  542. }
  543. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  544. let cell: UICollectionViewCell
  545. guard let metadata = NCMainCommon.sharedInstance.getMetadataFromSectionDataSourceIndexPath(indexPath, sectionDataSource: sectionDatasource) else {
  546. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  547. }
  548. if typeLayout == k_layout_grid {
  549. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  550. } else {
  551. cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  552. (cell as! NCListCell).separator.backgroundColor = NCBrandColor.sharedInstance.separator
  553. }
  554. let shares = NCManageDatabase.sharedInstance.getTableShares(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  555. NCMainCommon.sharedInstance.collectionViewCellForItemAt(indexPath, collectionView: collectionView, cell: cell, metadata: metadata, metadataFolder: nil, serverUrl: metadata.serverUrl, isEditMode: isEditMode, selectocId: selectocId, autoUploadFileName: autoUploadFileName, autoUploadDirectory: autoUploadDirectory, hideButtonMore: false, downloadThumbnail: true, shares: shares, source: self)
  556. return cell
  557. }
  558. }
  559. extension NCOffline: UICollectionViewDelegateFlowLayout {
  560. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  561. if section == 0 {
  562. if datasourceGroupBy == "none" {
  563. return CGSize(width: collectionView.frame.width, height: headerMenuHeight)
  564. } else {
  565. return CGSize(width: collectionView.frame.width, height: headerMenuHeight + sectionHeaderHeight)
  566. }
  567. } else {
  568. return CGSize(width: collectionView.frame.width, height: sectionHeaderHeight)
  569. }
  570. }
  571. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  572. let sections = sectionDatasource.sectionArrayRow.allKeys.count
  573. if (section == sections - 1) {
  574. return CGSize(width: collectionView.frame.width, height: footerHeight)
  575. } else {
  576. return CGSize(width: collectionView.frame.width, height: 0)
  577. }
  578. }
  579. }
  580. // MARK: - NC API & Algorithm
  581. extension NCOffline {
  582. @objc func loadDatasource() {
  583. var ocIds = [String]()
  584. sectionDatasource = CCSectionDataSourceMetadata()
  585. if serverUrl == "" {
  586. if let directories = NCManageDatabase.sharedInstance.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "serverUrl", ascending: true) {
  587. for directory: tableDirectory in directories {
  588. ocIds.append(directory.ocId)
  589. }
  590. }
  591. if let files = NCManageDatabase.sharedInstance.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", appDelegate.activeAccount), sorted: "fileName", ascending: true) {
  592. for file: tableLocalFile in files {
  593. ocIds.append(file.ocId)
  594. }
  595. }
  596. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND ocId IN %@", appDelegate.activeAccount, ocIds), sorted: nil, ascending: false) {
  597. sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: datasourceGroupBy, filterocId: nil, filterTypeFileImage: false, filterTypeFileVideo: false, sorted: datasourceSorted, ascending: datasourceAscending, activeAccount: appDelegate.activeAccount)
  598. }
  599. } else {
  600. if let metadatas = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl), sorted: nil, ascending: false) {
  601. sectionDatasource = CCSectionMetadata.creataDataSourseSectionMetadata(metadatas, listProgressMetadata: nil, groupByField: datasourceGroupBy, filterocId: nil, filterTypeFileImage: false, filterTypeFileVideo: false, sorted: datasourceSorted, ascending: datasourceAscending, activeAccount: appDelegate.activeAccount)
  602. }
  603. }
  604. self.refreshControl.endRefreshing()
  605. collectionView.reloadData()
  606. }
  607. /*
  608. func deleteItem(with metadata: tableMetadata, sender: Any) {
  609. let mainMenuViewController = UIStoryboard.init(name: "NCMenu", bundle: nil).instantiateViewController(withIdentifier: "NCMainMenuTableViewController") as! NCMainMenuTableViewController
  610. var actions = [NCMenuAction]()
  611. actions.append(
  612. NCMenuAction(
  613. title: NSLocalizedString("_delete_", comment: ""),
  614. icon: CCGraphics.changeThemingColorImage(UIImage(named: "trash"), width: 50, height: 50, color: .red),
  615. action: { menuAction in
  616. NCNetworking.sharedInstance.deleteMetadata(metadata, user: self.appDelegate.activeUser, userID: self.appDelegate.activeUserID, password: self.appDelegate.activePassword, url: self.appDelegate.activeUrl) { (errorCode, errorDescription) in }
  617. }
  618. )
  619. )
  620. actions.append(
  621. NCMenuAction(
  622. title: NSLocalizedString("_cancel_", comment: ""),
  623. icon: CCGraphics.changeThemingColorImage(UIImage(named: "cancel"), width: 50, height: 50, color: NCBrandColor.sharedInstance.icon),
  624. action: { menuAction in }
  625. )
  626. )
  627. mainMenuViewController.actions = actions
  628. let menuPanelController = NCMenuPanelController()
  629. menuPanelController.parentPresenter = self
  630. menuPanelController.delegate = mainMenuViewController
  631. menuPanelController.set(contentViewController: mainMenuViewController)
  632. menuPanelController.track(scrollView: mainMenuViewController.tableView)
  633. }
  634. */
  635. }