NCCollectionViewCommon.swift 88 KB

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