NCCollectionViewCommon.swift 83 KB

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