NCCollectionViewCommon.swift 76 KB

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