NCCollectionViewCommon.swift 72 KB

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