NCCollectionViewCommon.swift 82 KB

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