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