NCCollectionViewCommon.swift 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  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 {
  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?.dimsBackgroundDuringPresentation = 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. // 3D Touch peek and pop
  99. if traitCollection.forceTouchCapability == .available {
  100. registerForPreviewing(with: self, sourceView: view)
  101. }
  102. // Long Press on CollectionView
  103. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  104. longPressedGesture.minimumPressDuration = 0.5
  105. longPressedGesture.delegate = self
  106. longPressedGesture.delaysTouchesBegan = true
  107. collectionView.addGestureRecognizer(longPressedGesture)
  108. // Notification
  109. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: k_notificationCenter_initializeMain), object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSourceNetworkForced), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_changeStatusFolderE2EE), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: k_notificationCenter_closeRichWorkspaceWebView), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_copyFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_createFolder), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadStartFile), object: nil)
  122. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  123. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadCancelFile), object: nil)
  124. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadStartFile), object: nil)
  125. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  126. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadCancelFile), object: nil)
  127. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  128. changeTheming()
  129. }
  130. override func viewWillAppear(_ animated: Bool) {
  131. super.viewWillAppear(animated)
  132. appDelegate.activeViewController = self
  133. if serverUrl == "" {
  134. appDelegate.activeServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  135. } else {
  136. appDelegate.activeServerUrl = serverUrl
  137. }
  138. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  139. gridLayout.itemForLine = CGFloat(itemForLine)
  140. if layout == k_layout_list {
  141. collectionView?.collectionViewLayout = listLayout
  142. } else {
  143. collectionView?.collectionViewLayout = gridLayout
  144. }
  145. navigationController?.navigationBar.prefersLargeTitles = true
  146. navigationController?.setNavigationBarHidden(false, animated: true)
  147. setNavigationItem()
  148. reloadDataSource()
  149. }
  150. override func viewDidAppear(_ animated: Bool) {
  151. super.viewDidAppear(animated)
  152. reloadDataSourceNetwork()
  153. }
  154. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  155. let viewController = presentationController.presentedViewController
  156. if viewController is NCViewerRichWorkspaceWebView {
  157. closeRichWorkspaceWebView()
  158. } else if viewController is UINavigationController {
  159. if (viewController as! UINavigationController).topViewController is NCFileViewInFolder {
  160. appDelegate.activeFileViewInFolder = nil
  161. }
  162. }
  163. }
  164. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  165. super.viewWillTransition(to: size, with: coordinator)
  166. coordinator.animate(alongsideTransition: nil) { _ in
  167. self.collectionView?.collectionViewLayout.invalidateLayout()
  168. }
  169. }
  170. override var canBecomeFirstResponder: Bool {
  171. return true
  172. }
  173. func setNavigationItem() {
  174. if isEditMode {
  175. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  176. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  177. navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  178. } else {
  179. navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  180. navigationItem.leftBarButtonItem = nil
  181. navigationItem.title = titleCurrentFolder
  182. }
  183. }
  184. // MARK: - NotificationCenter
  185. @objc func initializeMain() {
  186. if appDelegate.account.count == 0 { return }
  187. if searchController?.isActive ?? false {
  188. searchController?.isActive = false
  189. }
  190. // set active serverUrl
  191. if self.view?.window != nil {
  192. if serverUrl == "" {
  193. appDelegate.activeServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  194. } else {
  195. appDelegate.activeServerUrl = serverUrl
  196. }
  197. }
  198. self.navigationController?.popToRootViewController(animated: false)
  199. appDelegate.listFilesVC.removeAllObjects()
  200. appDelegate.listFavoriteVC.removeAllObjects()
  201. appDelegate.listOfflineVC.removeAllObjects()
  202. reloadDataSource()
  203. }
  204. @objc func changeTheming() {
  205. view.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  206. collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  207. collectionView.reloadData()
  208. }
  209. @objc func reloadDataSource(_ notification: NSNotification) {
  210. if self.view?.window == nil { return }
  211. reloadDataSource()
  212. }
  213. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  214. if self.view?.window == nil { return }
  215. if let userInfo = notification.userInfo as NSDictionary? {
  216. if let serverUrl = userInfo["serverUrl"] as? String {
  217. if serverUrl == self.serverUrl {
  218. reloadDataSourceNetwork(forced: true)
  219. }
  220. }
  221. } else {
  222. reloadDataSourceNetwork(forced: true)
  223. }
  224. }
  225. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  226. if self.view?.window == nil { return }
  227. reloadDataSource()
  228. }
  229. @objc func closeRichWorkspaceWebView() {
  230. if self.view?.window == nil { return }
  231. reloadDataSourceNetwork()
  232. }
  233. @objc func deleteFile(_ notification: NSNotification) {
  234. if self.view?.window == nil { return }
  235. if let userInfo = notification.userInfo as NSDictionary? {
  236. if let ocId = userInfo["ocId"] as? String, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  237. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  238. if onlyLocal {
  239. reloadDataSource()
  240. } else if metadata.fileNameView.lowercased() == k_fileNameRichWorkspace.lowercased() {
  241. reloadDataSourceNetwork(forced: true)
  242. } else {
  243. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  244. let indexPath = IndexPath(row: row, section: 0)
  245. collectionView?.performBatchUpdates({
  246. collectionView?.deleteItems(at: [indexPath])
  247. }, completion: { (_) in
  248. self.collectionView?.reloadData()
  249. })
  250. }
  251. }
  252. }
  253. }
  254. }
  255. }
  256. @objc func moveFile(_ notification: NSNotification) {
  257. if self.view?.window == nil { return }
  258. if let userInfo = notification.userInfo as NSDictionary? {
  259. if let ocId = userInfo["ocId"] as? String, let ocIdNew = userInfo["ocIdNew"] as? String {
  260. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId), let metadataNew = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocIdNew) {
  261. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  262. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  263. let indexPath = IndexPath(row: row, section: 0)
  264. collectionView?.performBatchUpdates({
  265. collectionView?.deleteItems(at: [indexPath])
  266. }, completion: { (_) in
  267. self.collectionView?.reloadData()
  268. })
  269. }
  270. } else if metadataNew.serverUrl == serverUrl && metadata.account == appDelegate.account {
  271. if let row = dataSource.addMetadata(metadataNew) {
  272. let indexPath = IndexPath(row: row, section: 0)
  273. collectionView?.performBatchUpdates({
  274. collectionView?.insertItems(at: [indexPath])
  275. }, completion: { (_) in
  276. self.collectionView?.reloadData()
  277. })
  278. }
  279. }
  280. }
  281. }
  282. }
  283. }
  284. @objc func copyFile(_ notification: NSNotification) {
  285. if self.view?.window == nil { return }
  286. if let userInfo = notification.userInfo as NSDictionary? {
  287. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  288. if serverUrlTo == self.serverUrl {
  289. reloadDataSource()
  290. }
  291. }
  292. }
  293. }
  294. @objc func renameFile(_ notification: NSNotification) {
  295. if self.view?.window == nil { return }
  296. reloadDataSource()
  297. }
  298. @objc func createFolder(_ notification: NSNotification) {
  299. if self.view?.window == nil { return }
  300. if let userInfo = notification.userInfo as NSDictionary? {
  301. if let ocId = userInfo["ocId"] as? String {
  302. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  303. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  304. if let row = dataSource.addMetadata(metadata) {
  305. let indexPath = IndexPath(row: row, section: 0)
  306. collectionView?.performBatchUpdates({
  307. collectionView?.insertItems(at: [indexPath])
  308. }, completion: { (_) in
  309. self.collectionView?.reloadData()
  310. })
  311. }
  312. }
  313. }
  314. }
  315. } else {
  316. reloadDataSourceNetwork()
  317. }
  318. }
  319. @objc func favoriteFile(_ notification: NSNotification) {
  320. if self.view?.window == nil { return }
  321. if let userInfo = notification.userInfo as NSDictionary? {
  322. if let ocId = userInfo["ocId"] as? String, let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  323. if dataSource.getIndexMetadata(ocId: metadata.ocId) != nil {
  324. reloadDataSource()
  325. }
  326. }
  327. }
  328. }
  329. @objc func downloadStartFile(_ notification: NSNotification) {
  330. if self.view?.window == nil { return }
  331. if let userInfo = notification.userInfo as NSDictionary? {
  332. if let ocId = userInfo["ocId"] as? String {
  333. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  334. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  335. let indexPath = IndexPath(row: row, section: 0)
  336. collectionView?.reloadItems(at: [indexPath])
  337. }
  338. }
  339. }
  340. }
  341. }
  342. @objc func downloadedFile(_ notification: NSNotification) {
  343. if self.view?.window == nil { return }
  344. if let userInfo = notification.userInfo as NSDictionary? {
  345. if let ocId = userInfo["ocId"] as? String, let _ = userInfo["errorCode"] as? Int {
  346. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  347. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  348. let indexPath = IndexPath(row: row, section: 0)
  349. collectionView?.reloadItems(at: [indexPath])
  350. }
  351. }
  352. }
  353. }
  354. }
  355. @objc func downloadCancelFile(_ notification: NSNotification) {
  356. if self.view?.window == nil { return }
  357. if let userInfo = notification.userInfo as NSDictionary? {
  358. if let ocId = userInfo["ocId"] as? String {
  359. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  360. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  361. let indexPath = IndexPath(row: row, section: 0)
  362. collectionView?.reloadItems(at: [indexPath])
  363. }
  364. }
  365. }
  366. }
  367. }
  368. @objc func uploadStartFile(_ notification: NSNotification) {
  369. if self.view?.window == nil { return }
  370. if let userInfo = notification.userInfo as NSDictionary? {
  371. if let ocId = userInfo["ocId"] as? String {
  372. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  373. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  374. if let row = dataSource.addMetadata(metadata) {
  375. let indexPath = IndexPath(row: row, section: 0)
  376. collectionView?.performBatchUpdates({
  377. collectionView?.insertItems(at: [indexPath])
  378. }, completion: { (_) in
  379. self.collectionView?.reloadData()
  380. })
  381. }
  382. }
  383. }
  384. }
  385. }
  386. }
  387. @objc func uploadedFile(_ notification: NSNotification) {
  388. if self.view?.window == nil { return }
  389. if let userInfo = notification.userInfo as NSDictionary? {
  390. if let ocId = userInfo["ocId"] as? String, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int {
  391. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  392. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  393. dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  394. collectionView?.reloadData()
  395. }
  396. }
  397. }
  398. }
  399. }
  400. @objc func uploadCancelFile(_ notification: NSNotification) {
  401. if self.view?.window == nil { return }
  402. if let userInfo = notification.userInfo as NSDictionary? {
  403. if let ocId = userInfo["ocId"] as? String {
  404. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  405. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  406. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  407. let indexPath = IndexPath(row: row, section: 0)
  408. collectionView?.performBatchUpdates({
  409. collectionView?.deleteItems(at: [indexPath])
  410. }, completion: { (_) in
  411. self.collectionView?.reloadData()
  412. })
  413. } else {
  414. self.reloadDataSource()
  415. }
  416. }
  417. }
  418. }
  419. }
  420. }
  421. @objc func triggerProgressTask(_ notification: NSNotification) {
  422. if self.view?.window == nil { return }
  423. if let userInfo = notification.userInfo as NSDictionary? {
  424. if let ocId = userInfo["ocId"] as? String {
  425. let _ = userInfo["account"] as? String ?? ""
  426. let _ = userInfo["serverUrl"] as? String ?? ""
  427. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  428. let progress = progressNumber.floatValue
  429. let status = userInfo["status"] as? Int ?? Int(k_metadataStatusNormal)
  430. let totalBytes = userInfo["totalBytes"] as? Double ?? 0
  431. let totalBytesExpected = userInfo["totalBytesExpected"] as? Double ?? 0
  432. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: userInfo["ocId"] as? NSString ?? "")
  433. if let index = dataSource.getIndexMetadata(ocId: ocId) {
  434. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  435. if cell is NCListCell {
  436. let cell = cell as! NCListCell
  437. if progress > 0 {
  438. cell.progressView?.isHidden = false
  439. cell.progressView?.progress = progress
  440. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  441. if status == k_metadataStatusInDownload {
  442. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  443. } else if status == k_metadataStatusInUpload {
  444. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  445. }
  446. }
  447. } else if cell is NCTransferCell {
  448. let cell = cell as! NCTransferCell
  449. if progress > 0 {
  450. cell.progressView?.isHidden = false
  451. cell.progressView?.progress = progress
  452. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  453. if status == k_metadataStatusInDownload {
  454. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  455. } else if status == k_metadataStatusInUpload {
  456. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  457. }
  458. }
  459. } else if cell is NCGridCell {
  460. let cell = cell as! NCGridCell
  461. if progress > 0 {
  462. cell.progressView.isHidden = false
  463. cell.progressView.progress = progress
  464. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  465. }
  466. }
  467. }
  468. }
  469. }
  470. }
  471. }
  472. // MARK: - Empty
  473. func emptyDataSetView(_ view: NCEmptyView) {
  474. if searchController?.isActive ?? false {
  475. view.emptyImage.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "search"), width: 300, height: 300, color: .gray)
  476. if isReloadDataSourceNetworkInProgress {
  477. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  478. } else {
  479. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  480. }
  481. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  482. } else if isReloadDataSourceNetworkInProgress {
  483. view.emptyImage.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "networkInProgress"), width: 300, height: 300, color: .gray)
  484. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  485. view.emptyDescription.text = ""
  486. } else {
  487. view.emptyImage.image = emptyImage
  488. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  489. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  490. }
  491. }
  492. // MARK: - SEARCH
  493. func updateSearchResults(for searchController: UISearchController) {
  494. timerInputSearch?.invalidate()
  495. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  496. literalSearch = searchController.searchBar.text
  497. collectionView?.reloadData()
  498. }
  499. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  500. isSearching = true
  501. metadatasSource.removeAll()
  502. reloadDataSource()
  503. }
  504. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  505. isSearching = false
  506. literalSearch = ""
  507. reloadDataSource()
  508. }
  509. // MARK: - TAP EVENT
  510. @objc func tapSelect(sender: Any) {
  511. isEditMode = !isEditMode
  512. selectOcId.removeAll()
  513. setNavigationItem()
  514. self.collectionView.reloadData()
  515. }
  516. func tapSwitchHeader(sender: Any) {
  517. if collectionView.collectionViewLayout == gridLayout {
  518. // list layout
  519. UIView.animate(withDuration: 0.0, animations: {
  520. self.collectionView.collectionViewLayout.invalidateLayout()
  521. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  522. self.collectionView.reloadData()
  523. })
  524. })
  525. layout = k_layout_list
  526. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  527. } else {
  528. // grid layout
  529. UIView.animate(withDuration: 0.0, animations: {
  530. self.collectionView.collectionViewLayout.invalidateLayout()
  531. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  532. self.collectionView.reloadData()
  533. })
  534. })
  535. layout = k_layout_grid
  536. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  537. }
  538. }
  539. func tapOrderHeader(sender: Any) {
  540. let sortMenu = NCSortMenu()
  541. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  542. }
  543. @objc func tapSelectMenu(sender: Any) {
  544. guard let tabBarController = self.tabBarController else { return }
  545. toggleMoreSelect(viewController: tabBarController, selectOcId: selectOcId)
  546. }
  547. func tapMoreHeader(sender: Any) { }
  548. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  549. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  550. }
  551. func tapShareListItem(with objectId: String, sender: Any) {
  552. if isEditMode { return }
  553. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  554. NCNetworkingNotificationCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  555. }
  556. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  557. if isEditMode { return }
  558. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  559. if namedButtonMore == k_buttonMoreMore {
  560. toggleMoreMenu(viewController: self, metadata: metadata)
  561. } else if namedButtonMore == k_buttonMoreStop {
  562. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  563. }
  564. }
  565. func tapRichWorkspace(sender: Any) {
  566. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  567. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  568. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  569. viewerRichWorkspace.serverUrl = serverUrl
  570. navigationController.modalPresentationStyle = .fullScreen
  571. self.present(navigationController, animated: true, completion: nil)
  572. }
  573. }
  574. }
  575. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  576. openMenuItems(with: objectId, gestureRecognizer: gestureRecognizer)
  577. }
  578. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  579. openMenuItems(with: objectId, gestureRecognizer: gestureRecognizer)
  580. }
  581. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  582. }
  583. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  584. }
  585. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  586. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  587. }
  588. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  589. if gestureRecognizer.state != .began { return }
  590. if serverUrl == "" { return }
  591. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  592. metadataTouch = metadata
  593. } else {
  594. metadataTouch = nil
  595. }
  596. var listMenuItems: [UIMenuItem] = []
  597. let touchPoint = gestureRecognizer.location(in: collectionView)
  598. becomeFirstResponder()
  599. if metadataTouch != nil {
  600. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_copy_file_", comment: ""), action: #selector(copyFileMenu(_:))))
  601. }
  602. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu(_:))))
  603. if metadataTouch != nil {
  604. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_quicklook_", comment: ""), action: #selector(openQuickLookMenu(_:))))
  605. if !NCBrandOptions.sharedInstance.disable_openin_file {
  606. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_in_", comment: ""), action: #selector(openInMenu(_:))))
  607. }
  608. }
  609. if listMenuItems.count > 0 {
  610. UIMenuController.shared.menuItems = listMenuItems
  611. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  612. UIMenuController.shared.setMenuVisible(true, animated: true)
  613. }
  614. }
  615. // MARK: - Menu Item
  616. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  617. if (#selector(pasteFilesMenu(_:)) == action) {
  618. if UIPasteboard.general.items.count > 0 {
  619. return true
  620. }
  621. }
  622. if (#selector(openQuickLookMenu(_:)) == action || #selector(openInMenu(_:)) == action || #selector(copyFileMenu(_:)) == action) {
  623. guard let metadata = metadataTouch else { return false }
  624. if !metadata.directory && metadata.status == k_metadataStatusNormal {
  625. return true
  626. }
  627. }
  628. return false
  629. }
  630. @objc func copyFileMenu(_ notification: Any) {
  631. var metadatas: [tableMetadata] = []
  632. var items = [[String : Any]]()
  633. if isEditMode {
  634. for ocId in selectOcId {
  635. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  636. metadatas.append(metadata)
  637. }
  638. }
  639. } else {
  640. guard let metadata = metadataTouch else { return }
  641. metadatas.append(metadata)
  642. }
  643. for metadata in metadatas {
  644. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  645. do {
  646. let etagPasteboard = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  647. items.append([k_metadataKeyedUnarchiver:etagPasteboard])
  648. } catch {
  649. print("error")
  650. }
  651. } else {
  652. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadCopy, setFavorite: false) { (_) in }
  653. }
  654. }
  655. UIPasteboard.general.setItems(items, options: [:])
  656. if isEditMode {
  657. tapSelect(sender: self)
  658. }
  659. }
  660. @objc func pasteFilesMenu(_ notification: Any) {
  661. var listData: [String] = []
  662. for item in UIPasteboard.general.items {
  663. for object in item {
  664. let contentType = object.key
  665. let data = object.value
  666. if contentType == k_metadataKeyedUnarchiver {
  667. do {
  668. if let ocId = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? String{
  669. uploadPasteOcId(ocId)
  670. }
  671. } catch {
  672. print("error")
  673. }
  674. continue
  675. }
  676. if data is String {
  677. if listData.contains(data as! String) {
  678. continue
  679. } else {
  680. listData.append(data as! String)
  681. }
  682. }
  683. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  684. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  685. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, data: data)
  686. }
  687. }
  688. }
  689. }
  690. private func uploadPasteFile(fileName: String, ext: String, contentType: String, data: Any) {
  691. do {
  692. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  693. let ocId = UUID().uuidString
  694. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  695. if data is UIImage {
  696. try (data as? UIImage)?.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: filePath))
  697. } else if data is Data {
  698. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  699. } else if data is String {
  700. try (data as? String)?.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
  701. } else {
  702. return
  703. }
  704. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  705. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  706. metadataForUpload.sessionSelector = selectorUploadFile
  707. metadataForUpload.size = Double(NCUtilityFileSystem.shared.getFileSize(filePath: filePath))
  708. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  709. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  710. } catch { }
  711. }
  712. private func uploadPasteOcId(_ ocId: String) {
  713. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  714. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  715. let fileNameView = NCUtility.shared.createFileName(metadata.fileNameView, serverUrl: serverUrl, account: appDelegate.account)
  716. let ocId = NSUUID().uuidString
  717. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  718. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
  719. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  720. metadataForUpload.sessionSelector = selectorUploadFile
  721. metadataForUpload.size = metadata.size
  722. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  723. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  724. }
  725. }
  726. }
  727. @objc func openQuickLookMenu(_ notification: Any) {
  728. guard let metadata = metadataTouch else { return }
  729. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  730. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["ocId": metadata.ocId, "selector": selectorLoadFileQuickLook, "errorCode": 0, "errorDescription": "" ])
  731. } else {
  732. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadFileQuickLook) { (_) in }
  733. }
  734. }
  735. @objc func openInMenu(_ notification: Any) {
  736. guard let metadata = metadataTouch else { return }
  737. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  738. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["ocId": metadata.ocId, "selector": selectorOpenIn, "errorCode": 0, "errorDescription": "" ])
  739. } else {
  740. NCNetworking.shared.download(metadata: metadata, selector: selectorOpenIn) { (_) in }
  741. }
  742. }
  743. // MARK: - DataSource + NC Endpoint
  744. @objc func reloadDataSource() {
  745. if appDelegate.account.count == 0 { return }
  746. // Get richWorkspace Text
  747. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  748. richWorkspaceText = directory?.richWorkspace
  749. // E2EE
  750. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  751. // get auto upload folder
  752. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  753. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  754. // get layout for view
  755. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  756. }
  757. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  758. @objc func reloadDataSourceNetworkRefreshControl() {
  759. reloadDataSourceNetwork(forced: true)
  760. }
  761. @objc func networkSearch() {
  762. if appDelegate.account.count == 0 { return }
  763. if literalSearch?.count ?? 0 > 1 {
  764. isReloadDataSourceNetworkInProgress = true
  765. collectionView?.reloadData()
  766. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  767. if self.searchController?.isActive ?? false && errorCode == 0 {
  768. self.metadatasSource = metadatas!
  769. }
  770. self.refreshControl.endRefreshing()
  771. self.isReloadDataSourceNetworkInProgress = false
  772. self.reloadDataSource()
  773. }
  774. } else {
  775. self.refreshControl.endRefreshing()
  776. }
  777. }
  778. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  779. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  780. if errorCode == 0 {
  781. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  782. if forced || directory?.etag != metadata?.etag || directory?.e2eEncrypted ?? false {
  783. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  784. if errorCode == 0 {
  785. self.metadataFolder = metadataFolder
  786. // E2EE
  787. if let metadataFolder = metadataFolder {
  788. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  789. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { (account, e2eMetadata, errorCode, errorDescription) in
  790. if errorCode == 0 && e2eMetadata != nil {
  791. if !NCEndToEndMetadata.sharedInstance.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  792. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorDecodeMetadata), forced: true)
  793. } else {
  794. self.reloadDataSource()
  795. }
  796. } else if errorCode != k_CCErrorResourceNotFound {
  797. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorDecodeMetadata), forced: true)
  798. }
  799. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  800. }
  801. } else {
  802. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  803. }
  804. } else {
  805. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  806. }
  807. } else {
  808. completion(nil, nil, errorCode, errorDescription)
  809. }
  810. }
  811. } else {
  812. completion(nil, nil, 0, "")
  813. }
  814. } else {
  815. completion(nil, nil, errorCode, errorDescription)
  816. }
  817. }
  818. }
  819. }
  820. // MARK: - 3D Touch peek and pop
  821. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  822. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  823. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  824. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  825. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  826. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  827. viewController.metadata = metadata
  828. if layout == k_layout_grid {
  829. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  830. previewingContext.sourceRect = cell.frame
  831. viewController.imageFile = cell.imageItem.image
  832. } else {
  833. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  834. previewingContext.sourceRect = cell.frame
  835. viewController.imageFile = cell.imageItem.image
  836. }
  837. viewController.showOpenIn = true
  838. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  839. viewController.showShare = false
  840. return viewController
  841. }
  842. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  843. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  844. collectionView(collectionView, didSelectItemAt: indexPath)
  845. }
  846. }
  847. // MARK: - Collection View
  848. extension NCCollectionViewCommon: UICollectionViewDelegate {
  849. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  850. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  851. metadataTouch = metadata
  852. selectedIndexPath = indexPath
  853. if isEditMode {
  854. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  855. selectOcId.remove(at: index)
  856. } else {
  857. selectOcId.append(metadata.ocId)
  858. }
  859. collectionView.reloadItems(at: [indexPath])
  860. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  861. return
  862. }
  863. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  864. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorE2EENotEnabled), forced: true)
  865. return
  866. }
  867. if metadata.directory {
  868. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  869. // FILES
  870. if layoutKey == k_layout_view_files {
  871. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  872. guard let vcFiles = (viewController as? NCFiles) else { return }
  873. if vcFiles.isViewLoaded {
  874. self.navigationController?.pushViewController(vcFiles, animated: true)
  875. }
  876. } else {
  877. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  878. vcFiles.isRoot = false
  879. vcFiles.serverUrl = serverUrlPush
  880. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  881. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  882. self.navigationController?.pushViewController(vcFiles, animated: true)
  883. }
  884. }
  885. // FAVORITE
  886. if layoutKey == k_layout_view_favorite {
  887. if let viewController = appDelegate.listFavoriteVC.value(forKey: serverUrlPush) {
  888. guard let vcFavorite = (viewController as? NCFavorite) else { return }
  889. if vcFavorite.isViewLoaded {
  890. self.navigationController?.pushViewController(vcFavorite, animated: true)
  891. }
  892. } else {
  893. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  894. vcFavorite.serverUrl = serverUrlPush
  895. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  896. appDelegate.listFavoriteVC.setValue(vcFavorite, forKey: serverUrlPush)
  897. self.navigationController?.pushViewController(vcFavorite, animated: true)
  898. }
  899. }
  900. // OFFLINE
  901. if layoutKey == k_layout_view_offline {
  902. if let viewController = appDelegate.listOfflineVC.value(forKey: serverUrlPush) {
  903. guard let vcOffline = (viewController as? NCOffline) else { return }
  904. if vcOffline.isViewLoaded {
  905. self.navigationController?.pushViewController(vcOffline, animated: true)
  906. }
  907. } else {
  908. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  909. vcOffline.serverUrl = serverUrlPush
  910. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  911. appDelegate.listOfflineVC.setValue(vcOffline, forKey: serverUrlPush)
  912. self.navigationController?.pushViewController(vcOffline, animated: true)
  913. }
  914. }
  915. // RECENT ( for push use Files ... he he he )
  916. if layoutKey == k_layout_view_recent {
  917. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  918. guard let vcFiles = (viewController as? NCFiles) else { return }
  919. if vcFiles.isViewLoaded {
  920. self.navigationController?.pushViewController(vcFiles, animated: true)
  921. }
  922. } else {
  923. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  924. vcFiles.isRoot = false
  925. vcFiles.serverUrl = serverUrlPush
  926. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  927. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  928. self.navigationController?.pushViewController(vcFiles, animated: true)
  929. }
  930. }
  931. //VIEW IN FOLDER
  932. if layoutKey == k_layout_view_viewInFolder {
  933. let vcFileViewInFolder:NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  934. vcFileViewInFolder.serverUrl = serverUrlPush
  935. vcFileViewInFolder.titleCurrentFolder = metadataTouch!.fileNameView
  936. self.navigationController?.pushViewController(vcFileViewInFolder, animated: true)
  937. }
  938. // SHARES ( for push use Files ... he he he )
  939. if layoutKey == k_layout_view_shares {
  940. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  941. guard let vcFiles = (viewController as? NCFiles) else { return }
  942. if vcFiles.isViewLoaded {
  943. self.navigationController?.pushViewController(vcFiles, animated: true)
  944. }
  945. } else {
  946. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  947. vcFiles.isRoot = false
  948. vcFiles.serverUrl = serverUrlPush
  949. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  950. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  951. self.navigationController?.pushViewController(vcFiles, animated: true)
  952. }
  953. }
  954. } else {
  955. guard let metadataTouch = metadataTouch else { return }
  956. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isDirectEditing(account: metadata.account, contentType: metadata.contentType) != nil {
  957. if NCCommunication.shared.isNetworkReachable() {
  958. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: [metadataTouch])
  959. } else {
  960. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  961. }
  962. return
  963. }
  964. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isRichDocument(metadata) {
  965. if NCCommunication.shared.isNetworkReachable() {
  966. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: [metadataTouch])
  967. } else {
  968. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  969. }
  970. return
  971. }
  972. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  973. var metadatas: [tableMetadata] = []
  974. for metadata in dataSource.metadatas {
  975. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video || metadata.typeFile == k_metadataTypeFile_audio {
  976. metadatas.append(metadata)
  977. }
  978. }
  979. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: metadatas)
  980. return
  981. }
  982. if CCUtility.fileProviderStorageExists(metadataTouch.ocId, fileNameView: metadataTouch.fileNameView) {
  983. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: [metadataTouch])
  984. } else {
  985. NCNetworking.shared.download(metadata: metadataTouch, selector: selectorLoadFileView) { (_) in }
  986. }
  987. }
  988. }
  989. func collectionViewSelectAll() {
  990. selectOcId.removeAll()
  991. for metadata in metadatasSource {
  992. selectOcId.append(metadata.ocId)
  993. }
  994. collectionView.reloadData()
  995. }
  996. }
  997. extension NCCollectionViewCommon: UICollectionViewDataSource {
  998. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  999. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1000. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  1001. }
  1002. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1003. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1004. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  1005. }
  1006. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1007. if kind == UICollectionView.elementKindSectionHeader {
  1008. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  1009. if collectionView.collectionViewLayout == gridLayout {
  1010. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  1011. } else {
  1012. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  1013. }
  1014. header.delegate = self
  1015. header.setStatusButton(count: dataSource.metadatas.count)
  1016. header.setTitleSorted(datasourceTitleButton: titleButton)
  1017. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  1018. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  1019. return header
  1020. } else {
  1021. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1022. let info = dataSource.getFilesInformation()
  1023. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  1024. return footer
  1025. }
  1026. }
  1027. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1028. return 1
  1029. }
  1030. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1031. let numberItems = dataSource.numberOfItems()
  1032. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1033. return numberItems
  1034. }
  1035. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1036. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  1037. return UICollectionViewCell()
  1038. }
  1039. var tableShare: tableShare?
  1040. var isShare = false
  1041. var isMounted = false
  1042. if metadataFolder != nil {
  1043. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  1044. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  1045. }
  1046. if dataSource.metadataShare[metadata.ocId] != nil {
  1047. tableShare = dataSource.metadataShare[metadata.ocId]
  1048. }
  1049. //
  1050. // LAYOUT LIST
  1051. //
  1052. if layout == k_layout_list {
  1053. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1054. cell.delegate = self
  1055. cell.objectId = metadata.ocId
  1056. cell.indexPath = indexPath
  1057. cell.labelTitle.text = metadata.fileNameView
  1058. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  1059. cell.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  1060. cell.imageSelect.image = nil
  1061. cell.imageStatus.image = nil
  1062. cell.imageLocal.image = nil
  1063. cell.imageFavorite.image = nil
  1064. cell.imageShared.image = nil
  1065. cell.imageMore.image = nil
  1066. cell.imageItem.image = nil
  1067. cell.imageItem.backgroundColor = nil
  1068. cell.progressView.progress = 0.0
  1069. if metadata.directory {
  1070. if metadata.e2eEncrypted {
  1071. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1072. } else if isShare {
  1073. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1074. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1075. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1076. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1077. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1078. } else if metadata.mountType == "group" {
  1079. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1080. } else if isMounted {
  1081. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1082. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1083. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1084. } else {
  1085. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1086. }
  1087. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  1088. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1089. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1090. // Local image: offline
  1091. if tableDirectory != nil && tableDirectory!.offline {
  1092. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1093. }
  1094. } else {
  1095. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1096. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1097. } else {
  1098. if metadata.hasPreview {
  1099. cell.imageItem.backgroundColor = .lightGray
  1100. } else {
  1101. if metadata.iconName.count > 0 {
  1102. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1103. } else {
  1104. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1105. }
  1106. }
  1107. }
  1108. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1109. // image local
  1110. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1111. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1112. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1113. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1114. }
  1115. }
  1116. // image Favorite
  1117. if metadata.favorite {
  1118. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1119. }
  1120. // Share image
  1121. if (isShare) {
  1122. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  1123. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1124. cell.imageShared.image = NCCollectionCommon.images.cellShareByLinkImage
  1125. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1126. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  1127. } else {
  1128. cell.imageShared.image = NCCollectionCommon.images.cellCanShareImage
  1129. }
  1130. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userID {
  1131. // Load avatar
  1132. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  1133. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-avatar-" + metadata.ownerId + ".png"
  1134. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  1135. cell.imageShared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  1136. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  1137. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  1138. } else {
  1139. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  1140. if errorCode == 0 && account == self.appDelegate.account {
  1141. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  1142. }
  1143. }
  1144. }
  1145. }
  1146. // Transfer
  1147. var progress: Float = 0.0
  1148. var totalBytes: Double = 0.0
  1149. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  1150. if progressArray != nil && progressArray?.count == 3 {
  1151. progress = progressArray?.object(at: 0) as? Float ?? 0
  1152. totalBytes = progressArray?.object(at: 1) as? Double ?? 0
  1153. }
  1154. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  1155. cell.progressView.isHidden = false
  1156. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1157. } else {
  1158. cell.progressView.isHidden = true
  1159. cell.progressView.progress = progress
  1160. cell.setButtonMore(named: k_buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1161. }
  1162. // Write status on Label Info
  1163. switch metadata.status {
  1164. case Int(k_metadataStatusWaitDownload):
  1165. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1166. break
  1167. case Int(k_metadataStatusInDownload):
  1168. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1169. break
  1170. case Int(k_metadataStatusDownloading):
  1171. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1172. break
  1173. case Int(k_metadataStatusWaitUpload):
  1174. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1175. break
  1176. case Int(k_metadataStatusInUpload):
  1177. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1178. break
  1179. case Int(k_metadataStatusUploading):
  1180. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1181. break
  1182. default:
  1183. break
  1184. }
  1185. // Live Photo
  1186. if metadata.livePhoto {
  1187. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1188. }
  1189. // E2EE
  1190. if metadata.e2eEncrypted || isEncryptedFolder {
  1191. cell.hideButtonShare(true)
  1192. } else {
  1193. cell.hideButtonShare(false)
  1194. }
  1195. // Remove last separator
  1196. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1197. cell.separator.isHidden = true
  1198. } else {
  1199. cell.separator.isHidden = false
  1200. }
  1201. // Edit mode
  1202. if isEditMode {
  1203. cell.selectMode(true)
  1204. if selectOcId.contains(metadata.ocId) {
  1205. cell.selected(true)
  1206. } else {
  1207. cell.selected(false)
  1208. }
  1209. } else {
  1210. cell.selectMode(false)
  1211. }
  1212. return cell
  1213. }
  1214. //
  1215. // LAYOUT GRID
  1216. //
  1217. if layout == k_layout_grid {
  1218. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1219. cell.delegate = self
  1220. cell.objectId = metadata.ocId
  1221. cell.indexPath = indexPath
  1222. cell.labelTitle.text = metadata.fileNameView
  1223. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  1224. cell.imageSelect.image = nil
  1225. cell.imageStatus.image = nil
  1226. cell.imageLocal.image = nil
  1227. cell.imageFavorite.image = nil
  1228. cell.imageItem.image = nil
  1229. cell.imageItem.backgroundColor = nil
  1230. cell.progressView.progress = 0.0
  1231. if metadata.directory {
  1232. if metadata.e2eEncrypted {
  1233. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1234. } else if isShare {
  1235. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1236. } else if (tableShare != nil && tableShare!.shareType != 3) {
  1237. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1238. } else if (tableShare != nil && tableShare!.shareType == 3) {
  1239. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1240. } else if metadata.mountType == "group" {
  1241. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1242. } else if isMounted {
  1243. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1244. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1245. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1246. } else {
  1247. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1248. }
  1249. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1250. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1251. // Local image: offline
  1252. if tableDirectory != nil && tableDirectory!.offline {
  1253. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1254. }
  1255. } else {
  1256. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1257. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1258. } else {
  1259. if metadata.hasPreview {
  1260. cell.imageItem.backgroundColor = .lightGray
  1261. } else {
  1262. if metadata.iconName.count > 0 {
  1263. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1264. } else {
  1265. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1266. }
  1267. }
  1268. }
  1269. // image Local
  1270. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1271. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1272. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1273. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1274. }
  1275. }
  1276. // image Favorite
  1277. if metadata.favorite {
  1278. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1279. }
  1280. // Transfer
  1281. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  1282. cell.progressView.isHidden = false
  1283. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1284. } else {
  1285. cell.progressView.isHidden = true
  1286. cell.progressView.progress = 0.0
  1287. cell.setButtonMore(named: k_buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1288. }
  1289. // Live Photo
  1290. if metadata.livePhoto {
  1291. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1292. }
  1293. // Edit mode
  1294. if isEditMode {
  1295. cell.selectMode(true)
  1296. if selectOcId.contains(metadata.ocId) {
  1297. cell.selected(true)
  1298. } else {
  1299. cell.selected(false)
  1300. }
  1301. } else {
  1302. cell.selectMode(false)
  1303. }
  1304. return cell
  1305. }
  1306. return UICollectionViewCell()
  1307. }
  1308. }
  1309. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1310. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1311. headerRichWorkspaceHeight = 0
  1312. if let richWorkspaceText = richWorkspaceText {
  1313. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1314. if trimmed.count > 0 && !isSearching {
  1315. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1316. }
  1317. }
  1318. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1319. }
  1320. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1321. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1322. }
  1323. }