NCCollectionViewCommon.swift 78 KB

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