NCCollectionViewCommon.swift 81 KB

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