NCCollectionViewCommon.swift 77 KB

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