NCCollectionViewCommon.swift 82 KB

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