NCCollectionViewCommon.swift 81 KB

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