NCCollectionViewCommon.swift 79 KB

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