NCCollectionViewCommon.swift 83 KB

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