NCCollectionViewCommon.swift 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  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 Realm
  25. import NextcloudKit
  26. import EasyTipView
  27. import JGProgressHUD
  28. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, NCSectionFooterDelegate, UIAdaptivePresentationControllerDelegate, NCEmptyDataSetDelegate, UIContextMenuInteractionDelegate, NCAccountRequestDelegate, NCSelectableNavigationView {
  29. @IBOutlet weak var collectionView: UICollectionView!
  30. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  31. internal let refreshControl = UIRefreshControl()
  32. internal var searchController: UISearchController?
  33. internal var emptyDataSet: NCEmptyDataSet?
  34. internal var backgroundImageView = UIImageView()
  35. internal var serverUrl: String = ""
  36. internal var isDirectoryE2EE = false
  37. internal var isDirectoryE2EETop = false
  38. internal var isEditMode = false
  39. internal var selectOcId: [String] = []
  40. internal var selectIndexPath: [IndexPath] = []
  41. internal var metadataFolder: tableMetadata?
  42. internal var dataSource = NCDataSource()
  43. internal var richWorkspaceText: String?
  44. internal var headerMenu: NCSectionHeaderMenu?
  45. internal var isSearchingMode: Bool = false
  46. internal var layoutForView: NCDBLayoutForView?
  47. internal var selectableDataSource: [RealmSwiftObject] { dataSource.getMetadataSourceForAllSections() }
  48. private var autoUploadFileName = ""
  49. private var autoUploadDirectory = ""
  50. internal var groupByField = "name"
  51. internal var providers: [NKSearchProvider]?
  52. internal var searchResults: [NKSearchResult]?
  53. internal var listLayout: NCListLayout!
  54. internal var gridLayout: NCGridLayout!
  55. internal var literalSearch: String?
  56. internal var isReloadDataSourceNetworkInProgress: Bool = false
  57. private var pushed: Bool = false
  58. private var tipView: EasyTipView?
  59. private var isTransitioning: Bool = false
  60. // DECLARE
  61. internal var layoutKey = ""
  62. internal var titleCurrentFolder = ""
  63. internal var titlePreviusFolder: String?
  64. internal var enableSearchBar: Bool = false
  65. internal var headerMenuTransferView = false
  66. internal var headerMenuButtonsView: Bool = true
  67. internal var headerRichWorkspaceDisable:Bool = false
  68. internal var emptyImage: UIImage?
  69. internal var emptyTitle: String = ""
  70. internal var emptyDescription: String = ""
  71. // MARK: - View Life Cycle
  72. required init?(coder aDecoder: NSCoder) {
  73. super.init(coder: aDecoder)
  74. }
  75. override func viewDidLoad() {
  76. super.viewDidLoad()
  77. self.navigationController?.presentationController?.delegate = self
  78. // CollectionView & layout
  79. collectionView.alwaysBounceVertical = true
  80. listLayout = NCListLayout()
  81. gridLayout = NCGridLayout()
  82. // Color
  83. view.backgroundColor = .systemBackground
  84. collectionView.backgroundColor = .systemBackground
  85. refreshControl.tintColor = .gray
  86. if enableSearchBar {
  87. searchController = UISearchController(searchResultsController: nil)
  88. searchController?.searchResultsUpdater = self
  89. searchController?.obscuresBackgroundDuringPresentation = false
  90. searchController?.delegate = self
  91. searchController?.searchBar.delegate = self
  92. searchController?.searchBar.autocapitalizationType = .none
  93. navigationItem.searchController = searchController
  94. navigationItem.hidesSearchBarWhenScrolling = true
  95. }
  96. // Cell
  97. collectionView.register(UINib(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  98. collectionView.register(UINib(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  99. collectionView.register(UINib(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  100. // Header
  101. collectionView.register(UINib(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  102. collectionView.register(UINib(nibName: "NCSectionHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeader")
  103. // Footer
  104. collectionView.register(UINib(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  105. // Refresh Control
  106. collectionView.refreshControl = refreshControl
  107. refreshControl.action(for: .valueChanged) { _ in
  108. self.dataSource.clearDirectory()
  109. self.reloadDataSourceNetwork(isForced: true)
  110. }
  111. // Empty
  112. emptyDataSet = NCEmptyDataSet(view: collectionView, offset: getHeaderHeight(), delegate: self)
  113. // Long Press on CollectionView
  114. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  115. longPressedGesture.minimumPressDuration = 0.5
  116. longPressedGesture.delegate = self
  117. longPressedGesture.delaysTouchesBegan = true
  118. collectionView.addGestureRecognizer(longPressedGesture)
  119. // TIP
  120. var preferences = EasyTipView.Preferences()
  121. preferences.drawing.foregroundColor = .white
  122. preferences.drawing.backgroundColor = NCBrandColor.shared.nextcloud
  123. preferences.drawing.textAlignment = .left
  124. preferences.drawing.arrowPosition = .top
  125. preferences.drawing.cornerRadius = 10
  126. preferences.animating.dismissTransform = CGAffineTransform(translationX: 0, y: 100)
  127. preferences.animating.showInitialTransform = CGAffineTransform(translationX: 0, y: -100)
  128. preferences.animating.showInitialAlpha = 0
  129. preferences.animating.showDuration = 1.5
  130. preferences.animating.dismissDuration = 1.5
  131. tipView = EasyTipView(text: NSLocalizedString("_tip_accountrequest_", comment: ""), preferences: preferences, delegate: self)
  132. // Notification
  133. NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
  134. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeTheming), object: nil)
  135. }
  136. override func viewWillAppear(_ animated: Bool) {
  137. super.viewWillAppear(animated)
  138. appDelegate.activeViewController = self
  139. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  140. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  141. if layoutForView?.layout == NCGlobal.shared.layoutList {
  142. collectionView?.collectionViewLayout = listLayout
  143. } else {
  144. collectionView?.collectionViewLayout = gridLayout
  145. }
  146. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  147. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  148. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  149. NotificationCenter.default.addObserver(self, selector: #selector(setNavigationItem), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  150. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  151. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetwork), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetwork), object: nil)
  152. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  153. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  154. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  155. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  156. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  157. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  158. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterFavoriteFile), object: nil)
  159. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadStartFile), object: nil)
  160. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadedFile), object: nil)
  161. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDownloadCancelFile), object: nil)
  162. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadStartFile), object: nil)
  163. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadedFile), object: nil)
  164. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterUploadCancelFile), object: nil)
  165. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  166. if serverUrl == "" {
  167. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  168. } else {
  169. appDelegate.activeServerUrl = serverUrl
  170. }
  171. navigationController?.navigationBar.prefersLargeTitles = true
  172. navigationController?.setNavigationBarHidden(false, animated: true)
  173. setNavigationItem()
  174. reloadDataSource(isForced: false)
  175. if !isSearchingMode {
  176. reloadDataSourceNetwork()
  177. }
  178. //FIXME: iPAD PDF landscape mode iOS 16
  179. DispatchQueue.main.async {
  180. self.collectionView?.collectionViewLayout.invalidateLayout()
  181. }
  182. }
  183. override func viewDidAppear(_ animated: Bool) {
  184. super.viewDidAppear(animated)
  185. showTip()
  186. }
  187. override func viewWillDisappear(_ animated: Bool) {
  188. super.viewWillDisappear(animated)
  189. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationWillResignActive), object: nil)
  190. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCloseRichWorkspaceWebView), object: nil)
  191. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterChangeStatusFolderE2EE), object: nil)
  192. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadAvatar), object: nil)
  193. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSource), object: nil)
  194. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetwork), object: nil)
  195. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterReloadDataSourceNetworkForced), object: nil)
  196. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterDeleteFile), object: nil)
  197. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterMoveFile), object: nil)
  198. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCopyFile), object: nil)
  199. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterRenameFile), object: nil)
  200. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterCreateFolder), object: nil)
  201. NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterProgressTask), object: nil)
  202. pushed = false
  203. // REQUEST
  204. NCNetworking.shared.cancelUnifiedSearchFiles()
  205. // TIP
  206. self.tipView?.dismiss()
  207. }
  208. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  209. let viewController = presentationController.presentedViewController
  210. if viewController is NCViewerRichWorkspaceWebView {
  211. closeRichWorkspaceWebView()
  212. }
  213. }
  214. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  215. super.viewWillTransition(to: size, with: coordinator)
  216. self.collectionView?.collectionViewLayout.invalidateLayout()
  217. self.collectionView?.reloadData()
  218. self.tipView?.dismiss()
  219. coordinator.animate(alongsideTransition: nil) { _ in
  220. self.showTip()
  221. }
  222. }
  223. override var canBecomeFirstResponder: Bool {
  224. return true
  225. }
  226. // MARK: - NotificationCenter
  227. @objc func initialize() {
  228. guard !appDelegate.account.isEmpty else { return }
  229. // Search
  230. if searchController?.isActive ?? false || isSearchingMode {
  231. searchController?.isActive = false
  232. isSearchingMode = false
  233. }
  234. // Select
  235. if isEditMode {
  236. isEditMode = !isEditMode
  237. selectOcId.removeAll()
  238. selectIndexPath.removeAll()
  239. }
  240. if self.view?.window != nil {
  241. if serverUrl == "" {
  242. appDelegate.activeServerUrl = NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId)
  243. } else {
  244. appDelegate.activeServerUrl = serverUrl
  245. }
  246. appDelegate.listFilesVC.removeAll()
  247. appDelegate.listFavoriteVC.removeAll()
  248. appDelegate.listOfflineVC.removeAll()
  249. }
  250. if serverUrl != "" {
  251. self.navigationController?.popToRootViewController(animated: false)
  252. }
  253. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  254. gridLayout.itemForLine = CGFloat(layoutForView?.itemForLine ?? 3)
  255. if layoutForView?.layout == NCGlobal.shared.layoutList {
  256. collectionView?.collectionViewLayout = listLayout
  257. } else {
  258. collectionView?.collectionViewLayout = gridLayout
  259. }
  260. setNavigationItem()
  261. }
  262. @objc func applicationWillResignActive(_ notification: NSNotification) {
  263. self.refreshControl.endRefreshing()
  264. }
  265. @objc func changeTheming() {
  266. collectionView.reloadData()
  267. }
  268. @objc func reloadDataSource(_ notification: NSNotification) {
  269. reloadDataSource()
  270. }
  271. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  272. if !isSearchingMode {
  273. reloadDataSourceNetwork(isForced: 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. guard let userInfo = notification.userInfo as NSDictionary?,
  284. let error = userInfo["error"] as? NKError else { return }
  285. let onlyLocalCache: Bool = userInfo["onlyLocalCache"] as? Bool ?? false
  286. self.queryDB(isForced: true)
  287. if error == .success, let indexPath = userInfo["indexPath"] as? [IndexPath], !indexPath.isEmpty, !onlyLocalCache {
  288. collectionView?.performBatchUpdates({
  289. collectionView?.deleteItems(at: indexPath)
  290. }, completion: { _ in
  291. self.collectionView?.reloadData()
  292. })
  293. } else {
  294. if error != .success {
  295. NCContentPresenter.shared.showError(error: error)
  296. }
  297. self.collectionView?.reloadData()
  298. }
  299. if let hud = userInfo["hud"] as? JGProgressHUD {
  300. hud.dismiss()
  301. }
  302. }
  303. @objc func moveFile(_ notification: NSNotification) {
  304. deleteFile(notification)
  305. }
  306. @objc func copyFile(_ notification: NSNotification) {
  307. guard let userInfo = notification.userInfo as NSDictionary? else { return }
  308. if let hud = userInfo["hud"] as? JGProgressHUD {
  309. hud.dismiss()
  310. }
  311. }
  312. @objc func renameFile(_ notification: NSNotification) {
  313. guard let userInfo = notification.userInfo as NSDictionary?,
  314. let account = userInfo["account"] as? String,
  315. account == appDelegate.account
  316. else { return }
  317. if isSearchingMode {
  318. reloadDataSourceNetwork()
  319. } else {
  320. reloadDataSource()
  321. }
  322. }
  323. @objc func createFolder(_ notification: NSNotification) {
  324. guard let userInfo = notification.userInfo as NSDictionary?,
  325. let ocId = userInfo["ocId"] as? String,
  326. let serverUrl = userInfo["serverUrl"] as? String,
  327. serverUrl == self.serverUrl,
  328. let account = userInfo["account"] as? String,
  329. account == appDelegate.account,
  330. let e2ee = userInfo["e2ee"] as? Bool,
  331. let withPush = userInfo["withPush"] as? Bool
  332. else { return }
  333. if e2ee {
  334. reloadDataSourceNetwork(isForced: true)
  335. } else if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  336. reloadDataSource()
  337. if withPush {
  338. pushMetadata(metadata)
  339. }
  340. }
  341. }
  342. @objc func favoriteFile(_ notification: NSNotification) {
  343. guard let userInfo = notification.userInfo as NSDictionary?,
  344. let ocId = userInfo["ocId"] as? String,
  345. let serverUrl = userInfo["serverUrl"] as? String,
  346. serverUrl == self.serverUrl
  347. else {
  348. if self is NCFavorite {
  349. reloadDataSource()
  350. }
  351. return
  352. }
  353. dataSource.reloadMetadata(ocId: ocId)
  354. collectionView?.reloadData()
  355. }
  356. @objc func downloadStartFile(_ notification: NSNotification) {
  357. guard let userInfo = notification.userInfo as NSDictionary?,
  358. let serverUrl = userInfo["serverUrl"] as? String,
  359. serverUrl == self.serverUrl,
  360. let account = userInfo["account"] as? String,
  361. account == appDelegate.account
  362. else { return }
  363. reloadDataSource()
  364. }
  365. @objc func downloadedFile(_ notification: NSNotification) {
  366. guard let userInfo = notification.userInfo as NSDictionary?,
  367. let serverUrl = userInfo["serverUrl"] as? String,
  368. serverUrl == self.serverUrl,
  369. let account = userInfo["account"] as? String,
  370. account == appDelegate.account
  371. else { return }
  372. reloadDataSource()
  373. }
  374. @objc func downloadCancelFile(_ notification: NSNotification) {
  375. guard let userInfo = notification.userInfo as NSDictionary?,
  376. let ocId = userInfo["ocId"] as? String,
  377. let serverUrl = userInfo["serverUrl"] as? String,
  378. serverUrl == self.serverUrl,
  379. let account = userInfo["account"] as? String,
  380. account == appDelegate.account
  381. else { return }
  382. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  383. if let indexPath = indexPath {
  384. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  385. collectionView?.reloadItems(at: [indexPath])
  386. } else {
  387. self.collectionView?.reloadData()
  388. }
  389. } else {
  390. reloadDataSource()
  391. }
  392. }
  393. @objc func uploadStartFile(_ notification: NSNotification) {
  394. guard let userInfo = notification.userInfo as NSDictionary?,
  395. let ocId = userInfo["ocId"] as? String,
  396. let serverUrl = userInfo["serverUrl"] as? String,
  397. let account = userInfo["account"] as? String
  398. else { return }
  399. guard !isSearchingMode, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
  400. // Header view trasfer
  401. if metadata.isTransferInForeground {
  402. NCNetworking.shared.transferInForegorund = NCNetworking.TransferInForegorund(ocId: ocId, progress: 0)
  403. self.collectionView?.reloadData()
  404. }
  405. if serverUrl == self.serverUrl, account == appDelegate.account {
  406. reloadDataSource()
  407. }
  408. }
  409. @objc func uploadedFile(_ notification: NSNotification) {
  410. guard let userInfo = notification.userInfo as NSDictionary?,
  411. let ocId = userInfo["ocId"] as? String,
  412. let ocIdTemp = userInfo["ocIdTemp"] as? String,
  413. let serverUrl = userInfo["serverUrl"] as? String,
  414. let account = userInfo["account"] as? String
  415. else { return }
  416. if ocIdTemp == NCNetworking.shared.transferInForegorund?.ocId {
  417. NCNetworking.shared.transferInForegorund = nil
  418. self.collectionView?.reloadData()
  419. }
  420. if account == appDelegate.account, serverUrl == self.serverUrl, let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  421. if metadata.e2eEncrypted {
  422. reloadDataSourceNetwork(isForced: true)
  423. } else {
  424. reloadDataSource()
  425. }
  426. }
  427. }
  428. @objc func uploadCancelFile(_ notification: NSNotification) {
  429. guard let userInfo = notification.userInfo as NSDictionary?,
  430. let ocId = userInfo["ocId"] as? String,
  431. let serverUrl = userInfo["serverUrl"] as? String,
  432. let account = userInfo["account"] as? String
  433. else { return }
  434. if ocId == NCNetworking.shared.transferInForegorund?.ocId {
  435. NCNetworking.shared.transferInForegorund = nil
  436. self.collectionView?.reloadData()
  437. }
  438. if account == appDelegate.account, serverUrl == self.serverUrl {
  439. reloadDataSource()
  440. }
  441. }
  442. @objc func triggerProgressTask(_ notification: NSNotification) {
  443. guard let userInfo = notification.userInfo as NSDictionary?,
  444. let progressNumber = userInfo["progress"] as? NSNumber,
  445. let totalBytes = userInfo["totalBytes"] as? Int64,
  446. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64,
  447. let ocId = userInfo["ocId"] as? String
  448. else { return }
  449. let chunk: Int = userInfo["chunk"] as? Int ?? 0
  450. let e2eEncrypted: Bool = userInfo["e2eEncrypted"] as? Bool ?? false
  451. // Header Transfer
  452. if headerMenuTransferView && (chunk > 0 || e2eEncrypted) {
  453. if NCNetworking.shared.transferInForegorund?.ocId == ocId {
  454. NCNetworking.shared.transferInForegorund?.progress = progressNumber.floatValue
  455. } else {
  456. NCNetworking.shared.transferInForegorund = NCNetworking.TransferInForegorund(ocId: ocId, progress: progressNumber.floatValue)
  457. collectionView.reloadData()
  458. }
  459. self.headerMenu?.progressTransfer.progress = progressNumber.floatValue
  460. }
  461. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  462. if let (indexPath, _) = self.dataSource.getIndexPathMetadata(ocId: ocId) as? (IndexPath, NCMetadataForSection?),
  463. let cell = collectionView?.cellForItem(at: indexPath) {
  464. if let cell = cell as? NCCellProtocol {
  465. if progressNumber.floatValue == 1 && !(cell is NCTransferCell) {
  466. cell.fileProgressView?.isHidden = true
  467. cell.fileProgressView?.progress = .zero
  468. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  469. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  470. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  471. } else {
  472. cell.fileInfoLabel?.text = ""
  473. }
  474. } else {
  475. cell.fileProgressView?.isHidden = false
  476. cell.fileProgressView?.progress = progressNumber.floatValue
  477. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  478. if status == NCGlobal.shared.metadataStatusInDownload {
  479. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  480. } else if status == NCGlobal.shared.metadataStatusInUpload {
  481. if totalBytes > 0 {
  482. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  483. } else {
  484. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ …"
  485. }
  486. }
  487. }
  488. }
  489. }
  490. }
  491. // MARK: - Tip
  492. func showTip() {
  493. if self is NCFiles, self.view.window != nil, !NCBrandOptions.shared.disable_multiaccount, !NCBrandOptions.shared.disable_manage_account, self.serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId), let view = self.navigationItem.leftBarButtonItem?.customView {
  494. if !NCManageDatabase.shared.tipExists(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest), NCManageDatabase.shared.getAllAccountOrderAlias().count > 0 {
  495. self.tipView?.show(forView: view)
  496. }
  497. }
  498. }
  499. // MARK: - Layout
  500. @objc func setNavigationItem() {
  501. self.setNavigationRightItems()
  502. navigationItem.title = titleCurrentFolder
  503. guard layoutKey == NCGlobal.shared.layoutViewFiles else { return }
  504. // PROFILE BUTTON
  505. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  506. let image = NCUtility.shared.loadUserImage(
  507. for: appDelegate.user,
  508. displayName: activeAccount?.displayName,
  509. userBaseUrl: appDelegate)
  510. let button = UIButton(type: .custom)
  511. button.setImage(image, for: .normal)
  512. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) {
  513. var titleButton = " "
  514. if getNavigationTitle() == activeAccount?.alias {
  515. titleButton = ""
  516. } else {
  517. titleButton += activeAccount?.displayName ?? ""
  518. }
  519. button.setTitle(titleButton, for: .normal)
  520. button.setTitleColor(.systemBlue, for: .normal)
  521. }
  522. button.semanticContentAttribute = .forceLeftToRight
  523. button.sizeToFit()
  524. button.action(for: .touchUpInside) { _ in
  525. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  526. if accounts.count > 0 && !NCBrandOptions.shared.disable_multiaccount && !NCBrandOptions.shared.disable_manage_account {
  527. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  528. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  529. vcAccountRequest.accounts = accounts
  530. vcAccountRequest.enableTimerProgress = false
  531. vcAccountRequest.enableAddAccount = true
  532. vcAccountRequest.delegate = self
  533. vcAccountRequest.dismissDidEnterBackground = true
  534. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  535. let numberCell = accounts.count + 1
  536. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  537. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height)
  538. self.present(popup, animated: true)
  539. }
  540. // TIP
  541. self.dismissTip()
  542. }
  543. }
  544. navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true)
  545. navigationItem.leftItemsSupplementBackButton = true
  546. if titlePreviusFolder == nil {
  547. navigationController?.navigationBar.topItem?.title = getNavigationTitle()
  548. } else {
  549. navigationController?.navigationBar.topItem?.title = titlePreviusFolder
  550. }
  551. navigationItem.title = titleCurrentFolder
  552. }
  553. func getNavigationTitle() -> String {
  554. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  555. guard let userAlias = activeAccount?.alias, !userAlias.isEmpty else {
  556. return NCBrandOptions.shared.brand
  557. }
  558. return userAlias
  559. }
  560. // MARK: - Empty
  561. func emptyDataSetView(_ view: NCEmptyView) {
  562. self.emptyDataSet?.setOffset(getHeaderHeight())
  563. if isSearchingMode {
  564. view.emptyImage.image = UIImage(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  565. if isReloadDataSourceNetworkInProgress {
  566. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  567. } else {
  568. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  569. }
  570. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  571. } else if isReloadDataSourceNetworkInProgress {
  572. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  573. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  574. view.emptyDescription.text = ""
  575. } else {
  576. if serverUrl == "" {
  577. view.emptyImage.image = emptyImage
  578. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  579. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  580. } else {
  581. view.emptyImage.image = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  582. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  583. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  584. }
  585. }
  586. }
  587. // MARK: - SEARCH
  588. func updateSearchResults(for searchController: UISearchController) {
  589. self.literalSearch = searchController.searchBar.text
  590. }
  591. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  592. isSearchingMode = true
  593. self.providers?.removeAll()
  594. self.dataSource.clearDataSource()
  595. self.collectionView.reloadData()
  596. // TIP
  597. self.tipView?.dismiss()
  598. }
  599. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  600. if isSearchingMode && self.literalSearch?.count ?? 0 >= 2 {
  601. reloadDataSourceNetwork()
  602. }
  603. }
  604. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  605. DispatchQueue.global().async {
  606. NCNetworking.shared.cancelUnifiedSearchFiles()
  607. self.isSearchingMode = false
  608. self.literalSearch = ""
  609. self.providers?.removeAll()
  610. self.dataSource.clearDataSource()
  611. self.reloadDataSource()
  612. }
  613. }
  614. // MARK: - TAP EVENT
  615. func accountRequestChangeAccount(account: String) {
  616. NCManageDatabase.shared.setAccountActive(account)
  617. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  618. NCOperationQueue.shared.cancelAllQueue()
  619. NCNetworking.shared.cancelAllTask()
  620. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  621. }
  622. }
  623. func accountRequestAddAccount() {
  624. appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  625. }
  626. func tapButtonSwitch(_ sender: Any) {
  627. guard isTransitioning == false else { return }
  628. isTransitioning = true
  629. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  630. // list layout
  631. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  632. layoutForView?.layout = NCGlobal.shared.layoutList
  633. NCManageDatabase.shared.setLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  634. self.groupByField = "name"
  635. if self.dataSource.groupByField != self.groupByField {
  636. self.dataSource.changeGroupByField(self.groupByField)
  637. }
  638. self.collectionView.reloadData()
  639. self.collectionView.collectionViewLayout.invalidateLayout()
  640. self.collectionView.setCollectionViewLayout(self.listLayout, animated: true) {_ in self.isTransitioning = false }
  641. } else {
  642. // grid layout
  643. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  644. layoutForView?.layout = NCGlobal.shared.layoutGrid
  645. NCManageDatabase.shared.setLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  646. if isSearchingMode {
  647. self.groupByField = "name"
  648. } else {
  649. self.groupByField = "classFile"
  650. }
  651. if self.dataSource.groupByField != self.groupByField {
  652. self.dataSource.changeGroupByField(self.groupByField)
  653. }
  654. self.collectionView.reloadData()
  655. self.collectionView.collectionViewLayout.invalidateLayout()
  656. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: true) {_ in self.isTransitioning = false }
  657. }
  658. }
  659. func tapButtonOrder(_ sender: Any) {
  660. let sortMenu = NCSortMenu()
  661. sortMenu.toggleMenu(viewController: self, account: appDelegate.account, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  662. }
  663. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, indexPath: IndexPath, sender: Any) {
  664. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, indexPath: indexPath, sender: sender)
  665. }
  666. func tapShareListItem(with objectId: String, indexPath: IndexPath, sender: Any) {
  667. if isEditMode { return }
  668. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  669. NCActionCenter.shared.openShare(viewController: self, metadata: metadata, page: .sharing)
  670. }
  671. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, indexPath: IndexPath, sender: Any) {
  672. if isEditMode { return }
  673. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  674. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  675. toggleMenu(metadata: metadata, indexPath: indexPath, imageIcon: image)
  676. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  677. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  678. }
  679. }
  680. func tapRichWorkspace(_ sender: Any) {
  681. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  682. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  683. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  684. viewerRichWorkspace.serverUrl = serverUrl
  685. viewerRichWorkspace.delegate = self
  686. navigationController.modalPresentationStyle = .fullScreen
  687. self.present(navigationController, animated: true, completion: nil)
  688. }
  689. }
  690. }
  691. func tapButtonSection(_ sender: Any, metadataForSection: NCMetadataForSection?) {
  692. unifiedSearchMore(metadataForSection: metadataForSection)
  693. }
  694. func tapButtonTransfer(_ sender: Any) {
  695. if let ocId = NCNetworking.shared.transferInForegorund?.ocId,
  696. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  697. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  698. }
  699. }
  700. func longPressListItem(with objectId: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  701. }
  702. func longPressGridItem(with objectId: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  703. }
  704. func longPressMoreListItem(with objectId: String, namedButtonMore: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  705. }
  706. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, indexPath: IndexPath, gestureRecognizer: UILongPressGestureRecognizer) {
  707. }
  708. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  709. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  710. }
  711. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  712. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  713. return nil
  714. }, actionProvider: { _ in
  715. return nil
  716. })
  717. }
  718. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  719. if gestureRecognizer.state != .began { return }
  720. var listMenuItems: [UIMenuItem] = []
  721. let touchPoint = gestureRecognizer.location(in: collectionView)
  722. becomeFirstResponder()
  723. if serverUrl != "" {
  724. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  725. }
  726. if listMenuItems.count > 0 {
  727. UIMenuController.shared.menuItems = listMenuItems
  728. UIMenuController.shared.showMenu(from: collectionView, rect: CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0))
  729. }
  730. }
  731. // MARK: - Menu Item
  732. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  733. if #selector(pasteFilesMenu) == action {
  734. if !UIPasteboard.general.items.isEmpty, !(metadataFolder?.e2eEncrypted ?? false) {
  735. return true
  736. }
  737. }
  738. return false
  739. }
  740. @objc func pasteFilesMenu() {
  741. NCActionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  742. }
  743. // MARK: - DataSource + NC Endpoint
  744. func queryDB(isForced: Bool) { }
  745. @objc func reloadDataSource(isForced: Bool = true) {
  746. guard !appDelegate.account.isEmpty else { return }
  747. // E2EE
  748. isDirectoryE2EE = NCUtility.shared.isDirectoryE2EE(serverUrl: serverUrl, userBase: appDelegate)
  749. isDirectoryE2EETop = NCUtility.shared.isDirectoryE2EETop(account: appDelegate.account, serverUrl: serverUrl)
  750. // get auto upload folder
  751. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  752. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)
  753. // get layout for view
  754. layoutForView = NCManageDatabase.shared.getLayoutForView(account: appDelegate.account, key: layoutKey, serverUrl: serverUrl)
  755. // set GroupField for Grid
  756. if !isSearchingMode && layoutForView?.layout == NCGlobal.shared.layoutGrid {
  757. groupByField = "classFile"
  758. } else {
  759. groupByField = "name"
  760. }
  761. }
  762. @objc func reloadDataSourceNetwork(isForced: Bool = false) { }
  763. @objc func networkSearch() {
  764. guard !appDelegate.account.isEmpty, let literalSearch = literalSearch, !literalSearch.isEmpty
  765. else {
  766. self.refreshControl.endRefreshing()
  767. return
  768. }
  769. isReloadDataSourceNetworkInProgress = true
  770. self.dataSource.clearDataSource()
  771. self.refreshControl.beginRefreshing()
  772. self.collectionView.reloadData()
  773. if NCGlobal.shared.capabilityServerVersionMajor >= NCGlobal.shared.nextcloudVersion20 {
  774. NCNetworking.shared.unifiedSearchFiles(userBaseUrl: appDelegate, literal: literalSearch) { account, searchProviders in
  775. self.providers = searchProviders
  776. self.searchResults = []
  777. self.dataSource = NCDataSource(
  778. metadatas: [] ,
  779. account: self.appDelegate.account,
  780. sort: self.layoutForView?.sort,
  781. ascending: self.layoutForView?.ascending,
  782. directoryOnTop: self.layoutForView?.directoryOnTop,
  783. favoriteOnTop: true,
  784. filterLivePhoto: true,
  785. providers: self.providers,
  786. searchResults: self.searchResults)
  787. } update: { account, id, searchResult, metadatas in
  788. guard let metadatas = metadatas, metadatas.count > 0, self.isSearchingMode , let searchResult = searchResult else { return }
  789. NCOperationQueue.shared.unifiedSearchAddSection(collectionViewCommon: self, metadatas: metadatas, searchResult: searchResult)
  790. } completion: { account, error in
  791. self.refreshControl.endRefreshing()
  792. self.isReloadDataSourceNetworkInProgress = false
  793. self.collectionView.reloadData()
  794. }
  795. } else {
  796. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch) { metadatas, error in
  797. DispatchQueue.main.async {
  798. self.refreshControl.endRefreshing()
  799. self.collectionView.reloadData()
  800. }
  801. guard let metadatas = metadatas, error == .success, self.isSearchingMode else { return }
  802. self.dataSource = NCDataSource(
  803. metadatas: metadatas,
  804. account: self.appDelegate.account,
  805. sort: self.layoutForView?.sort,
  806. ascending: self.layoutForView?.ascending,
  807. directoryOnTop: self.layoutForView?.directoryOnTop,
  808. favoriteOnTop: true,
  809. filterLivePhoto: true,
  810. groupByField: self.groupByField,
  811. providers: self.providers,
  812. searchResults: self.searchResults)
  813. self.isReloadDataSourceNetworkInProgress = false
  814. }
  815. }
  816. }
  817. func unifiedSearchMore(metadataForSection: NCMetadataForSection?) {
  818. guard let metadataForSection = metadataForSection, let lastSearchResult = metadataForSection.lastSearchResult, let cursor = lastSearchResult.cursor, let term = literalSearch else { return }
  819. metadataForSection.unifiedSearchInProgress = true
  820. self.collectionView?.reloadData()
  821. NCNetworking.shared.unifiedSearchFilesProvider(userBaseUrl: appDelegate, id: lastSearchResult.id, term: term, limit: 5, cursor: cursor) { account, searchResult, metadatas, error in
  822. if error != .success {
  823. NCContentPresenter.shared.showError(error: error)
  824. }
  825. metadataForSection.unifiedSearchInProgress = false
  826. guard let searchResult = searchResult, let metadatas = metadatas else { return }
  827. self.dataSource.appendMetadatasToSection(metadatas, metadataForSection: metadataForSection, lastSearchResult: searchResult)
  828. DispatchQueue.main.async {
  829. self.collectionView?.reloadData()
  830. }
  831. }
  832. }
  833. @objc func networkReadFolder(isForced: Bool, completion: @escaping(_ tableDirectory: tableDirectory?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasDelete: [tableMetadata]?, _ error: NKError) -> Void) {
  834. var tableDirectory: tableDirectory?
  835. NCNetworking.shared.readFile(serverUrlFileName: serverUrl) { (account, metadataFolder, error) in
  836. guard error == .success else {
  837. completion(nil, nil, nil, nil, error)
  838. return
  839. }
  840. if let metadataFolder = metadataFolder {
  841. tableDirectory = NCManageDatabase.shared.setDirectory(serverUrl: self.serverUrl, richWorkspace: metadataFolder.richWorkspace, account: account)
  842. }
  843. if isForced || tableDirectory?.etag != metadataFolder?.etag || metadataFolder?.e2eEncrypted ?? false {
  844. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { account, metadataFolder, metadatas, metadatasUpdate, _, metadatasDelete, error in
  845. guard error == .success else {
  846. completion(tableDirectory, nil, nil, nil, error)
  847. return
  848. }
  849. self.metadataFolder = metadataFolder
  850. // E2EE
  851. if let metadataFolder = metadataFolder, metadataFolder.e2eEncrypted, CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  852. NextcloudKit.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { account, e2eMetadata, signature, data, error in
  853. if error == .success, let e2eMetadata = e2eMetadata {
  854. let error = NCEndToEndMetadata().decoderMetadata(e2eMetadata, signature: signature, serverUrl: self.serverUrl, account: self.appDelegate.account, urlBase: self.appDelegate.urlBase, userId: self.appDelegate.userId, ownerId: metadataFolder.ownerId)
  855. if error == .success {
  856. self.reloadDataSource()
  857. } else {
  858. NCContentPresenter.shared.showError(error: error)
  859. }
  860. } else if error.errorCode != NCGlobal.shared.errorResourceNotFound {
  861. NCContentPresenter.shared.showError(error: NKError(errorCode: NCGlobal.shared.errorDecodeMetadata, errorDescription: "_e2e_error_decode_metadata_"))
  862. }
  863. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, error)
  864. }
  865. } else {
  866. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, error)
  867. }
  868. }
  869. } else {
  870. completion(tableDirectory, nil, nil, nil, NKError())
  871. }
  872. }
  873. }
  874. // MARK: - Push metadata
  875. func pushMetadata(_ metadata: tableMetadata) {
  876. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  877. appDelegate.activeMetadata = metadata
  878. // FILES
  879. if layoutKey == NCGlobal.shared.layoutViewFiles && !pushed {
  880. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  881. if viewController.isViewLoaded {
  882. pushViewController(viewController: viewController)
  883. }
  884. } else {
  885. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  886. viewController.isRoot = false
  887. viewController.serverUrl = serverUrlPush
  888. viewController.titlePreviusFolder = navigationItem.title
  889. viewController.titleCurrentFolder = metadata.fileNameView
  890. appDelegate.listFilesVC[serverUrlPush] = viewController
  891. pushViewController(viewController: viewController)
  892. }
  893. }
  894. }
  895. // FAVORITE
  896. if layoutKey == NCGlobal.shared.layoutViewFavorite && !pushed {
  897. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  898. if viewController.isViewLoaded {
  899. pushViewController(viewController: viewController)
  900. }
  901. } else {
  902. if let viewController: NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as? NCFavorite {
  903. viewController.serverUrl = serverUrlPush
  904. viewController.titlePreviusFolder = navigationItem.title
  905. viewController.titleCurrentFolder = metadata.fileNameView
  906. appDelegate.listFavoriteVC[serverUrlPush] = viewController
  907. pushViewController(viewController: viewController)
  908. }
  909. }
  910. }
  911. // OFFLINE
  912. if layoutKey == NCGlobal.shared.layoutViewOffline && !pushed {
  913. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  914. if viewController.isViewLoaded {
  915. pushViewController(viewController: viewController)
  916. }
  917. } else {
  918. if let viewController: NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as? NCOffline {
  919. viewController.serverUrl = serverUrlPush
  920. viewController.titlePreviusFolder = navigationItem.title
  921. viewController.titleCurrentFolder = metadata.fileNameView
  922. appDelegate.listOfflineVC[serverUrlPush] = viewController
  923. pushViewController(viewController: viewController)
  924. }
  925. }
  926. }
  927. // RECENT ( for push use Files ... he he he )
  928. if layoutKey == NCGlobal.shared.layoutViewRecent && !pushed {
  929. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  930. if viewController.isViewLoaded {
  931. pushViewController(viewController: viewController)
  932. }
  933. } else {
  934. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  935. viewController.isRoot = false
  936. viewController.serverUrl = serverUrlPush
  937. viewController.titlePreviusFolder = navigationItem.title
  938. viewController.titleCurrentFolder = metadata.fileNameView
  939. appDelegate.listFilesVC[serverUrlPush] = viewController
  940. pushViewController(viewController: viewController)
  941. }
  942. }
  943. }
  944. // SHARES ( for push use Files ... he he he )
  945. if layoutKey == NCGlobal.shared.layoutViewShares && !pushed {
  946. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  947. if viewController.isViewLoaded {
  948. pushViewController(viewController: viewController)
  949. }
  950. } else {
  951. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  952. viewController.isRoot = false
  953. viewController.serverUrl = serverUrlPush
  954. viewController.titlePreviusFolder = navigationItem.title
  955. viewController.titleCurrentFolder = metadata.fileNameView
  956. appDelegate.listFilesVC[serverUrlPush] = viewController
  957. pushViewController(viewController: viewController)
  958. }
  959. }
  960. }
  961. // GROUPFOLDERS
  962. if layoutKey == NCGlobal.shared.layoutViewGroupfolders && !pushed {
  963. if let viewController = appDelegate.listGroupfoldersVC[serverUrlPush] {
  964. if viewController.isViewLoaded {
  965. pushViewController(viewController: viewController)
  966. }
  967. } else {
  968. if let viewController: NCGroupfolders = UIStoryboard(name: "NCGroupfolders", bundle: nil).instantiateInitialViewController() as? NCGroupfolders {
  969. viewController.serverUrl = serverUrlPush
  970. viewController.titlePreviusFolder = navigationItem.title
  971. viewController.titleCurrentFolder = metadata.fileNameView
  972. appDelegate.listGroupfoldersVC[serverUrlPush] = viewController
  973. pushViewController(viewController: viewController)
  974. }
  975. }
  976. }
  977. }
  978. }
  979. // MARK: - E2EE
  980. extension NCCollectionViewCommon: NCEndToEndInitializeDelegate {
  981. func endToEndInitializeSuccess() {
  982. if let metadata = appDelegate.activeMetadata {
  983. pushMetadata(metadata)
  984. }
  985. }
  986. }
  987. // MARK: - Collection View
  988. extension NCCollectionViewCommon: UICollectionViewDelegate {
  989. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  990. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  991. appDelegate.activeMetadata = metadata
  992. let metadataSourceForAllSections = dataSource.getMetadataSourceForAllSections()
  993. if isEditMode {
  994. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  995. selectOcId.remove(at: index)
  996. selectIndexPath.removeAll(where: { $0 == indexPath })
  997. } else {
  998. selectOcId.append(metadata.ocId)
  999. selectIndexPath.append(indexPath)
  1000. }
  1001. collectionView.reloadItems(at: [indexPath])
  1002. return
  1003. }
  1004. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  1005. let e2ee = NCEndToEndInitialize()
  1006. e2ee.delegate = self
  1007. e2ee.initEndToEndEncryption()
  1008. return
  1009. }
  1010. if metadata.directory {
  1011. pushMetadata(metadata)
  1012. } else {
  1013. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1014. if !metadata.isDirectoryE2EE && (metadata.isImage || metadata.isAudioOrVideo) {
  1015. var metadatas: [tableMetadata] = []
  1016. for metadata in metadataSourceForAllSections {
  1017. if metadata.isImage || metadata.isAudioOrVideo {
  1018. metadatas.append(metadata)
  1019. }
  1020. }
  1021. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: imageIcon)
  1022. return
  1023. }
  1024. if CCUtility.fileProviderStorageExists(metadata) {
  1025. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  1026. } else if NextcloudKit.shared.isNetworkReachable() {
  1027. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileView) { _, _ in }
  1028. } else {
  1029. let error = NKError(errorCode: NCGlobal.shared.errorOffline, errorDescription: "_go_online_")
  1030. NCContentPresenter.shared.showInfo(error: error)
  1031. }
  1032. }
  1033. }
  1034. func pushViewController(viewController: UIViewController) {
  1035. if pushed { return }
  1036. pushed = true
  1037. navigationController?.pushViewController(viewController, animated: true)
  1038. }
  1039. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1040. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  1041. if isEditMode || metadata.classFile == NKCommon.TypeClassFile.url.rawValue { return nil }
  1042. let identifier = indexPath as NSCopying
  1043. var image: UIImage?
  1044. let cell = collectionView.cellForItem(at: indexPath)
  1045. if cell is NCListCell {
  1046. image = (cell as! NCListCell).imageItem.image
  1047. } else if cell is NCGridCell {
  1048. image = (cell as! NCGridCell).imageItem.image
  1049. }
  1050. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  1051. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  1052. }, actionProvider: { _ in
  1053. return NCContextMenu().viewMenu(ocId: metadata.ocId, indexPath: indexPath, viewController: self, image: image)
  1054. })
  1055. }
  1056. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  1057. animator.addCompletion {
  1058. if let indexPath = configuration.identifier as? IndexPath {
  1059. self.collectionView(collectionView, didSelectItemAt: indexPath)
  1060. }
  1061. }
  1062. }
  1063. }
  1064. extension NCCollectionViewCommon: UICollectionViewDataSource {
  1065. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1066. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1067. // Thumbnail
  1068. if !metadata.directory {
  1069. if metadata.name == NCGlobal.shared.appName {
  1070. if let image = NCUtility.shared.createFilePreviewImage(ocId: metadata.ocId, etag: metadata.etag, fileNameView: metadata.fileNameView, classFile: metadata.classFile, status: metadata.status, createPreviewMedia: !metadata.hasPreview) {
  1071. (cell as! NCCellProtocol).filePreviewImageView?.image = image
  1072. } else {
  1073. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: true, cell: cell, view: collectionView)
  1074. }
  1075. } else {
  1076. // Unified search
  1077. switch metadata.iconName {
  1078. case let str where str.contains("contacts"):
  1079. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconContacts
  1080. case let str where str.contains("conversation"):
  1081. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1082. case let str where str.contains("calendar"):
  1083. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconCalendar
  1084. case let str where str.contains("deck"):
  1085. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconDeck
  1086. case let str where str.contains("mail"):
  1087. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconMail
  1088. case let str where str.contains("talk"):
  1089. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1090. case let str where str.contains("confirm"):
  1091. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconConfirm
  1092. case let str where str.contains("pages"):
  1093. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconPages
  1094. default:
  1095. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.file
  1096. }
  1097. if !metadata.iconUrl.isEmpty {
  1098. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata), let cell = cell as? NCCellProtocol {
  1099. let fileName = metadata.userBaseUrl + "-" + ownerId + ".png"
  1100. NCOperationQueue.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1101. }
  1102. }
  1103. }
  1104. }
  1105. // Avatar
  1106. if metadata.ownerId.count > 0,
  1107. metadata.ownerId != appDelegate.userId,
  1108. appDelegate.account == metadata.account,
  1109. let cell = cell as? NCCellProtocol {
  1110. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  1111. NCOperationQueue.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.fileAvatarImageView)
  1112. }
  1113. }
  1114. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { }
  1115. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1116. return dataSource.numberOfSections()
  1117. }
  1118. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1119. let numberItems = dataSource.numberOfItemsInSection(section)
  1120. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1121. return numberItems
  1122. }
  1123. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1124. var cell: NCCellProtocol & UICollectionViewCell
  1125. // LAYOUT LIST
  1126. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1127. guard let listCell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as? NCListCell else { return UICollectionViewCell() }
  1128. listCell.delegate = self
  1129. cell = listCell
  1130. } else {
  1131. // LAYOUT GRID
  1132. guard let gridCell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridCell else { return UICollectionViewCell() }
  1133. gridCell.delegate = self
  1134. cell = gridCell
  1135. }
  1136. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return cell }
  1137. var isShare = false
  1138. var isMounted = false
  1139. var a11yValues: [String] = []
  1140. if metadataFolder != nil {
  1141. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  1142. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  1143. }
  1144. cell.fileSelectImage?.image = nil
  1145. cell.fileStatusImage?.image = nil
  1146. cell.fileLocalImage?.image = nil
  1147. cell.fileFavoriteImage?.image = nil
  1148. cell.fileSharedImage?.image = nil
  1149. cell.fileMoreImage?.image = nil
  1150. cell.filePreviewImageView?.image = nil
  1151. cell.filePreviewImageView?.backgroundColor = nil
  1152. cell.fileObjectId = metadata.ocId
  1153. cell.indexPath = indexPath
  1154. cell.fileUser = metadata.ownerId
  1155. cell.fileProgressView?.isHidden = true
  1156. cell.fileProgressView?.progress = 0.0
  1157. cell.hideButtonShare(false)
  1158. cell.hideButtonMore(false)
  1159. cell.titleInfoTrailingDefault()
  1160. if isSearchingMode {
  1161. cell.fileTitleLabel?.text = metadata.fileName
  1162. cell.fileTitleLabel?.lineBreakMode = .byTruncatingTail
  1163. if metadata.name == NCGlobal.shared.appName {
  1164. cell.fileInfoLabel?.text = NSLocalizedString("_in_", comment: "") + " " + NCUtilityFileSystem.shared.getPath(path: metadata.path, user: metadata.user)
  1165. } else {
  1166. cell.fileInfoLabel?.text = metadata.subline
  1167. }
  1168. } else {
  1169. cell.fileTitleLabel?.text = metadata.fileNameView
  1170. cell.fileTitleLabel?.lineBreakMode = .byTruncatingMiddle
  1171. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  1172. }
  1173. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1174. cell.fileProgressView?.isHidden = false
  1175. }
  1176. // Accessibility [shared]
  1177. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1178. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1179. }
  1180. if metadata.directory {
  1181. let tableDirectory = NCManageDatabase.shared.getTableDirectory(ocId: metadata.ocId)
  1182. if metadata.e2eEncrypted {
  1183. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderEncrypted
  1184. } else if isShare {
  1185. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderSharedWithMe
  1186. } else if !metadata.shareType.isEmpty {
  1187. metadata.shareType.contains(3) ?
  1188. (cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderPublic) :
  1189. (cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderSharedWithMe)
  1190. } else if !metadata.shareType.isEmpty && metadata.shareType.contains(3) {
  1191. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderPublic
  1192. } else if metadata.mountType == "group" {
  1193. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderGroup
  1194. } else if isMounted {
  1195. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderExternal
  1196. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1197. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1198. } else {
  1199. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folder
  1200. }
  1201. // Local image: offline
  1202. if let tableDirectory, tableDirectory.offline {
  1203. cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag
  1204. }
  1205. // color folder
  1206. cell.filePreviewImageView?.image = cell.filePreviewImageView?.image?.colorizeFolder(metadata: metadata, tableDirectory: tableDirectory)
  1207. } else {
  1208. // image local
  1209. if NCManageDatabase.shared.getTableLocalFile(ocId: metadata.ocId) != nil {
  1210. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1211. cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag
  1212. } else if CCUtility.fileProviderStorageExists(metadata) {
  1213. cell.fileLocalImage?.image = NCBrandColor.cacheImages.local
  1214. }
  1215. }
  1216. // image Favorite
  1217. if metadata.favorite {
  1218. cell.fileFavoriteImage?.image = NCBrandColor.cacheImages.favorite
  1219. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1220. }
  1221. // Share image
  1222. if isShare {
  1223. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1224. } else if !metadata.shareType.isEmpty {
  1225. metadata.shareType.contains(3) ?
  1226. (cell.fileSharedImage?.image = NCBrandColor.cacheImages.shareByLink) :
  1227. (cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared)
  1228. } else {
  1229. cell.fileSharedImage?.image = NCBrandColor.cacheImages.canShare
  1230. }
  1231. if appDelegate.account != metadata.account {
  1232. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1233. }
  1234. // Button More
  1235. if metadata.isInTransfer || metadata.isWaitingTransfer {
  1236. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1237. } else if metadata.lock == true {
  1238. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1239. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1240. } else {
  1241. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1242. }
  1243. // Write status on Label Info
  1244. switch metadata.status {
  1245. case NCGlobal.shared.metadataStatusWaitDownload:
  1246. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1247. break
  1248. case NCGlobal.shared.metadataStatusInDownload:
  1249. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1250. break
  1251. case NCGlobal.shared.metadataStatusDownloading:
  1252. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↓ …"
  1253. break
  1254. case NCGlobal.shared.metadataStatusWaitUpload:
  1255. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1256. cell.fileLocalImage?.image = nil
  1257. break
  1258. case NCGlobal.shared.metadataStatusInUpload:
  1259. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1260. cell.fileLocalImage?.image = nil
  1261. break
  1262. case NCGlobal.shared.metadataStatusUploading:
  1263. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↑ …"
  1264. cell.fileLocalImage?.image = nil
  1265. break
  1266. case NCGlobal.shared.metadataStatusUploadError:
  1267. if metadata.sessionError != "" {
  1268. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1269. } else {
  1270. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1271. }
  1272. break
  1273. default:
  1274. break
  1275. }
  1276. // Live Photo
  1277. if metadata.livePhoto {
  1278. cell.fileStatusImage?.image = NCBrandColor.cacheImages.livePhoto
  1279. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1280. }
  1281. // URL
  1282. if metadata.classFile == NKCommon.TypeClassFile.url.rawValue {
  1283. cell.fileLocalImage?.image = nil
  1284. cell.hideButtonShare(true)
  1285. cell.hideButtonMore(true)
  1286. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata) {
  1287. cell.fileUser = ownerId
  1288. }
  1289. }
  1290. // Disable Share Button
  1291. if appDelegate.disableSharesView || (isDirectoryE2EE && !isDirectoryE2EETop ) {
  1292. cell.hideButtonShare(true)
  1293. }
  1294. // Separator
  1295. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || isSearchingMode {
  1296. cell.cellSeparatorView?.isHidden = true
  1297. } else {
  1298. cell.cellSeparatorView?.isHidden = false
  1299. }
  1300. // Edit mode
  1301. if isEditMode {
  1302. cell.selectMode(true)
  1303. if selectOcId.contains(metadata.ocId) {
  1304. cell.selected(true)
  1305. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1306. } else {
  1307. cell.selected(false)
  1308. }
  1309. } else {
  1310. cell.selectMode(false)
  1311. }
  1312. // Accessibility
  1313. cell.setAccessibility(label: metadata.fileNameView + ", " + (cell.fileInfoLabel?.text ?? ""), value: a11yValues.joined(separator: ", "))
  1314. // Color string find in search
  1315. if isSearchingMode, let literalSearch = self.literalSearch, let title = cell.fileTitleLabel?.text {
  1316. let longestWordRange = (title.lowercased() as NSString).range(of: literalSearch)
  1317. let attributedString = NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)])
  1318. attributedString.setAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15), NSAttributedString.Key.foregroundColor : UIColor.systemBlue], range: longestWordRange)
  1319. cell.fileTitleLabel?.attributedText = attributedString
  1320. }
  1321. // Add TAGS
  1322. cell.setTags(tags: Array(metadata.tags))
  1323. // Hide buttons
  1324. if metadata.name != NCGlobal.shared.appName {
  1325. cell.titleInfoTrailingFull()
  1326. cell.hideButtonShare(true)
  1327. cell.hideButtonMore(true)
  1328. }
  1329. // ** IMPORT MUST BE AT THE END **
  1330. //
  1331. if !metadata.isSharable() {
  1332. cell.hideButtonShare(true)
  1333. }
  1334. return cell
  1335. }
  1336. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1337. if kind == UICollectionView.elementKindSectionHeader {
  1338. if indexPath.section == 0 {
  1339. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  1340. let (_, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: indexPath.section)
  1341. self.headerMenu = header
  1342. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  1343. header.setImageSwitchList()
  1344. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  1345. } else {
  1346. header.setImageSwitchGrid()
  1347. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  1348. }
  1349. header.delegate = self
  1350. if !isSearchingMode, headerMenuTransferView, let ocId = NCNetworking.shared.transferInForegorund?.ocId {
  1351. let text = String(format: NSLocalizedString("_upload_foreground_msg_", comment: ""), NCBrandOptions.shared.brand)
  1352. header.setViewTransfer(isHidden: false, ocId: ocId, text: text, progress: NCNetworking.shared.transferInForegorund?.progress)
  1353. } else {
  1354. header.setViewTransfer(isHidden: true)
  1355. }
  1356. if headerMenuButtonsView {
  1357. header.setStatusButtonsView(enable: !dataSource.getMetadataSourceForAllSections().isEmpty)
  1358. header.setButtonsView(height: NCGlobal.shared.heightButtonsView)
  1359. header.setSortedTitle(layoutForView?.titleButtonHeader ?? "")
  1360. } else {
  1361. header.setButtonsView(height: 0)
  1362. }
  1363. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  1364. header.setRichWorkspaceText(richWorkspaceText)
  1365. header.setSectionHeight(heightHeaderSection)
  1366. if heightHeaderSection == 0 {
  1367. header.labelSection.text = ""
  1368. } else {
  1369. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  1370. }
  1371. header.labelSection.textColor = .label
  1372. return header
  1373. } else {
  1374. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  1375. header.labelSection.text = self.dataSource.getSectionValueLocalization(indexPath: indexPath)
  1376. header.labelSection.textColor = .label
  1377. return header
  1378. }
  1379. } else {
  1380. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1381. let sections = dataSource.numberOfSections()
  1382. let section = indexPath.section
  1383. let metadataForSection = self.dataSource.getMetadataForSection(indexPath.section)
  1384. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1385. let metadatasCount: Int = metadataForSection?.metadatas.count ?? 0
  1386. let unifiedSearchInProgress = metadataForSection?.unifiedSearchInProgress ?? false
  1387. footer.delegate = self
  1388. footer.metadataForSection = metadataForSection
  1389. footer.setTitleLabel("")
  1390. footer.setButtonText(NSLocalizedString("_show_more_results_", comment: ""))
  1391. footer.separatorIsHidden(true)
  1392. footer.buttonIsHidden(true)
  1393. footer.hideActivityIndicatorSection()
  1394. if isSearchingMode {
  1395. if sections > 1 && section != sections - 1 {
  1396. footer.separatorIsHidden(false)
  1397. }
  1398. // If the number of entries(metadatas) is lower than the cursor, then there are no more entries.
  1399. // The blind spot in this is when the number of entries is the same as the cursor. If so, we don't have a way of knowing if there are no more entries.
  1400. // This is as good as it gets for determining last page without server-side flag.
  1401. let isLastPage = (metadatasCount < metadataForSection?.lastSearchResult?.cursor ?? 0) || metadataForSection?.lastSearchResult?.entries.isEmpty == true
  1402. if isSearchingMode && isPaginated && metadatasCount > 0 && !isLastPage {
  1403. footer.buttonIsHidden(false)
  1404. }
  1405. if unifiedSearchInProgress {
  1406. footer.showActivityIndicatorSection()
  1407. }
  1408. } else {
  1409. if sections == 1 || section == sections - 1 {
  1410. let info = dataSource.getFooterInformationAllMetadatas()
  1411. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  1412. } else {
  1413. footer.separatorIsHidden(false)
  1414. }
  1415. }
  1416. return footer
  1417. }
  1418. }
  1419. }
  1420. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1421. func getHeaderHeight() -> CGFloat {
  1422. var size: CGFloat = 0
  1423. // transfer in progress
  1424. if headerMenuTransferView,
  1425. let metadata = NCManageDatabase.shared.getMetadataFromOcId(NCNetworking.shared.transferInForegorund?.ocId),
  1426. metadata.isTransferInForeground {
  1427. if !isSearchingMode {
  1428. size += NCGlobal.shared.heightHeaderTransfer
  1429. }
  1430. } else {
  1431. NCNetworking.shared.transferInForegorund = nil
  1432. }
  1433. if headerMenuButtonsView {
  1434. size += NCGlobal.shared.heightButtonsView
  1435. }
  1436. return size
  1437. }
  1438. func getHeaderHeight(section:Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  1439. var headerRichWorkspace: CGFloat = 0
  1440. if let richWorkspaceText = richWorkspaceText, !headerRichWorkspaceDisable {
  1441. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1442. if trimmed.count > 0 && !isSearchingMode {
  1443. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  1444. }
  1445. }
  1446. if isSearchingMode || layoutForView?.layout == NCGlobal.shared.layoutGrid || dataSource.numberOfSections() > 1 {
  1447. if section == 0 {
  1448. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1449. } else {
  1450. return (0, 0, NCGlobal.shared.heightSection)
  1451. }
  1452. } else {
  1453. return (getHeaderHeight(), headerRichWorkspace, 0)
  1454. }
  1455. }
  1456. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1457. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  1458. let heightHeader = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  1459. return CGSize(width: collectionView.frame.width, height: heightHeader)
  1460. }
  1461. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1462. let sections = dataSource.numberOfSections()
  1463. let metadataForSection = self.dataSource.getMetadataForSection(section)
  1464. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1465. let metadatasCount: Int = metadataForSection?.lastSearchResult?.entries.count ?? 0
  1466. var size = CGSize(width: collectionView.frame.width, height: 0)
  1467. if section == sections - 1 {
  1468. size.height += NCGlobal.shared.endHeightFooter
  1469. } else {
  1470. size.height += NCGlobal.shared.heightFooter
  1471. }
  1472. if isSearchingMode && isPaginated && metadatasCount > 0 {
  1473. size.height += NCGlobal.shared.heightFooterButton
  1474. }
  1475. return size
  1476. }
  1477. }
  1478. extension NCCollectionViewCommon: EasyTipViewDelegate {
  1479. func easyTipViewDidTap(_ tipView: EasyTipView) {
  1480. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1481. }
  1482. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  1483. func dismissTip() {
  1484. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1485. self.tipView?.dismiss()
  1486. }
  1487. }