NCCollectionViewCommon.swift 82 KB

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