NCCollectionViewCommon.swift 76 KB

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