NCCollectionViewCommon.swift 78 KB

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