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