NCCollectionViewCommon.swift 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  1. //
  2. // NCCollectionViewCommon.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/09/2020.
  6. // Copyright © 2020 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 NCCommunication
  25. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, UIAdaptivePresentationControllerDelegate, NCEmptyDataSetDelegate, UIContextMenuInteractionDelegate {
  26. @IBOutlet weak var collectionView: UICollectionView!
  27. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  28. internal let refreshControl = UIRefreshControl()
  29. internal var searchController: UISearchController?
  30. internal var emptyDataSet: NCEmptyDataSet?
  31. internal var serverUrl: String = ""
  32. internal var isEncryptedFolder = false
  33. internal var isEditMode = false
  34. internal var selectOcId: [String] = []
  35. internal var metadatasSource: [tableMetadata] = []
  36. internal var metadataFolder: tableMetadata?
  37. internal var metadataTouch: tableMetadata?
  38. internal var dataSource = NCDataSource()
  39. internal var richWorkspaceText: String?
  40. internal var layout = ""
  41. internal var sort: String = ""
  42. internal var ascending: Bool = true
  43. internal var directoryOnTop: Bool = true
  44. internal var groupBy = ""
  45. internal var titleButton = ""
  46. internal var itemForLine = 0
  47. private var autoUploadFileName = ""
  48. private var autoUploadDirectory = ""
  49. internal var listLayout: NCListLayout!
  50. internal var gridLayout: NCGridLayout!
  51. private let headerHeight: CGFloat = 50
  52. private var headerRichWorkspaceHeight: CGFloat = 0
  53. private let footerHeight: CGFloat = 100
  54. private var timerInputSearch: Timer?
  55. internal var literalSearch: String?
  56. internal var isSearching: Bool = false
  57. internal var isReloadDataSourceNetworkInProgress: Bool = false
  58. var selectedIndexPath: IndexPath!
  59. // DECLARE
  60. internal var layoutKey = ""
  61. internal var titleCurrentFolder = ""
  62. internal var enableSearchBar: Bool = false
  63. internal var emptyImage: UIImage?
  64. internal var emptyTitle: String = ""
  65. internal var emptyDescription: String = ""
  66. required init?(coder aDecoder: NSCoder) {
  67. super.init(coder: aDecoder)
  68. }
  69. override func viewDidLoad() {
  70. super.viewDidLoad()
  71. self.navigationController?.presentationController?.delegate = self
  72. if enableSearchBar {
  73. searchController = UISearchController(searchResultsController: nil)
  74. searchController?.searchResultsUpdater = self
  75. searchController?.obscuresBackgroundDuringPresentation = false
  76. searchController?.delegate = self
  77. searchController?.searchBar.delegate = self
  78. navigationItem.searchController = searchController
  79. navigationItem.hidesSearchBarWhenScrolling = false
  80. }
  81. // Cell
  82. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  83. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  84. collectionView.register(UINib.init(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  85. // Header
  86. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  87. // Footer
  88. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  89. collectionView.alwaysBounceVertical = true
  90. listLayout = NCListLayout()
  91. gridLayout = NCGridLayout()
  92. // Refresh Control
  93. collectionView.addSubview(refreshControl)
  94. refreshControl.tintColor = .gray
  95. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  96. // Empty
  97. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: 0, delegate: self)
  98. // Long Press on CollectionView
  99. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  100. longPressedGesture.minimumPressDuration = 0.5
  101. longPressedGesture.delegate = self
  102. longPressedGesture.delaysTouchesBegan = true
  103. collectionView.addGestureRecognizer(longPressedGesture)
  104. // Notification
  105. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitializeMain), object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  122. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  123. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object:nil)
  124. changeTheming()
  125. }
  126. override func viewWillAppear(_ animated: Bool) {
  127. super.viewWillAppear(animated)
  128. appDelegate.activeViewController = self
  129. if serverUrl == "" {
  130. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  131. } else {
  132. appDelegate.activeServerUrl = serverUrl
  133. }
  134. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  135. gridLayout.itemForLine = CGFloat(itemForLine)
  136. if layout == NCGlobal.shared.layoutList {
  137. collectionView?.collectionViewLayout = listLayout
  138. } else {
  139. collectionView?.collectionViewLayout = gridLayout
  140. }
  141. navigationController?.navigationBar.prefersLargeTitles = true
  142. navigationController?.setNavigationBarHidden(false, animated: true)
  143. setNavigationItem()
  144. reloadDataSource()
  145. }
  146. override func viewDidAppear(_ animated: Bool) {
  147. super.viewDidAppear(animated)
  148. reloadDataSourceNetwork()
  149. }
  150. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  151. let viewController = presentationController.presentedViewController
  152. if viewController is NCViewerRichWorkspaceWebView {
  153. closeRichWorkspaceWebView()
  154. } else if viewController is UINavigationController {
  155. if (viewController as! UINavigationController).topViewController is NCFileViewInFolder {
  156. appDelegate.activeFileViewInFolder = nil
  157. }
  158. }
  159. }
  160. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  161. super.viewWillTransition(to: size, with: coordinator)
  162. coordinator.animate(alongsideTransition: nil) { _ in
  163. self.collectionView?.collectionViewLayout.invalidateLayout()
  164. }
  165. }
  166. override var canBecomeFirstResponder: Bool {
  167. return true
  168. }
  169. func setNavigationItem() {
  170. if isEditMode {
  171. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  172. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  173. navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  174. } else {
  175. navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  176. navigationItem.leftBarButtonItem = nil
  177. navigationItem.title = titleCurrentFolder
  178. }
  179. }
  180. // MARK: - NotificationCenter
  181. @objc func initializeMain() {
  182. if appDelegate.account == "" { return }
  183. if searchController?.isActive ?? false {
  184. searchController?.isActive = false
  185. }
  186. // set active serverUrl
  187. if self.view?.window != nil {
  188. if serverUrl == "" {
  189. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  190. } else {
  191. appDelegate.activeServerUrl = serverUrl
  192. }
  193. }
  194. if self is NCFiles || self is NCFavorite || self is NCOffline {
  195. self.navigationController?.popToRootViewController(animated: false)
  196. }
  197. appDelegate.listFilesVC.removeAll()
  198. appDelegate.listFavoriteVC.removeAll()
  199. appDelegate.listOfflineVC.removeAll()
  200. reloadDataSource()
  201. }
  202. @objc func changeTheming() {
  203. view.backgroundColor = NCBrandColor.shared.backgroundView
  204. collectionView.backgroundColor = NCBrandColor.shared.backgroundView
  205. collectionView.reloadData()
  206. }
  207. @objc func reloadDataSource(_ notification: NSNotification) {
  208. if self.view?.window == nil { return }
  209. reloadDataSource()
  210. }
  211. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  212. if self.view?.window == nil { return }
  213. if let userInfo = notification.userInfo as NSDictionary? {
  214. if let serverUrl = userInfo["serverUrl"] as? String {
  215. if serverUrl == self.serverUrl {
  216. reloadDataSourceNetwork(forced: true)
  217. }
  218. }
  219. } else {
  220. reloadDataSourceNetwork(forced: true)
  221. }
  222. }
  223. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  224. if self.view?.window == nil { return }
  225. reloadDataSource()
  226. }
  227. @objc func closeRichWorkspaceWebView() {
  228. if self.view?.window == nil { return }
  229. reloadDataSourceNetwork()
  230. }
  231. @objc func deleteFile(_ notification: NSNotification) {
  232. if self.view?.window == nil { return }
  233. if let userInfo = notification.userInfo as NSDictionary? {
  234. if let ocId = userInfo["ocId"] as? String, let fileNameView = userInfo["fileNameView"] as? String, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  235. if onlyLocal {
  236. reloadDataSource()
  237. } else if fileNameView.lowercased() == NCGlobal.shared.fileNameRichWorkspace.lowercased() {
  238. reloadDataSourceNetwork(forced: true)
  239. } else {
  240. if let row = dataSource.deleteMetadata(ocId: ocId) {
  241. let indexPath = IndexPath(row: row, section: 0)
  242. collectionView?.performBatchUpdates({
  243. collectionView?.deleteItems(at: [indexPath])
  244. }, completion: { (_) in
  245. self.collectionView?.reloadData()
  246. })
  247. }
  248. }
  249. }
  250. }
  251. }
  252. @objc func moveFile(_ notification: NSNotification) {
  253. if self.view?.window == nil { return }
  254. if let userInfo = notification.userInfo as NSDictionary? {
  255. if let ocId = userInfo["ocId"] as? String, let serverUrlFrom = userInfo["serverUrlFrom"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  256. // DEL
  257. if serverUrlFrom == serverUrl && metadata.account == appDelegate.account {
  258. if let row = dataSource.deleteMetadata(ocId: ocId) {
  259. let indexPath = IndexPath(row: row, section: 0)
  260. collectionView?.performBatchUpdates({
  261. collectionView?.deleteItems(at: [indexPath])
  262. }, completion: { (_) in
  263. self.collectionView?.reloadData()
  264. })
  265. }
  266. // ADD
  267. } else if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  268. if let row = dataSource.addMetadata(metadata) {
  269. let indexPath = IndexPath(row: row, section: 0)
  270. collectionView?.performBatchUpdates({
  271. collectionView?.insertItems(at: [indexPath])
  272. }, completion: { (_) in
  273. self.collectionView?.reloadData()
  274. })
  275. }
  276. }
  277. }
  278. }
  279. }
  280. @objc func copyFile(_ notification: NSNotification) {
  281. if self.view?.window == nil { return }
  282. if let userInfo = notification.userInfo as NSDictionary? {
  283. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  284. if serverUrlTo == self.serverUrl {
  285. reloadDataSource()
  286. }
  287. }
  288. }
  289. }
  290. @objc func renameFile(_ notification: NSNotification) {
  291. if self.view?.window == nil { return }
  292. reloadDataSource()
  293. }
  294. @objc func createFolder(_ notification: NSNotification) {
  295. if self.view?.window == nil { return }
  296. if let userInfo = notification.userInfo as NSDictionary? {
  297. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  298. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  299. if let row = dataSource.addMetadata(metadata) {
  300. let indexPath = IndexPath(row: row, section: 0)
  301. collectionView?.performBatchUpdates({
  302. collectionView?.insertItems(at: [indexPath])
  303. }, completion: { (_) in
  304. self.collectionView?.reloadData()
  305. })
  306. }
  307. }
  308. }
  309. } else {
  310. reloadDataSourceNetwork()
  311. }
  312. }
  313. @objc func favoriteFile(_ notification: NSNotification) {
  314. if self.view?.window == nil { return }
  315. if let userInfo = notification.userInfo as NSDictionary? {
  316. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  317. if dataSource.getIndexMetadata(ocId: metadata.ocId) != nil {
  318. reloadDataSource()
  319. }
  320. }
  321. }
  322. }
  323. @objc func downloadStartFile(_ notification: NSNotification) {
  324. if self.view?.window == nil { return }
  325. if let userInfo = notification.userInfo as NSDictionary? {
  326. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  327. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  328. let indexPath = IndexPath(row: row, section: 0)
  329. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  330. collectionView?.reloadItems(at: [indexPath])
  331. }
  332. }
  333. }
  334. }
  335. }
  336. @objc func downloadedFile(_ notification: NSNotification) {
  337. if self.view?.window == nil { return }
  338. if let userInfo = notification.userInfo as NSDictionary? {
  339. if let ocId = userInfo["ocId"] as? String, let _ = userInfo["errorCode"] as? Int, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  340. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  341. let indexPath = IndexPath(row: row, section: 0)
  342. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  343. collectionView?.reloadItems(at: [indexPath])
  344. }
  345. }
  346. }
  347. }
  348. }
  349. @objc func downloadCancelFile(_ notification: NSNotification) {
  350. if self.view?.window == nil { return }
  351. if let userInfo = notification.userInfo as NSDictionary? {
  352. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  353. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  354. let indexPath = IndexPath(row: row, section: 0)
  355. if indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section) {
  356. collectionView?.reloadItems(at: [indexPath])
  357. }
  358. }
  359. }
  360. }
  361. }
  362. @objc func uploadStartFile(_ notification: NSNotification) {
  363. if self.view?.window == nil { return }
  364. if let userInfo = notification.userInfo as NSDictionary? {
  365. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  366. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  367. dataSource.addMetadata(metadata)
  368. self.collectionView?.reloadData()
  369. }
  370. }
  371. }
  372. }
  373. @objc func uploadedFile(_ notification: NSNotification) {
  374. if self.view?.window == nil { return }
  375. if let userInfo = notification.userInfo as NSDictionary? {
  376. if let ocId = userInfo["ocId"] as? String, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  377. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  378. dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  379. collectionView?.reloadData()
  380. }
  381. }
  382. }
  383. }
  384. @objc func uploadCancelFile(_ notification: NSNotification) {
  385. if self.view?.window == nil { return }
  386. if let userInfo = notification.userInfo as NSDictionary? {
  387. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  388. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  389. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  390. let indexPath = IndexPath(row: row, section: 0)
  391. collectionView?.performBatchUpdates({
  392. collectionView?.deleteItems(at: [indexPath])
  393. }, completion: { (_) in
  394. self.collectionView?.reloadData()
  395. })
  396. } else {
  397. self.reloadDataSource()
  398. }
  399. }
  400. }
  401. }
  402. }
  403. @objc func triggerProgressTask(_ notification: NSNotification) {
  404. if self.view?.window == nil { return }
  405. if let userInfo = notification.userInfo as NSDictionary? {
  406. if let ocId = userInfo["ocId"] as? String {
  407. let _ = userInfo["account"] as? String ?? ""
  408. let _ = userInfo["serverUrl"] as? String ?? ""
  409. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  410. let progress = progressNumber.floatValue
  411. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  412. let totalBytes = userInfo["totalBytes"] as? Int64 ?? 0
  413. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64 ?? 0
  414. let progressType = NCGlobal.progressType(progress: progress, totalBytes: totalBytes, totalBytesExpected: totalBytesExpected)
  415. appDelegate.listProgress[ocId] = progressType
  416. if let index = dataSource.getIndexMetadata(ocId: ocId) {
  417. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  418. if cell is NCListCell {
  419. let cell = cell as! NCListCell
  420. if progress > 0 {
  421. cell.progressView?.isHidden = false
  422. cell.progressView?.progress = progress
  423. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.buttonStop)
  424. if status == NCGlobal.shared.metadataStatusInDownload {
  425. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  426. } else if status == NCGlobal.shared.metadataStatusInUpload {
  427. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  428. }
  429. }
  430. } else if cell is NCTransferCell {
  431. let cell = cell as! NCTransferCell
  432. if progress > 0 {
  433. cell.progressView?.isHidden = false
  434. cell.progressView?.progress = progress
  435. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.buttonStop)
  436. if status == NCGlobal.shared.metadataStatusInDownload {
  437. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  438. } else if status == NCGlobal.shared.metadataStatusInUpload {
  439. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  440. }
  441. }
  442. } else if cell is NCGridCell {
  443. let cell = cell as! NCGridCell
  444. if progress > 0 {
  445. cell.progressView.isHidden = false
  446. cell.progressView.progress = progress
  447. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.buttonStop)
  448. }
  449. }
  450. }
  451. }
  452. }
  453. }
  454. }
  455. // MARK: - Empty
  456. func emptyDataSetView(_ view: NCEmptyView) {
  457. if searchController?.isActive ?? false {
  458. view.emptyImage.image = UIImage.init(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  459. if isReloadDataSourceNetworkInProgress {
  460. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  461. } else {
  462. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  463. }
  464. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  465. } else if isReloadDataSourceNetworkInProgress {
  466. view.emptyImage.image = UIImage.init(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  467. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  468. view.emptyDescription.text = ""
  469. } else {
  470. if serverUrl == "" {
  471. view.emptyImage.image = emptyImage
  472. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  473. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  474. } else {
  475. view.emptyImage.image = UIImage.init(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  476. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  477. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  478. }
  479. }
  480. }
  481. // MARK: - SEARCH
  482. func updateSearchResults(for searchController: UISearchController) {
  483. timerInputSearch?.invalidate()
  484. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  485. literalSearch = searchController.searchBar.text
  486. collectionView?.reloadData()
  487. }
  488. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  489. isSearching = true
  490. metadatasSource.removeAll()
  491. reloadDataSource()
  492. }
  493. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  494. isSearching = false
  495. literalSearch = ""
  496. reloadDataSource()
  497. }
  498. // MARK: - TAP EVENT
  499. @objc func tapSelect(sender: Any) {
  500. isEditMode = !isEditMode
  501. selectOcId.removeAll()
  502. setNavigationItem()
  503. self.collectionView.reloadData()
  504. }
  505. func tapSwitchHeader(sender: Any) {
  506. if collectionView.collectionViewLayout == gridLayout {
  507. // list layout
  508. UIView.animate(withDuration: 0.0, animations: {
  509. self.collectionView.collectionViewLayout.invalidateLayout()
  510. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  511. self.collectionView.reloadData()
  512. })
  513. })
  514. layout = NCGlobal.shared.layoutList
  515. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  516. } else {
  517. // grid layout
  518. UIView.animate(withDuration: 0.0, animations: {
  519. self.collectionView.collectionViewLayout.invalidateLayout()
  520. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  521. self.collectionView.reloadData()
  522. })
  523. })
  524. layout = NCGlobal.shared.layoutGrid
  525. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  526. }
  527. }
  528. func tapOrderHeader(sender: Any) {
  529. let sortMenu = NCSortMenu()
  530. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  531. }
  532. @objc func tapSelectMenu(sender: Any) {
  533. guard let tabBarController = self.tabBarController else { return }
  534. toggleMenuSelect(viewController: tabBarController, selectOcId: selectOcId)
  535. }
  536. func tapMoreHeader(sender: Any) { }
  537. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  538. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  539. }
  540. func tapShareListItem(with objectId: String, sender: Any) {
  541. if isEditMode { return }
  542. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  543. NCNetworkingNotificationCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  544. }
  545. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  546. if isEditMode { return }
  547. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  548. if namedButtonMore == NCGlobal.shared.buttonMoreMore {
  549. toggleMenu(viewController: self, metadata: metadata, image: image)
  550. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  551. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  552. }
  553. }
  554. func tapRichWorkspace(sender: Any) {
  555. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  556. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  557. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  558. viewerRichWorkspace.serverUrl = serverUrl
  559. navigationController.modalPresentationStyle = .fullScreen
  560. self.present(navigationController, animated: true, completion: nil)
  561. }
  562. }
  563. }
  564. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  565. }
  566. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  567. }
  568. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  569. }
  570. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  571. }
  572. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  573. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  574. /*
  575. if #available(iOS 13.0, *) {
  576. let interaction = UIContextMenuInteraction(delegate: self)
  577. self.view.addInteraction(interaction)
  578. }
  579. */
  580. }
  581. @available(iOS 13.0, *)
  582. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  583. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  584. return nil
  585. }, actionProvider: { suggestedActions in
  586. //let share = UIAction(title: "Share Pupper", image: UIImage(systemName: "square.and.arrow.up")) { action in
  587. //}
  588. //return UIMenu(title: "Main Menu", children: [share])
  589. return nil
  590. })
  591. }
  592. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  593. if gestureRecognizer.state != .began { return }
  594. if serverUrl == "" { return }
  595. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) {
  596. metadataTouch = metadata
  597. } else {
  598. metadataTouch = nil
  599. }
  600. var listMenuItems: [UIMenuItem] = []
  601. let touchPoint = gestureRecognizer.location(in: collectionView)
  602. becomeFirstResponder()
  603. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  604. if listMenuItems.count > 0 {
  605. UIMenuController.shared.menuItems = listMenuItems
  606. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  607. UIMenuController.shared.setMenuVisible(true, animated: true)
  608. }
  609. }
  610. // MARK: - Menu Item
  611. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  612. if (#selector(pasteFilesMenu) == action) {
  613. if UIPasteboard.general.items.count > 0 {
  614. return true
  615. }
  616. }
  617. return false
  618. }
  619. @objc func pasteFilesMenu() {
  620. NCCollectionCommon.shared.pastePasteboard(serverUrl: serverUrl)
  621. }
  622. // MARK: - DataSource + NC Endpoint
  623. @objc func reloadDataSource() {
  624. if appDelegate.account == "" { return }
  625. // Get richWorkspace Text
  626. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  627. richWorkspaceText = directory?.richWorkspace
  628. // E2EE
  629. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  630. // get auto upload folder
  631. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  632. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  633. // get layout for view
  634. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  635. }
  636. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  637. @objc func reloadDataSourceNetworkRefreshControl() {
  638. reloadDataSourceNetwork(forced: true)
  639. }
  640. @objc func networkSearch() {
  641. if appDelegate.account == "" { return }
  642. if literalSearch?.count ?? 0 > 1 {
  643. isReloadDataSourceNetworkInProgress = true
  644. collectionView?.reloadData()
  645. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  646. if self.searchController?.isActive ?? false && errorCode == 0 {
  647. self.metadatasSource = metadatas!
  648. }
  649. self.refreshControl.endRefreshing()
  650. self.isReloadDataSourceNetworkInProgress = false
  651. self.reloadDataSource()
  652. }
  653. } else {
  654. self.refreshControl.endRefreshing()
  655. }
  656. }
  657. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  658. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  659. if errorCode == 0 {
  660. let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  661. if forced || directory?.etag != metadata?.etag || directory?.e2eEncrypted ?? false {
  662. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  663. if errorCode == 0 {
  664. self.metadataFolder = metadataFolder
  665. // E2EE
  666. if let metadataFolder = metadataFolder {
  667. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  668. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { (account, e2eMetadata, errorCode, errorDescription) in
  669. if errorCode == 0 && e2eMetadata != nil {
  670. if !NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  671. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorDecodeMetadata, forced: true)
  672. } else {
  673. self.reloadDataSource()
  674. }
  675. } else if errorCode != NCGlobal.shared.ErrorResourceNotFound {
  676. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.ErrorDecodeMetadata, forced: true)
  677. }
  678. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  679. }
  680. } else {
  681. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  682. }
  683. } else {
  684. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  685. }
  686. } else {
  687. completion(nil, nil, errorCode, errorDescription)
  688. }
  689. }
  690. } else {
  691. completion(nil, nil, 0, "")
  692. }
  693. } else {
  694. completion(nil, nil, errorCode, errorDescription)
  695. }
  696. }
  697. }
  698. }
  699. // MARK: - Collection View
  700. extension NCCollectionViewCommon: UICollectionViewDelegate {
  701. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  702. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  703. metadataTouch = metadata
  704. selectedIndexPath = indexPath
  705. if isEditMode {
  706. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  707. selectOcId.remove(at: index)
  708. } else {
  709. selectOcId.append(metadata.ocId)
  710. }
  711. collectionView.reloadItems(at: [indexPath])
  712. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  713. return
  714. }
  715. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  716. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorE2EENotEnabled, forced: true)
  717. return
  718. }
  719. if metadata.directory {
  720. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  721. // FILES
  722. if layoutKey == NCGlobal.shared.layoutViewFiles {
  723. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  724. if viewController.isViewLoaded {
  725. self.navigationController?.pushViewController(viewController, animated: true)
  726. }
  727. } else {
  728. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  729. vcFiles.isRoot = false
  730. vcFiles.serverUrl = serverUrlPush
  731. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  732. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  733. self.navigationController?.pushViewController(vcFiles, animated: true)
  734. }
  735. }
  736. // FAVORITE
  737. if layoutKey == NCGlobal.shared.layoutViewFavorite {
  738. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  739. if viewController.isViewLoaded {
  740. self.navigationController?.pushViewController(viewController, animated: true)
  741. }
  742. } else {
  743. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  744. vcFavorite.serverUrl = serverUrlPush
  745. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  746. appDelegate.listFavoriteVC[serverUrlPush] = vcFavorite
  747. self.navigationController?.pushViewController(vcFavorite, animated: true)
  748. }
  749. }
  750. // OFFLINE
  751. if layoutKey == NCGlobal.shared.layoutViewOffline {
  752. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  753. if viewController.isViewLoaded {
  754. self.navigationController?.pushViewController(viewController, animated: true)
  755. }
  756. } else {
  757. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  758. vcOffline.serverUrl = serverUrlPush
  759. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  760. appDelegate.listOfflineVC[serverUrlPush] = vcOffline
  761. self.navigationController?.pushViewController(vcOffline, animated: true)
  762. }
  763. }
  764. // RECENT ( for push use Files ... he he he )
  765. if layoutKey == NCGlobal.shared.layoutViewRecent {
  766. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  767. if viewController.isViewLoaded {
  768. self.navigationController?.pushViewController(viewController, animated: true)
  769. }
  770. } else {
  771. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  772. vcFiles.isRoot = false
  773. vcFiles.serverUrl = serverUrlPush
  774. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  775. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  776. self.navigationController?.pushViewController(vcFiles, animated: true)
  777. }
  778. }
  779. //VIEW IN FOLDER
  780. if layoutKey == NCGlobal.shared.layoutViewViewInFolder {
  781. let vcFileViewInFolder:NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  782. vcFileViewInFolder.serverUrl = serverUrlPush
  783. vcFileViewInFolder.titleCurrentFolder = metadataTouch!.fileNameView
  784. self.navigationController?.pushViewController(vcFileViewInFolder, animated: true)
  785. }
  786. // SHARES ( for push use Files ... he he he )
  787. if layoutKey == NCGlobal.shared.layoutViewShares {
  788. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  789. if viewController.isViewLoaded {
  790. self.navigationController?.pushViewController(viewController, animated: true)
  791. }
  792. } else {
  793. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  794. vcFiles.isRoot = false
  795. vcFiles.serverUrl = serverUrlPush
  796. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  797. appDelegate.listFilesVC[serverUrlPush] = vcFiles
  798. self.navigationController?.pushViewController(vcFiles, animated: true)
  799. }
  800. }
  801. } else {
  802. guard let metadataTouch = metadataTouch else { return }
  803. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  804. var metadatas: [tableMetadata] = []
  805. for metadata in dataSource.metadatas {
  806. if metadata.typeFile == NCGlobal.shared.metadataTypeFileImage || metadata.typeFile == NCGlobal.shared.metadataTypeFileVideo || metadata.typeFile == NCGlobal.shared.metadataTypeFileAudio {
  807. metadatas.append(metadata)
  808. }
  809. }
  810. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: metadatas)
  811. return
  812. }
  813. if CCUtility.fileProviderStorageExists(metadataTouch.ocId, fileNameView: metadataTouch.fileNameView) {
  814. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: [metadataTouch])
  815. } else if NCCommunication.shared.isNetworkReachable() {
  816. NCNetworking.shared.download(metadata: metadataTouch, selector: NCGlobal.shared.selectorLoadFileView) { (_) in }
  817. } else {
  818. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.ErrorOffline, forced: true)
  819. }
  820. }
  821. }
  822. func collectionViewSelectAll() {
  823. selectOcId.removeAll()
  824. for metadata in metadatasSource {
  825. selectOcId.append(metadata.ocId)
  826. }
  827. collectionView.reloadData()
  828. }
  829. @available(iOS 13.0, *)
  830. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  831. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  832. metadataTouch = metadata
  833. let identifier = indexPath as NSCopying
  834. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  835. return NCViewerProviderContextMenu(metadata: metadata)
  836. }, actionProvider: { suggestedActions in
  837. return NCCollectionCommon.shared.contextMenuConfiguration(metadata: metadata, viewController: self, enableDeleteLocal: true, enableViewInFolder: false)
  838. })
  839. }
  840. @available(iOS 13.0, *)
  841. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  842. animator.addCompletion {
  843. if let indexPath = configuration.identifier as? IndexPath {
  844. self.collectionView(collectionView, didSelectItemAt: indexPath)
  845. }
  846. }
  847. }
  848. }
  849. extension NCCollectionViewCommon: UICollectionViewDataSource {
  850. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  851. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  852. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  853. }
  854. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  855. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  856. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  857. }
  858. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  859. if kind == UICollectionView.elementKindSectionHeader {
  860. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  861. if collectionView.collectionViewLayout == gridLayout {
  862. header.buttonSwitch.setImage(UIImage.init(named: "switchList")!.image(color: NCBrandColor.shared.icon, size: 50), for: .normal)
  863. } else {
  864. header.buttonSwitch.setImage(UIImage.init(named: "switchGrid")!.image(color: NCBrandColor.shared.icon, size: 50), for: .normal)
  865. }
  866. header.delegate = self
  867. header.setStatusButton(count: dataSource.metadatas.count)
  868. header.setTitleSorted(datasourceTitleButton: titleButton)
  869. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  870. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  871. return header
  872. } else {
  873. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  874. let info = dataSource.getFilesInformation()
  875. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  876. return footer
  877. }
  878. }
  879. func numberOfSections(in collectionView: UICollectionView) -> Int {
  880. return 1
  881. }
  882. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  883. let numberItems = dataSource.numberOfItems()
  884. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  885. return numberItems
  886. }
  887. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  888. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  889. if layout == NCGlobal.shared.layoutList {
  890. return collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  891. } else {
  892. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  893. }
  894. }
  895. var tableShare: tableShare?
  896. var isShare = false
  897. var isMounted = false
  898. if metadataFolder != nil {
  899. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  900. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  901. }
  902. if dataSource.metadataShare[metadata.ocId] != nil {
  903. tableShare = dataSource.metadataShare[metadata.ocId]
  904. }
  905. //
  906. // LAYOUT LIST
  907. //
  908. if layout == NCGlobal.shared.layoutList {
  909. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  910. cell.delegate = self
  911. cell.objectId = metadata.ocId
  912. cell.indexPath = indexPath
  913. cell.labelTitle.text = metadata.fileNameView
  914. cell.labelTitle.textColor = NCBrandColor.shared.textView
  915. cell.separator.backgroundColor = NCBrandColor.shared.separator
  916. cell.imageSelect.image = nil
  917. cell.imageStatus.image = nil
  918. cell.imageLocal.image = nil
  919. cell.imageFavorite.image = nil
  920. cell.imageShared.image = nil
  921. cell.imageShared.clearLayerMask()
  922. cell.imageMore.image = nil
  923. cell.imageItem.image = nil
  924. cell.imageItem.backgroundColor = nil
  925. cell.progressView.progress = 0.0
  926. if metadata.directory {
  927. if metadata.e2eEncrypted {
  928. cell.imageItem.image = NCCollectionCommon.images.folderEncrypted
  929. } else if isShare {
  930. cell.imageItem.image = NCCollectionCommon.images.folderSharedWithMe
  931. } else if (tableShare != nil && tableShare?.shareType != 3) {
  932. cell.imageItem.image = NCCollectionCommon.images.folderSharedWithMe
  933. } else if (tableShare != nil && tableShare?.shareType == 3) {
  934. cell.imageItem.image = NCCollectionCommon.images.folderPublic
  935. } else if metadata.mountType == "group" {
  936. cell.imageItem.image = NCCollectionCommon.images.folderGroup
  937. } else if isMounted {
  938. cell.imageItem.image = NCCollectionCommon.images.folderExternal
  939. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  940. cell.imageItem.image = NCCollectionCommon.images.folderAutomaticUpload
  941. } else {
  942. cell.imageItem.image = NCCollectionCommon.images.folder
  943. }
  944. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  945. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  946. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  947. // Local image: offline
  948. if tableDirectory != nil && tableDirectory!.offline {
  949. cell.imageLocal.image = NCCollectionCommon.images.offlineFlag
  950. }
  951. } else {
  952. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  953. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  954. } else {
  955. if metadata.hasPreview {
  956. cell.imageItem.backgroundColor = .lightGray
  957. } else {
  958. if metadata.iconName.count > 0 {
  959. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  960. } else {
  961. cell.imageItem.image = NCCollectionCommon.images.file
  962. }
  963. }
  964. }
  965. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  966. // image local
  967. if dataSource.metadataOffLine.contains(metadata.ocId) {
  968. cell.imageLocal.image = NCCollectionCommon.images.offlineFlag
  969. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  970. cell.imageLocal.image = NCCollectionCommon.images.local
  971. }
  972. }
  973. // image Favorite
  974. if metadata.favorite {
  975. cell.imageFavorite.image = NCCollectionCommon.images.favorite
  976. }
  977. // Share image
  978. if (isShare) {
  979. cell.imageShared.image = NCCollectionCommon.images.shared
  980. } else if (tableShare != nil && tableShare?.shareType == 3) {
  981. cell.imageShared.image = NCCollectionCommon.images.shareByLink
  982. } else if (tableShare != nil && tableShare?.shareType != 3) {
  983. cell.imageShared.image = NCCollectionCommon.images.shared
  984. } else {
  985. cell.imageShared.image = NCCollectionCommon.images.canShare
  986. }
  987. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userId {
  988. var fileNameUser = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId
  989. fileNameUser = fileNameUser + ".png"
  990. if FileManager.default.fileExists(atPath: fileNameUser) {
  991. cell.imageShared.avatar()
  992. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  993. } else {
  994. NCCommunication.shared.downloadAvatar(userId: metadata.ownerId, fileNameLocalPath: fileNameUser, size: NCGlobal.shared.avatarSize) { (account, data, errorCode, errorMessage) in
  995. if errorCode == 0 && account == self.appDelegate.account {
  996. cell.imageShared.avatar()
  997. cell.imageShared.image = UIImage(contentsOfFile: fileNameUser)
  998. }
  999. }
  1000. }
  1001. }
  1002. // Transfer
  1003. var progress: Float = 0.0
  1004. var totalBytes: Int64 = 0
  1005. if let progressType = appDelegate.listProgress[metadata.ocId] {
  1006. progress = progressType.progress
  1007. totalBytes = progressType.totalBytes
  1008. }
  1009. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status >= NCGlobal.shared.metadataStatusTypeUpload {
  1010. cell.progressView.isHidden = false
  1011. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.buttonStop)
  1012. } else {
  1013. cell.progressView.isHidden = true
  1014. cell.progressView.progress = progress
  1015. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCCollectionCommon.images.buttonMore)
  1016. }
  1017. // Write status on Label Info
  1018. switch metadata.status {
  1019. case NCGlobal.shared.metadataStatusWaitDownload:
  1020. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1021. break
  1022. case NCGlobal.shared.metadataStatusInDownload:
  1023. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1024. break
  1025. case NCGlobal.shared.metadataStatusDownloading:
  1026. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1027. break
  1028. case NCGlobal.shared.metadataStatusWaitUpload:
  1029. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1030. break
  1031. case NCGlobal.shared.metadataStatusInUpload:
  1032. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1033. break
  1034. case NCGlobal.shared.metadataStatusUploading:
  1035. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1036. break
  1037. default:
  1038. break
  1039. }
  1040. // Live Photo
  1041. if metadata.livePhoto {
  1042. cell.imageStatus.image = NCCollectionCommon.images.livePhoto
  1043. }
  1044. // E2EE
  1045. if metadata.e2eEncrypted || isEncryptedFolder {
  1046. cell.hideButtonShare(true)
  1047. } else {
  1048. cell.hideButtonShare(false)
  1049. }
  1050. // Remove last separator
  1051. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1052. cell.separator.isHidden = true
  1053. } else {
  1054. cell.separator.isHidden = false
  1055. }
  1056. // Edit mode
  1057. if isEditMode {
  1058. cell.selectMode(true)
  1059. if selectOcId.contains(metadata.ocId) {
  1060. cell.selected(true)
  1061. } else {
  1062. cell.selected(false)
  1063. }
  1064. } else {
  1065. cell.selectMode(false)
  1066. }
  1067. // Disable Share Button
  1068. if appDelegate.disableSharesView {
  1069. cell.hideButtonShare(true)
  1070. }
  1071. return cell
  1072. }
  1073. //
  1074. // LAYOUT GRID
  1075. //
  1076. if layout == NCGlobal.shared.layoutGrid {
  1077. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1078. cell.delegate = self
  1079. cell.objectId = metadata.ocId
  1080. cell.indexPath = indexPath
  1081. cell.labelTitle.text = metadata.fileNameView
  1082. cell.labelTitle.textColor = NCBrandColor.shared.textView
  1083. cell.imageSelect.image = nil
  1084. cell.imageStatus.image = nil
  1085. cell.imageLocal.image = nil
  1086. cell.imageFavorite.image = nil
  1087. cell.imageItem.image = nil
  1088. cell.imageItem.backgroundColor = nil
  1089. cell.progressView.progress = 0.0
  1090. if metadata.directory {
  1091. if metadata.e2eEncrypted {
  1092. cell.imageItem.image = NCCollectionCommon.images.folderEncrypted
  1093. } else if isShare {
  1094. cell.imageItem.image = NCCollectionCommon.images.folderSharedWithMe
  1095. } else if (tableShare != nil && tableShare!.shareType != 3) {
  1096. cell.imageItem.image = NCCollectionCommon.images.folderSharedWithMe
  1097. } else if (tableShare != nil && tableShare!.shareType == 3) {
  1098. cell.imageItem.image = NCCollectionCommon.images.folderPublic
  1099. } else if metadata.mountType == "group" {
  1100. cell.imageItem.image = NCCollectionCommon.images.folderGroup
  1101. } else if isMounted {
  1102. cell.imageItem.image = NCCollectionCommon.images.folderExternal
  1103. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1104. cell.imageItem.image = NCCollectionCommon.images.folderAutomaticUpload
  1105. } else {
  1106. cell.imageItem.image = NCCollectionCommon.images.folder
  1107. }
  1108. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1109. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1110. // Local image: offline
  1111. if tableDirectory != nil && tableDirectory!.offline {
  1112. cell.imageLocal.image = NCCollectionCommon.images.offlineFlag
  1113. }
  1114. } else {
  1115. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1116. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1117. } else {
  1118. if metadata.hasPreview {
  1119. cell.imageItem.backgroundColor = .lightGray
  1120. } else {
  1121. if metadata.iconName.count > 0 {
  1122. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1123. } else {
  1124. cell.imageItem.image = NCCollectionCommon.images.file
  1125. }
  1126. }
  1127. }
  1128. // image Local
  1129. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1130. cell.imageLocal.image = NCCollectionCommon.images.offlineFlag
  1131. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1132. cell.imageLocal.image = NCCollectionCommon.images.local
  1133. }
  1134. }
  1135. // image Favorite
  1136. if metadata.favorite {
  1137. cell.imageFavorite.image = NCCollectionCommon.images.favorite
  1138. }
  1139. // Transfer
  1140. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status >= NCGlobal.shared.metadataStatusTypeUpload {
  1141. cell.progressView.isHidden = false
  1142. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCCollectionCommon.images.buttonStop)
  1143. } else {
  1144. cell.progressView.isHidden = true
  1145. cell.progressView.progress = 0.0
  1146. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCCollectionCommon.images.buttonMore)
  1147. }
  1148. // Live Photo
  1149. if metadata.livePhoto {
  1150. cell.imageStatus.image = NCCollectionCommon.images.livePhoto
  1151. }
  1152. // Edit mode
  1153. if isEditMode {
  1154. cell.selectMode(true)
  1155. if selectOcId.contains(metadata.ocId) {
  1156. cell.selected(true)
  1157. } else {
  1158. cell.selected(false)
  1159. }
  1160. } else {
  1161. cell.selectMode(false)
  1162. }
  1163. return cell
  1164. }
  1165. return collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1166. }
  1167. }
  1168. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1169. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1170. headerRichWorkspaceHeight = 0
  1171. if let richWorkspaceText = richWorkspaceText {
  1172. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1173. if trimmed.count > 0 && !isSearching {
  1174. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1175. }
  1176. }
  1177. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1178. }
  1179. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1180. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1181. }
  1182. }