NCCollectionViewCommon.swift 89 KB

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