NCOffline.swift 35 KB

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