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