NCCollectionViewCommon.swift 75 KB

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