NCCollectionViewCommon.swift 84 KB

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