NCOffline.swift 39 KB

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