NCCollectionViewCommon.swift 89 KB

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