NCCollectionViewCommon.swift 85 KB

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