NCCollectionViewCommon.swift 76 KB

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