NCCollectionViewCommon.swift 83 KB

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