NCCollectionViewCommon.swift 77 KB

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