NCCollectionViewCommon.swift 78 KB

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