NCCollectionViewCommon.swift 78 KB

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