NCCollectionViewCommon.swift 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948
  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)
  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. self.dismissTip()
  587. }
  588. }
  589. navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true)
  590. navigationItem.leftItemsSupplementBackButton = true
  591. }
  592. func getNavigationTitle() -> String {
  593. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  594. guard let userAlias = activeAccount?.alias, !userAlias.isEmpty else {
  595. return NCBrandOptions.shared.brand
  596. }
  597. return userAlias
  598. }
  599. // MARK: - BackgroundImageColor Delegate
  600. func colorPickerCancel() {
  601. changeTheming()
  602. }
  603. func colorPickerWillChange(color: UIColor) {
  604. collectionView.backgroundColor = color
  605. }
  606. func colorPickerDidChange(lightColor: String, darkColor: String) {
  607. NCManageDatabase.shared.setAccountColorFiles(lightColorBackground: lightColor, darkColorBackground: darkColor)
  608. changeTheming()
  609. }
  610. // MARK: - Empty
  611. func emptyDataSetView(_ view: NCEmptyView) {
  612. self.emptyDataSet?.setOffset(getHeaderHeight())
  613. if isSearching {
  614. view.emptyImage.image = UIImage(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  615. if isReloadDataSourceNetworkInProgress {
  616. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  617. } else {
  618. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  619. }
  620. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  621. } else if isReloadDataSourceNetworkInProgress {
  622. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  623. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  624. view.emptyDescription.text = ""
  625. } else {
  626. if serverUrl == "" {
  627. view.emptyImage.image = emptyImage
  628. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  629. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  630. } else {
  631. view.emptyImage.image = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  632. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  633. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  634. }
  635. }
  636. }
  637. // MARK: - SEARCH
  638. func updateSearchResults(for searchController: UISearchController) {
  639. self.literalSearch = searchController.searchBar.text
  640. }
  641. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  642. self.isSearching = true
  643. self.providers?.removeAll()
  644. self.dataSource.clearDataSource()
  645. self.collectionView.reloadData()
  646. // TIP
  647. self.tipView?.dismiss()
  648. }
  649. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  650. if self.isSearching && self.literalSearch?.count ?? 0 >= 2 {
  651. reloadDataSourceNetwork()
  652. }
  653. }
  654. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  655. DispatchQueue.global().async {
  656. NCNetworking.shared.cancelUnifiedSearchFiles()
  657. self.isSearching = false
  658. self.literalSearch = ""
  659. self.providers?.removeAll()
  660. self.dataSource.clearDataSource()
  661. self.reloadDataSource()
  662. }
  663. }
  664. // MARK: - TAP EVENT
  665. func accountRequestChangeAccount(account: String) {
  666. NCManageDatabase.shared.setAccountActive(account)
  667. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  668. NCOperationQueue.shared.cancelAllQueue()
  669. NCNetworking.shared.cancelAllTask()
  670. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  671. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  672. }
  673. }
  674. func accountRequestAddAccount() {
  675. appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  676. }
  677. func tapButtonSwitch(_ sender: Any) {
  678. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  679. // list layout
  680. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  681. layoutForView?.layout = NCGlobal.shared.layoutList
  682. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  683. self.groupByField = "name"
  684. if self.dataSource.groupByField != self.groupByField {
  685. self.dataSource.changeGroupByField(self.groupByField)
  686. }
  687. self.collectionView.reloadData()
  688. self.collectionView.collectionViewLayout.invalidateLayout()
  689. self.collectionView.setCollectionViewLayout(self.listLayout, animated: true)
  690. } else {
  691. // grid layout
  692. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  693. layoutForView?.layout = NCGlobal.shared.layoutGrid
  694. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  695. if self.isSearching {
  696. self.groupByField = "name"
  697. } else {
  698. self.groupByField = "classFile"
  699. }
  700. if self.dataSource.groupByField != self.groupByField {
  701. self.dataSource.changeGroupByField(self.groupByField)
  702. }
  703. self.collectionView.reloadData()
  704. self.collectionView.collectionViewLayout.invalidateLayout()
  705. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: true)
  706. }
  707. }
  708. func tapButtonOrder(_ sender: Any) {
  709. let sortMenu = NCSortMenu()
  710. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  711. }
  712. func tapButton1(_ sender: Any) {
  713. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: self) { hasPermission in
  714. if hasPermission {
  715. NCPhotosPickerViewController.init(viewController: self, maxSelectedAssets: 0, singleSelectedMode: false)
  716. }
  717. }
  718. }
  719. func tapButton2(_ sender: Any) {
  720. guard !appDelegate.activeServerUrl.isEmpty else { return }
  721. let alertController = UIAlertController.createFolder(serverUrl: appDelegate.activeServerUrl, urlBase: appDelegate)
  722. appDelegate.window?.rootViewController?.present(alertController, animated: true, completion: nil)
  723. }
  724. func tapButton3(_ sender: Any) {
  725. if #available(iOS 13.0, *) {
  726. if let viewController = appDelegate.window?.rootViewController {
  727. NCCreateScanDocument.shared.openScannerDocument(viewController: viewController)
  728. }
  729. }
  730. }
  731. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  732. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  733. }
  734. func tapShareListItem(with objectId: String, sender: Any) {
  735. if isEditMode { return }
  736. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  737. NCFunctionCenter.shared.openShare(viewController: self, metadata: metadata, indexPage: .sharing)
  738. }
  739. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  740. if isEditMode { return }
  741. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  742. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  743. toggleMenu(metadata: metadata, imageIcon: image)
  744. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  745. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  746. }
  747. }
  748. func tapRichWorkspace(_ sender: Any) {
  749. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  750. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  751. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  752. viewerRichWorkspace.serverUrl = serverUrl
  753. navigationController.modalPresentationStyle = .fullScreen
  754. self.present(navigationController, animated: true, completion: nil)
  755. }
  756. }
  757. }
  758. func tapButtonSection(_ sender: Any, metadataForSection: NCMetadataForSection?) {
  759. unifiedSearchMore(metadataForSection: metadataForSection)
  760. }
  761. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  762. }
  763. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  764. }
  765. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  766. }
  767. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  768. }
  769. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  770. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  771. /*
  772. if #available(iOS 13.0, *) {
  773. let interaction = UIContextMenuInteraction(delegate: self)
  774. self.view.addInteraction(interaction)
  775. }
  776. */
  777. }
  778. @available(iOS 13.0, *)
  779. func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
  780. return UIContextMenuConfiguration(identifier: nil, previewProvider: {
  781. return nil
  782. }, actionProvider: { _ in
  783. // let share = UIAction(title: "Share Pupper", image: UIImage(systemName: "square.and.arrow.up")) { action in
  784. // }
  785. // return UIMenu(title: "Main Menu", children: [share])
  786. return nil
  787. })
  788. }
  789. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  790. if gestureRecognizer.state != .began { return }
  791. var listMenuItems: [UIMenuItem] = []
  792. let touchPoint = gestureRecognizer.location(in: collectionView)
  793. becomeFirstResponder()
  794. if serverUrl != "" {
  795. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu)))
  796. }
  797. if #available(iOS 13.0, *) {
  798. if !NCBrandOptions.shared.disable_background_color {
  799. listMenuItems.append(UIMenuItem(title: NSLocalizedString("_background_", comment: ""), action: #selector(backgroundFilesMenu)))
  800. }
  801. }
  802. if listMenuItems.count > 0 {
  803. UIMenuController.shared.menuItems = listMenuItems
  804. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  805. UIMenuController.shared.setMenuVisible(true, animated: true)
  806. }
  807. }
  808. // MARK: - Menu Item
  809. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  810. if #selector(pasteFilesMenu) == action {
  811. if UIPasteboard.general.items.count > 0 {
  812. return true
  813. }
  814. }
  815. if #selector(backgroundFilesMenu) == action {
  816. return true
  817. }
  818. return false
  819. }
  820. @objc func pasteFilesMenu() {
  821. NCFunctionCenter.shared.pastePasteboard(serverUrl: serverUrl)
  822. }
  823. @objc func backgroundFilesMenu() {
  824. if let vcBackgroundImageColor = UIStoryboard(name: "NCBackgroundImageColor", bundle: nil).instantiateInitialViewController() as? NCBackgroundImageColor {
  825. vcBackgroundImageColor.delegate = self
  826. vcBackgroundImageColor.setupColor = collectionView.backgroundColor
  827. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  828. vcBackgroundImageColor.lightColor = activeAccount.lightColorBackground
  829. vcBackgroundImageColor.darkColor = activeAccount.darkColorBackground
  830. }
  831. let popup = NCPopupViewController(contentController: vcBackgroundImageColor, popupWidth: vcBackgroundImageColor.width, popupHeight: vcBackgroundImageColor.height)
  832. popup.backgroundAlpha = 0
  833. self.present(popup, animated: true)
  834. }
  835. }
  836. // MARK: - DataSource + NC Endpoint
  837. @objc func reloadDataSource(forced: Bool = true) {
  838. guard !appDelegate.account.isEmpty else { return }
  839. // E2EE
  840. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  841. // get auto upload folder
  842. autoUploadFileName = NCManageDatabase.shared.getAccountAutoUploadFileName()
  843. autoUploadDirectory = NCManageDatabase.shared.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  844. // get layout for view
  845. layoutForView = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  846. // set GroupField for Grid
  847. if !self.isSearching && layoutForView?.layout == NCGlobal.shared.layoutGrid {
  848. groupByField = "classFile"
  849. } else {
  850. groupByField = "name"
  851. }
  852. }
  853. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  854. @objc func networkSearch() {
  855. guard !appDelegate.account.isEmpty, let literalSearch = literalSearch, !literalSearch.isEmpty
  856. else {
  857. self.refreshControl.endRefreshing()
  858. return
  859. }
  860. isReloadDataSourceNetworkInProgress = true
  861. self.dataSource.clearDataSource()
  862. self.refreshControl.beginRefreshing()
  863. self.collectionView.reloadData()
  864. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  865. if serverVersionMajor >= NCGlobal.shared.nextcloudVersion20 {
  866. NCNetworking.shared.unifiedSearchFiles(urlBase: appDelegate, literal: literalSearch) { allProviders in
  867. self.providers = allProviders
  868. self.searchResults = []
  869. self.dataSource = NCDataSource(
  870. metadatas: [] ,
  871. account: self.appDelegate.account,
  872. sort: self.layoutForView?.sort,
  873. ascending: self.layoutForView?.ascending,
  874. directoryOnTop: self.layoutForView?.directoryOnTop,
  875. favoriteOnTop: true,
  876. filterLivePhoto: true,
  877. providers: self.providers,
  878. searchResults: self.searchResults)
  879. } update: { id, searchResult, metadatas in
  880. guard let metadatas = metadatas, metadatas.count > 0, self.isSearching , let searchResult = searchResult else { return }
  881. NCOperationQueue.shared.unifiedSearchAddSection(collectionViewCommon: self, metadatas: metadatas, searchResult: searchResult)
  882. } completion: {errorCode, errorDescription in
  883. self.refreshControl.endRefreshing()
  884. self.isReloadDataSourceNetworkInProgress = false
  885. self.collectionView.reloadData()
  886. }
  887. } else {
  888. NCNetworking.shared.searchFiles(urlBase: appDelegate, literal: literalSearch) { metadatas, errorCode, errorDescription in
  889. DispatchQueue.main.async {
  890. self.refreshControl.endRefreshing()
  891. self.collectionView.reloadData()
  892. }
  893. guard let metadatas = metadatas, errorCode == 0, self.isSearching else { return }
  894. self.dataSource = NCDataSource(
  895. metadatas: metadatas,
  896. account: self.appDelegate.account,
  897. sort: self.layoutForView?.sort,
  898. ascending: self.layoutForView?.ascending,
  899. directoryOnTop: self.layoutForView?.directoryOnTop,
  900. favoriteOnTop: true,
  901. filterLivePhoto: true,
  902. groupByField: self.groupByField,
  903. providers: self.providers,
  904. searchResults: self.searchResults)
  905. self.isReloadDataSourceNetworkInProgress = false
  906. }
  907. }
  908. }
  909. func unifiedSearchMore(metadataForSection: NCMetadataForSection?) {
  910. guard let metadataForSection = metadataForSection, let searchResult = metadataForSection.lastSearchResult, let cursor = searchResult.cursor, let term = literalSearch else { return }
  911. metadataForSection.unifiedSearchInProgress = true
  912. self.collectionView?.reloadData()
  913. NCNetworking.shared.unifiedSearchFilesProvider(urlBase: appDelegate, id: searchResult.id, term: term, limit: 5, cursor: cursor) { searchResult, metadatas, errorCode, errorDescription in
  914. if errorCode != 0 {
  915. NCContentPresenter.shared.messageNotification("_error_", description: errorDescription, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: errorCode)
  916. }
  917. metadataForSection.unifiedSearchInProgress = false
  918. guard let searchResult = searchResult, let metadatas = metadatas else { return }
  919. self.dataSource.appendMetadatasToSection(metadatas, metadataForSection: metadataForSection, lastSearchResult: searchResult)
  920. DispatchQueue.main.async {
  921. self.collectionView?.reloadData()
  922. }
  923. }
  924. }
  925. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ tableDirectory: tableDirectory?, _ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ metadatasDelete: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String) -> Void) {
  926. var tableDirectory: tableDirectory?
  927. NCNetworking.shared.readFile(serverUrlFileName: serverUrl) { (account, metadataFolder, errorCode, errorDescription) in
  928. guard errorCode == 0 else {
  929. completion(nil, nil, nil, nil, errorCode, errorDescription)
  930. return
  931. }
  932. if let metadataFolder = metadataFolder {
  933. tableDirectory = NCManageDatabase.shared.setDirectory(richWorkspace: metadataFolder.richWorkspace, serverUrl: self.serverUrl, account: account)
  934. }
  935. if forced || tableDirectory?.etag != metadataFolder?.etag || metadataFolder?.e2eEncrypted ?? false {
  936. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { account, metadataFolder, metadatas, metadatasUpdate, _, metadatasDelete, errorCode, errorDescription in
  937. guard errorCode == 0 else {
  938. completion(tableDirectory, nil, nil, nil, errorCode, errorDescription)
  939. return
  940. }
  941. self.metadataFolder = metadataFolder
  942. // E2EE
  943. if let metadataFolder = metadataFolder, metadataFolder.e2eEncrypted, CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  944. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { account, e2eMetadata, errorCode, errorDescription in
  945. if errorCode == 0, let e2eMetadata = e2eMetadata {
  946. if NCEndToEndMetadata.shared.decoderMetadata(e2eMetadata, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  947. self.reloadDataSource()
  948. } else {
  949. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorDecodeMetadata)
  950. }
  951. } else if errorCode != NCGlobal.shared.errorResourceNotFound {
  952. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, errorCode: NCGlobal.shared.errorDecodeMetadata)
  953. }
  954. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  955. }
  956. } else {
  957. completion(tableDirectory, metadatas, metadatasUpdate, metadatasDelete, errorCode, errorDescription)
  958. }
  959. }
  960. } else {
  961. completion(tableDirectory, nil, nil, nil, 0, "")
  962. }
  963. }
  964. }
  965. // MARK: - Push metadata
  966. func pushMetadata(_ metadata: tableMetadata) {
  967. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName) else { return }
  968. appDelegate.activeMetadata = metadata
  969. // FILES
  970. if layoutKey == NCGlobal.shared.layoutViewFiles && !pushed {
  971. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  972. if viewController.isViewLoaded {
  973. pushViewController(viewController: viewController)
  974. }
  975. } else {
  976. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  977. viewController.isRoot = false
  978. viewController.serverUrl = serverUrlPush
  979. viewController.titleCurrentFolder = metadata.fileNameView
  980. appDelegate.listFilesVC[serverUrlPush] = viewController
  981. pushViewController(viewController: viewController)
  982. }
  983. }
  984. }
  985. // FAVORITE
  986. if layoutKey == NCGlobal.shared.layoutViewFavorite && !pushed {
  987. if let viewController = appDelegate.listFavoriteVC[serverUrlPush] {
  988. if viewController.isViewLoaded {
  989. pushViewController(viewController: viewController)
  990. }
  991. } else {
  992. if let viewController: NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as? NCFavorite {
  993. viewController.serverUrl = serverUrlPush
  994. viewController.titleCurrentFolder = metadata.fileNameView
  995. appDelegate.listFavoriteVC[serverUrlPush] = viewController
  996. pushViewController(viewController: viewController)
  997. }
  998. }
  999. }
  1000. // OFFLINE
  1001. if layoutKey == NCGlobal.shared.layoutViewOffline && !pushed {
  1002. if let viewController = appDelegate.listOfflineVC[serverUrlPush] {
  1003. if viewController.isViewLoaded {
  1004. pushViewController(viewController: viewController)
  1005. }
  1006. } else {
  1007. if let viewController: NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as? NCOffline {
  1008. viewController.serverUrl = serverUrlPush
  1009. viewController.titleCurrentFolder = metadata.fileNameView
  1010. appDelegate.listOfflineVC[serverUrlPush] = viewController
  1011. pushViewController(viewController: viewController)
  1012. }
  1013. }
  1014. }
  1015. // RECENT ( for push use Files ... he he he )
  1016. if layoutKey == NCGlobal.shared.layoutViewRecent && !pushed {
  1017. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  1018. if viewController.isViewLoaded {
  1019. pushViewController(viewController: viewController)
  1020. }
  1021. } else {
  1022. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  1023. viewController.isRoot = false
  1024. viewController.serverUrl = serverUrlPush
  1025. viewController.titleCurrentFolder = metadata.fileNameView
  1026. appDelegate.listFilesVC[serverUrlPush] = viewController
  1027. pushViewController(viewController: viewController)
  1028. }
  1029. }
  1030. }
  1031. // VIEW IN FOLDER
  1032. if layoutKey == NCGlobal.shared.layoutViewViewInFolder && !pushed {
  1033. if let viewController: NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as? NCFileViewInFolder {
  1034. viewController.serverUrl = serverUrlPush
  1035. viewController.titleCurrentFolder = metadata.fileNameView
  1036. pushViewController(viewController: viewController)
  1037. }
  1038. }
  1039. // SHARES ( for push use Files ... he he he )
  1040. if layoutKey == NCGlobal.shared.layoutViewShares && !pushed {
  1041. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  1042. if viewController.isViewLoaded {
  1043. pushViewController(viewController: viewController)
  1044. }
  1045. } else {
  1046. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  1047. viewController.isRoot = false
  1048. viewController.serverUrl = serverUrlPush
  1049. viewController.titleCurrentFolder = metadata.fileNameView
  1050. appDelegate.listFilesVC[serverUrlPush] = viewController
  1051. pushViewController(viewController: viewController)
  1052. }
  1053. }
  1054. }
  1055. }
  1056. }
  1057. // MARK: - Collection View
  1058. extension NCCollectionViewCommon: UICollectionViewDelegate {
  1059. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  1060. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1061. appDelegate.activeMetadata = metadata
  1062. let metadataSourceForAllSections = dataSource.getMetadataSourceForAllSections()
  1063. if isEditMode {
  1064. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  1065. selectOcId.remove(at: index)
  1066. } else {
  1067. selectOcId.append(metadata.ocId)
  1068. }
  1069. collectionView.reloadItems(at: [indexPath])
  1070. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(metadataSourceForAllSections.count)"
  1071. return
  1072. }
  1073. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  1074. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorE2EENotEnabled)
  1075. return
  1076. }
  1077. if metadata.directory {
  1078. pushMetadata(metadata)
  1079. } else if !(self is NCFileViewInFolder) {
  1080. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1081. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  1082. var metadatas: [tableMetadata] = []
  1083. for metadata in metadataSourceForAllSections {
  1084. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  1085. metadatas.append(metadata)
  1086. }
  1087. }
  1088. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: imageIcon)
  1089. return
  1090. }
  1091. if CCUtility.fileProviderStorageExists(metadata) {
  1092. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  1093. } else if NCCommunication.shared.isNetworkReachable() {
  1094. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileView) { _ in }
  1095. } else {
  1096. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorOffline)
  1097. }
  1098. }
  1099. }
  1100. func pushViewController(viewController: UIViewController) {
  1101. if pushed { return }
  1102. pushed = true
  1103. navigationController?.pushViewController(viewController, animated: true)
  1104. }
  1105. @available(iOS 13.0, *)
  1106. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1107. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  1108. if isEditMode || metadata.classFile == NCCommunicationCommon.typeClassFile.url.rawValue { return nil }
  1109. let identifier = indexPath as NSCopying
  1110. var image: UIImage?
  1111. let cell = collectionView.cellForItem(at: indexPath)
  1112. if cell is NCListCell {
  1113. image = (cell as! NCListCell).imageItem.image
  1114. } else if cell is NCGridCell {
  1115. image = (cell as! NCGridCell).imageItem.image
  1116. }
  1117. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  1118. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  1119. }, actionProvider: { _ in
  1120. return NCFunctionCenter.shared.contextMenuConfiguration(ocId: metadata.ocId, viewController: self, enableDeleteLocal: true, enableViewInFolder: false, image: image)
  1121. })
  1122. }
  1123. @available(iOS 13.0, *)
  1124. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  1125. animator.addCompletion {
  1126. if let indexPath = configuration.identifier as? IndexPath {
  1127. self.collectionView(collectionView, didSelectItemAt: indexPath)
  1128. }
  1129. }
  1130. }
  1131. }
  1132. extension NCCollectionViewCommon: UICollectionViewDataSource {
  1133. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1134. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1135. // Thumbnail
  1136. if !metadata.directory {
  1137. if metadata.name == NCGlobal.shared.appName {
  1138. let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  1139. let iconImagePath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  1140. if FileManager().fileExists(atPath: iconImagePath) {
  1141. (cell as! NCCellProtocol).filePreviewImageView?.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1142. } else if metadata.status > NCGlobal.shared.metadataStatusNormal && metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue && FileManager().fileExists(atPath: filePath) {
  1143. 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) {
  1144. do {
  1145. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  1146. (cell as! NCCellProtocol).filePreviewImageView?.image = image
  1147. } catch { }
  1148. }
  1149. } else if metadata.status > NCGlobal.shared.metadataStatusNormal && metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue && FileManager().fileExists(atPath: filePath) {
  1150. 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) {
  1151. do {
  1152. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  1153. (cell as! NCCellProtocol).filePreviewImageView?.image = image
  1154. } catch { }
  1155. }
  1156. } else {
  1157. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: true, cell: cell, view: collectionView)
  1158. }
  1159. } else {
  1160. // Unified search
  1161. switch metadata.iconName {
  1162. case let str where str.contains("contacts"):
  1163. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconContacts
  1164. case let str where str.contains("conversation"):
  1165. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1166. case let str where str.contains("calendar"):
  1167. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconCalendar
  1168. case let str where str.contains("deck"):
  1169. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconDeck
  1170. case let str where str.contains("mail"):
  1171. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconMail
  1172. case let str where str.contains("talk"):
  1173. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1174. case let str where str.contains("confirm"):
  1175. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconConfirm
  1176. case let str where str.contains("pages"):
  1177. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconPages
  1178. default:
  1179. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.file
  1180. }
  1181. if !metadata.iconUrl.isEmpty {
  1182. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata), let cell = cell as? NCCellProtocol {
  1183. let fileName = metadata.userBaseUrl + "-" + ownerId + ".png"
  1184. NCOperationQueue.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1185. }
  1186. }
  1187. // if metadata.iconName.contains("contacts"), let subline = metadata.subline, !subline.isEmpty, let cell = cell as? NCCellProtocol {
  1188. // let components = subline.components(separatedBy: "@")
  1189. // if let user = components.first {
  1190. // let fileName = metadata.userBaseUrl + "-" + user + ".png"
  1191. // NCOperationQueue.shared.downloadAvatar(user: user, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1192. // }
  1193. // }
  1194. }
  1195. }
  1196. // Avatar
  1197. if metadata.ownerId.count > 0,
  1198. metadata.ownerId != appDelegate.userId,
  1199. appDelegate.account == metadata.account,
  1200. let cell = cell as? NCCellProtocol {
  1201. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  1202. NCOperationQueue.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.fileAvatarImageView)
  1203. }
  1204. }
  1205. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { }
  1206. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1207. return dataSource.numberOfSections()
  1208. }
  1209. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1210. let numberItems = dataSource.numberOfItemsInSection(section)
  1211. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1212. return numberItems
  1213. }
  1214. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1215. var cell: NCCellProtocol & UICollectionViewCell
  1216. // LAYOUT LIST
  1217. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1218. guard let listCell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as? NCListCell else { return UICollectionViewCell() }
  1219. listCell.delegate = self
  1220. cell = listCell
  1221. } else {
  1222. // LAYOUT GRID
  1223. guard let gridCell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridCell else { return UICollectionViewCell() }
  1224. gridCell.delegate = self
  1225. cell = gridCell
  1226. }
  1227. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return cell }
  1228. let tableShare = dataSource.metadatasForSection[indexPath.section].metadataShare[metadata.ocId]
  1229. var isShare = false
  1230. var isMounted = false
  1231. var a11yValues: [String] = []
  1232. if metadataFolder != nil {
  1233. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  1234. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  1235. }
  1236. cell.fileSelectImage?.image = nil
  1237. cell.fileStatusImage?.image = nil
  1238. cell.fileLocalImage?.image = nil
  1239. cell.fileFavoriteImage?.image = nil
  1240. cell.fileSharedImage?.image = nil
  1241. cell.fileMoreImage?.image = nil
  1242. cell.filePreviewImageView?.image = nil
  1243. cell.filePreviewImageView?.backgroundColor = nil
  1244. cell.fileObjectId = metadata.ocId
  1245. cell.fileUser = metadata.ownerId
  1246. cell.fileProgressView?.isHidden = true
  1247. cell.fileProgressView?.progress = 0.0
  1248. cell.hideButtonShare(false)
  1249. cell.hideButtonMore(false)
  1250. cell.titleInfoTrailingDefault()
  1251. if isSearching {
  1252. cell.fileTitleLabel?.text = metadata.fileName
  1253. cell.fileTitleLabel?.lineBreakMode = .byTruncatingTail
  1254. if metadata.name == NCGlobal.shared.appName {
  1255. cell.fileInfoLabel?.text = NSLocalizedString("_in_", comment: "") + " " + NCUtilityFileSystem.shared.getPath(metadata: metadata, withFileName: false)
  1256. } else {
  1257. cell.fileInfoLabel?.text = metadata.subline
  1258. cell.titleInfoTrailingFull()
  1259. }
  1260. if let literalSearch = self.literalSearch {
  1261. let longestWordRange = (metadata.fileName.lowercased() as NSString).range(of: literalSearch)
  1262. let attributedString = NSMutableAttributedString(string: metadata.fileName, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)])
  1263. attributedString.setAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15), NSAttributedString.Key.foregroundColor : NCBrandColor.shared.annotationColor], range: longestWordRange)
  1264. cell.fileTitleLabel?.attributedText = attributedString
  1265. }
  1266. } else {
  1267. cell.fileTitleLabel?.text = metadata.fileNameView
  1268. cell.fileTitleLabel?.lineBreakMode = .byTruncatingMiddle
  1269. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  1270. }
  1271. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1272. cell.fileProgressView?.isHidden = false
  1273. }
  1274. // Accessibility [shared]
  1275. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1276. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1277. }
  1278. if metadata.directory {
  1279. if metadata.e2eEncrypted {
  1280. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderEncrypted
  1281. } else if isShare {
  1282. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderSharedWithMe
  1283. } else if tableShare != nil && tableShare?.shareType != 3 {
  1284. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderSharedWithMe
  1285. } else if tableShare != nil && tableShare?.shareType == 3 {
  1286. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderPublic
  1287. } else if metadata.mountType == "group" {
  1288. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderGroup
  1289. } else if isMounted {
  1290. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderExternal
  1291. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1292. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1293. if cell is NCListCell {
  1294. cell.fileTitleLabel?.text = (cell.fileTitleLabel?.text ?? "") + " - " + NSLocalizedString("_auto_upload_folder_", comment: "")
  1295. }
  1296. } else {
  1297. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folder
  1298. }
  1299. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1300. let tableDirectory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1301. // Local image: offline
  1302. if tableDirectory != nil && tableDirectory!.offline {
  1303. cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag
  1304. }
  1305. } else {
  1306. // image local
  1307. if dataSource.metadatasForSection[indexPath.section].metadataOffLine.contains(metadata.ocId) {
  1308. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1309. cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag
  1310. } else if CCUtility.fileProviderStorageExists(metadata) {
  1311. cell.fileLocalImage?.image = NCBrandColor.cacheImages.local
  1312. }
  1313. }
  1314. // image Favorite
  1315. if metadata.favorite {
  1316. cell.fileFavoriteImage?.image = NCBrandColor.cacheImages.favorite
  1317. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1318. }
  1319. // Share image
  1320. if isShare {
  1321. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1322. } else if tableShare != nil && tableShare?.shareType == 3 {
  1323. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shareByLink
  1324. } else if tableShare != nil && tableShare?.shareType != 3 {
  1325. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1326. } else {
  1327. cell.fileSharedImage?.image = NCBrandColor.cacheImages.canShare
  1328. }
  1329. if appDelegate.account != metadata.account {
  1330. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1331. }
  1332. // Button More
  1333. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusInUpload || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1334. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1335. } else if metadata.lock == true {
  1336. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1337. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1338. } else {
  1339. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1340. }
  1341. // Write status on Label Info
  1342. switch metadata.status {
  1343. case NCGlobal.shared.metadataStatusWaitDownload:
  1344. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1345. break
  1346. case NCGlobal.shared.metadataStatusInDownload:
  1347. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1348. break
  1349. case NCGlobal.shared.metadataStatusDownloading:
  1350. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↓ …"
  1351. break
  1352. case NCGlobal.shared.metadataStatusWaitUpload:
  1353. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1354. break
  1355. case NCGlobal.shared.metadataStatusInUpload:
  1356. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1357. break
  1358. case NCGlobal.shared.metadataStatusUploading:
  1359. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↑ …"
  1360. break
  1361. case NCGlobal.shared.metadataStatusUploadError:
  1362. if metadata.sessionError != "" {
  1363. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1364. } else {
  1365. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1366. }
  1367. break
  1368. default:
  1369. break
  1370. }
  1371. // Live Photo
  1372. if metadata.livePhoto {
  1373. cell.fileStatusImage?.image = NCBrandColor.cacheImages.livePhoto
  1374. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1375. }
  1376. // E2EE
  1377. if metadata.e2eEncrypted || isEncryptedFolder {
  1378. cell.hideButtonShare(true)
  1379. }
  1380. // URL
  1381. if metadata.classFile == NCCommunicationCommon.typeClassFile.url.rawValue {
  1382. cell.fileLocalImage?.image = nil
  1383. cell.hideButtonShare(true)
  1384. cell.hideButtonMore(true)
  1385. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata) {
  1386. cell.fileUser = ownerId
  1387. }
  1388. }
  1389. // Disable Share Button
  1390. if appDelegate.disableSharesView {
  1391. cell.hideButtonShare(true)
  1392. }
  1393. // Separator
  1394. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || isSearching {
  1395. cell.cellSeparatorView?.isHidden = true
  1396. } else {
  1397. cell.cellSeparatorView?.isHidden = false
  1398. }
  1399. // Edit mode
  1400. if isEditMode {
  1401. cell.selectMode(true)
  1402. if selectOcId.contains(metadata.ocId) {
  1403. cell.selected(true)
  1404. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1405. } else {
  1406. cell.selected(false)
  1407. }
  1408. } else {
  1409. cell.selectMode(false)
  1410. }
  1411. // Accessibility
  1412. cell.setAccessibility(label: metadata.fileNameView + ", " + (cell.fileInfoLabel?.text ?? ""), value: a11yValues.joined(separator: ", "))
  1413. return cell
  1414. }
  1415. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1416. if kind == UICollectionView.elementKindSectionHeader {
  1417. if indexPath.section == 0 {
  1418. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  1419. let (_, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: indexPath.section)
  1420. self.headerMenu = header
  1421. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  1422. header.setImageSwitchList()
  1423. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  1424. } else {
  1425. header.setImageSwitchGrid()
  1426. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  1427. }
  1428. header.delegate = self
  1429. if headerMenuButtonsCommand && !isSearching {
  1430. 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: ""))
  1431. } else {
  1432. header.setButtonsCommand(heigt: 0)
  1433. }
  1434. if headerMenuButtonsView {
  1435. header.setStatusButtonsView(enable: !dataSource.getMetadataSourceForAllSections().isEmpty)
  1436. header.setButtonsView(heigt: NCGlobal.shared.heightButtonsView)
  1437. header.setSortedTitle(layoutForView?.titleButtonHeader ?? "")
  1438. } else {
  1439. header.setButtonsView(heigt: 0)
  1440. }
  1441. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  1442. header.setRichWorkspaceText(richWorkspaceText)
  1443. header.setSectionHeight(heightHeaderSection)
  1444. if heightHeaderSection == 0 {
  1445. header.labelSection.text = ""
  1446. } else {
  1447. header.labelSection.text = self.dataSource.getSectionValue(indexPath: indexPath)
  1448. }
  1449. header.labelSection.textColor = NCBrandColor.shared.label
  1450. return header
  1451. } else {
  1452. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  1453. header.labelSection.text = self.dataSource.getSectionValue(indexPath: indexPath)
  1454. header.labelSection.textColor = NCBrandColor.shared.label
  1455. return header
  1456. }
  1457. } else {
  1458. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1459. let sections = dataSource.numberOfSections()
  1460. let section = indexPath.section
  1461. let metadataForSection = self.dataSource.getMetadataForSection(indexPath.section)
  1462. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1463. let metadatasCount: Int = metadataForSection?.metadatas.count ?? 0
  1464. let unifiedSearchInProgress = metadataForSection?.unifiedSearchInProgress ?? false
  1465. footer.delegate = self
  1466. footer.metadataForSection = metadataForSection
  1467. footer.setTitleLabel("")
  1468. footer.setButtonText(NSLocalizedString("_show_more_results_", comment: ""))
  1469. footer.separatorIsHidden(true)
  1470. footer.buttonIsHidden(true)
  1471. footer.hideActivityIndicatorSection()
  1472. if isSearching {
  1473. if sections > 1 && section != sections - 1 {
  1474. footer.separatorIsHidden(false)
  1475. }
  1476. if isSearching && isPaginated && metadatasCount > 0 {
  1477. footer.buttonIsHidden(false)
  1478. }
  1479. if unifiedSearchInProgress {
  1480. footer.showActivityIndicatorSection()
  1481. }
  1482. } else {
  1483. if sections == 1 || section == sections - 1 {
  1484. let info = dataSource.getFooterInformationAllMetadatas()
  1485. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  1486. } else {
  1487. footer.separatorIsHidden(false)
  1488. }
  1489. }
  1490. return footer
  1491. }
  1492. }
  1493. }
  1494. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1495. func getHeaderHeight() -> CGFloat {
  1496. var size: CGFloat = 0
  1497. if headerMenuButtonsCommand && !isSearching {
  1498. size += NCGlobal.shared.heightButtonsCommand
  1499. }
  1500. if headerMenuButtonsView {
  1501. size += NCGlobal.shared.heightButtonsView
  1502. }
  1503. return size
  1504. }
  1505. func getHeaderHeight(section:Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  1506. var headerRichWorkspace: CGFloat = 0
  1507. if let richWorkspaceText = richWorkspaceText, !headerRichWorkspaceDisable {
  1508. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1509. if trimmed.count > 0 && !isSearching {
  1510. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  1511. }
  1512. }
  1513. if isSearching || layoutForView?.layout == NCGlobal.shared.layoutGrid || dataSource.numberOfSections() > 1 {
  1514. if section == 0 {
  1515. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1516. } else {
  1517. return (0, 0, NCGlobal.shared.heightSection)
  1518. }
  1519. } else {
  1520. return (getHeaderHeight(), headerRichWorkspace, 0)
  1521. }
  1522. }
  1523. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1524. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  1525. let heightHeader = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  1526. return CGSize(width: collectionView.frame.width, height: heightHeader)
  1527. }
  1528. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1529. let sections = dataSource.numberOfSections()
  1530. let metadataForSection = self.dataSource.getMetadataForSection(section)
  1531. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1532. let metadatasCount: Int = metadataForSection?.lastSearchResult?.entries.count ?? 0
  1533. var size = CGSize(width: collectionView.frame.width, height: 0)
  1534. if section == sections - 1 {
  1535. size.height += NCGlobal.shared.endHeightFooter
  1536. } else {
  1537. size.height += NCGlobal.shared.heightFooter
  1538. }
  1539. if isSearching && isPaginated && metadatasCount > 0 {
  1540. size.height += NCGlobal.shared.heightFooterButton
  1541. }
  1542. return size
  1543. }
  1544. }
  1545. extension NCCollectionViewCommon: EasyTipViewDelegate {
  1546. func easyTipViewDidTap(_ tipView: EasyTipView) {
  1547. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1548. }
  1549. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  1550. func dismissTip() {
  1551. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1552. self.tipView?.dismiss()
  1553. }
  1554. }