NCCollectionViewCommon.swift 82 KB

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