NCOffline.swift 39 KB

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