NCCollectionViewCommon.swift 76 KB

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