NCCollectionViewCommon.swift 80 KB

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