NCCollectionViewCommon.swift 78 KB

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