NCCollectionViewCommon.swift 85 KB

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