NCCollectionViewCommon.swift 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  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. //coordinator.animate(alongsideTransition: nil) { _ in
  209. self.collectionView?.collectionViewLayout.invalidateLayout()
  210. self.collectionView?.reloadData()
  211. //}
  212. }
  213. override var canBecomeFirstResponder: Bool {
  214. return true
  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 changeTheming() {
  252. collectionView.reloadData()
  253. }
  254. @objc func reloadDataSource(_ notification: NSNotification) {
  255. reloadDataSource()
  256. }
  257. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  258. if !isSearching {
  259. reloadDataSourceNetwork(forced: true)
  260. }
  261. }
  262. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  263. reloadDataSource()
  264. }
  265. @objc func closeRichWorkspaceWebView() {
  266. reloadDataSourceNetwork()
  267. }
  268. @objc func deleteFile(_ notification: NSNotification) {
  269. guard let userInfo = notification.userInfo as NSDictionary?,
  270. let ocId = userInfo["ocId"] as? String,
  271. let fileNameView = userInfo["fileNameView"] as? String,
  272. let serverUrl = userInfo["serverUrl"] as? String,
  273. serverUrl == self.serverUrl,
  274. let account = userInfo["account"] as? String,
  275. account == appDelegate.account,
  276. let onlyLocalCache = userInfo["onlyLocalCache"] as? Bool
  277. else { return }
  278. if fileNameView.lowercased() == NCGlobal.shared.fileNameRichWorkspace.lowercased() {
  279. reloadDataSourceNetwork(forced: true)
  280. } else if onlyLocalCache {
  281. self.collectionView?.reloadData()
  282. } else {
  283. let (indexPath, sameSections) = dataSource.deleteMetadata(ocId: ocId)
  284. if let indexPath = indexPath {
  285. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  286. collectionView?.performBatchUpdates({
  287. collectionView?.deleteItems(at: [indexPath])
  288. }, completion: { _ in
  289. self.collectionView?.reloadData()
  290. })
  291. } else {
  292. self.collectionView?.reloadData()
  293. }
  294. } else {
  295. reloadDataSource()
  296. }
  297. }
  298. }
  299. @objc func moveFile(_ notification: NSNotification) {
  300. guard let userInfo = notification.userInfo as NSDictionary?,
  301. let ocId = userInfo["ocId"] as? String,
  302. let serverUrlFrom = userInfo["serverUrlFrom"] as? String,
  303. serverUrlFrom == self.serverUrl
  304. else { return }
  305. let (indexPath, sameSections) = dataSource.deleteMetadata(ocId: ocId)
  306. if let indexPath = indexPath {
  307. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  308. collectionView?.performBatchUpdates({
  309. collectionView?.deleteItems(at: [indexPath])
  310. }, completion: { _ in
  311. self.collectionView?.reloadData()
  312. })
  313. } else {
  314. self.collectionView?.reloadData()
  315. }
  316. } else {
  317. reloadDataSource()
  318. }
  319. }
  320. @objc func copyFile(_ notification: NSNotification) {
  321. guard let userInfo = notification.userInfo as NSDictionary?,
  322. let serverUrlTo = userInfo["serverUrlTo"] as? String,
  323. serverUrlTo == self.serverUrl
  324. else { return }
  325. reloadDataSource()
  326. }
  327. @objc func renameFile(_ notification: NSNotification) {
  328. if isSearching {
  329. reloadDataSourceNetwork()
  330. } else {
  331. reloadDataSource()
  332. }
  333. }
  334. @objc func createFolder(_ notification: NSNotification) {
  335. guard let userInfo = notification.userInfo as NSDictionary?,
  336. let ocId = userInfo["ocId"] as? String,
  337. let serverUrl = userInfo["serverUrl"] as? String,
  338. serverUrl == self.serverUrl,
  339. let account = userInfo["account"] as? String,
  340. account == appDelegate.account,
  341. let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId)
  342. else { return }
  343. pushMetadata(metadata)
  344. }
  345. @objc func favoriteFile(_ notification: NSNotification) {
  346. guard let userInfo = notification.userInfo as NSDictionary?,
  347. let ocId = userInfo["ocId"] as? String,
  348. let serverUrl = userInfo["serverUrl"] as? String,
  349. serverUrl == self.serverUrl
  350. else { return }
  351. dataSource.reloadMetadata(ocId: ocId)
  352. collectionView?.reloadData()
  353. }
  354. @objc func downloadStartFile(_ notification: NSNotification) {
  355. guard let userInfo = notification.userInfo as NSDictionary?,
  356. let ocId = userInfo["ocId"] as? String,
  357. let serverUrl = userInfo["serverUrl"] as? String,
  358. serverUrl == self.serverUrl,
  359. let account = userInfo["account"] as? String,
  360. account == appDelegate.account
  361. else { return }
  362. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  363. if let indexPath = indexPath {
  364. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  365. collectionView?.reloadItems(at: [indexPath])
  366. } else {
  367. self.collectionView?.reloadData()
  368. }
  369. } else {
  370. reloadDataSource()
  371. }
  372. }
  373. @objc func downloadedFile(_ notification: NSNotification) {
  374. guard let userInfo = notification.userInfo as NSDictionary?,
  375. let ocId = userInfo["ocId"] as? String,
  376. let serverUrl = userInfo["serverUrl"] as? String,
  377. serverUrl == self.serverUrl,
  378. let account = userInfo["account"] as? String,
  379. account == appDelegate.account
  380. else { return }
  381. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  382. if let indexPath = indexPath {
  383. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  384. collectionView?.reloadItems(at: [indexPath])
  385. } else {
  386. self.collectionView?.reloadData()
  387. }
  388. } else {
  389. reloadDataSource()
  390. }
  391. }
  392. @objc func downloadCancelFile(_ notification: NSNotification) {
  393. guard let userInfo = notification.userInfo as NSDictionary?,
  394. let ocId = userInfo["ocId"] as? String,
  395. let serverUrl = userInfo["serverUrl"] as? String,
  396. serverUrl == self.serverUrl,
  397. let account = userInfo["account"] as? String,
  398. account == appDelegate.account
  399. else { return }
  400. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: ocId)
  401. if let indexPath = indexPath {
  402. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  403. collectionView?.reloadItems(at: [indexPath])
  404. } else {
  405. self.collectionView?.reloadData()
  406. }
  407. } else {
  408. reloadDataSource()
  409. }
  410. }
  411. @objc func uploadStartFile(_ notification: NSNotification) {
  412. guard let userInfo = notification.userInfo as NSDictionary?,
  413. let ocId = userInfo["ocId"] as? String,
  414. let serverUrl = userInfo["serverUrl"] as? String,
  415. serverUrl == self.serverUrl,
  416. let account = userInfo["account"] as? String,
  417. account == appDelegate.account
  418. else { return }
  419. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
  420. dataSource.addMetadata(metadata)
  421. self.collectionView?.reloadData()
  422. }
  423. @objc func uploadedFile(_ notification: NSNotification) {
  424. guard let userInfo = notification.userInfo as NSDictionary?,
  425. let ocId = userInfo["ocId"] as? String,
  426. let ocIdTemp = userInfo["ocIdTemp"] as? String,
  427. let serverUrl = userInfo["serverUrl"] as? String,
  428. serverUrl == self.serverUrl,
  429. let account = userInfo["account"] as? String,
  430. account == appDelegate.account
  431. else { return }
  432. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) else { return }
  433. if metadata.livePhoto && metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue { return }
  434. let (indexPath, sameSections) = dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  435. if let indexPath = indexPath {
  436. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  437. collectionView?.performBatchUpdates({
  438. collectionView?.reloadItems(at: [indexPath])
  439. }, completion: { _ in
  440. self.collectionView?.reloadData()
  441. })
  442. } else {
  443. self.collectionView?.reloadData()
  444. }
  445. } else {
  446. reloadDataSource()
  447. }
  448. }
  449. @objc func uploadCancelFile(_ notification: NSNotification) {
  450. guard let userInfo = notification.userInfo as NSDictionary?,
  451. let ocId = userInfo["ocId"] as? String,
  452. let serverUrl = userInfo["serverUrl"] as? String,
  453. serverUrl == self.serverUrl,
  454. let account = userInfo["account"] as? String,
  455. account == appDelegate.account
  456. else { return }
  457. let (indexPath, sameSections) = dataSource.deleteMetadata(ocId: ocId)
  458. if let indexPath = indexPath {
  459. if sameSections && (indexPath.section < collectionView.numberOfSections && indexPath.row < collectionView.numberOfItems(inSection: indexPath.section)) {
  460. collectionView?.performBatchUpdates({
  461. collectionView?.deleteItems(at: [indexPath])
  462. }, completion: { _ in
  463. self.collectionView?.reloadData()
  464. })
  465. } else {
  466. self.collectionView?.reloadData()
  467. }
  468. } else {
  469. reloadDataSource()
  470. }
  471. }
  472. @objc func triggerProgressTask(_ notification: NSNotification) {
  473. guard let userInfo = notification.userInfo as NSDictionary?,
  474. let progressNumber = userInfo["progress"] as? NSNumber,
  475. let totalBytes = userInfo["totalBytes"] as? Int64,
  476. let totalBytesExpected = userInfo["totalBytesExpected"] as? Int64,
  477. let ocId = userInfo["ocId"] as? String,
  478. let (indexPath, _) = self.dataSource.getIndexPathMetadata(ocId: ocId) as? (IndexPath, NCMetadataForSection?)
  479. else { return }
  480. let status = userInfo["status"] as? Int ?? NCGlobal.shared.metadataStatusNormal
  481. if let cell = collectionView?.cellForItem(at: indexPath) {
  482. if let cell = cell as? NCCellProtocol {
  483. if progressNumber.floatValue == 1 && !(cell is NCTransferCell) {
  484. cell.fileProgressView?.isHidden = true
  485. cell.fileProgressView?.progress = .zero
  486. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  487. if let metadata = NCManageDatabase.shared.getMetadataFromOcId(ocId) {
  488. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  489. } else {
  490. cell.fileInfoLabel?.text = ""
  491. }
  492. } else {
  493. cell.fileProgressView?.isHidden = false
  494. cell.fileProgressView?.progress = progressNumber.floatValue
  495. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  496. if status == NCGlobal.shared.metadataStatusInDownload {
  497. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  498. } else if status == NCGlobal.shared.metadataStatusInUpload {
  499. if totalBytes > 0 {
  500. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  501. } else {
  502. cell.fileInfoLabel?.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ …"
  503. }
  504. }
  505. }
  506. }
  507. }
  508. }
  509. // MARK: - Layout
  510. @objc func setNavigationItem() {
  511. self.setNavigationHeader()
  512. guard !isEditMode, layoutKey == NCGlobal.shared.layoutViewFiles else { return }
  513. // PROFILE BUTTON
  514. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  515. let image = NCUtility.shared.loadUserImage(
  516. for: appDelegate.user,
  517. displayName: activeAccount?.displayName,
  518. userBaseUrl: appDelegate)
  519. let button = UIButton(type: .custom)
  520. button.setImage(image, for: .normal)
  521. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(account: appDelegate.account) {
  522. var titleButton = " "
  523. if getNavigationTitle() == activeAccount?.alias {
  524. titleButton = ""
  525. } else {
  526. titleButton += activeAccount?.displayName ?? ""
  527. }
  528. button.setTitle(titleButton, for: .normal)
  529. button.setTitleColor(.systemBlue, for: .normal)
  530. }
  531. button.semanticContentAttribute = .forceLeftToRight
  532. button.sizeToFit()
  533. button.action(for: .touchUpInside) { _ in
  534. let accounts = NCManageDatabase.shared.getAllAccountOrderAlias()
  535. if accounts.count > 0 && !NCBrandOptions.shared.disable_multiaccount && !NCBrandOptions.shared.disable_manage_account {
  536. if let vcAccountRequest = UIStoryboard(name: "NCAccountRequest", bundle: nil).instantiateInitialViewController() as? NCAccountRequest {
  537. vcAccountRequest.activeAccount = NCManageDatabase.shared.getActiveAccount()
  538. vcAccountRequest.accounts = accounts
  539. vcAccountRequest.enableTimerProgress = false
  540. vcAccountRequest.enableAddAccount = true
  541. vcAccountRequest.delegate = self
  542. vcAccountRequest.dismissDidEnterBackground = true
  543. let screenHeighMax = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/5)
  544. let numberCell = accounts.count + 1
  545. let height = min(CGFloat(numberCell * Int(vcAccountRequest.heightCell) + 45), screenHeighMax)
  546. let popup = NCPopupViewController(contentController: vcAccountRequest, popupWidth: 300, popupHeight: height)
  547. UIApplication.shared.keyWindow?.rootViewController?.present(popup, animated: true)
  548. }
  549. // TIP
  550. self.dismissTip()
  551. }
  552. }
  553. navigationItem.setLeftBarButton(UIBarButtonItem(customView: button), animated: true)
  554. navigationItem.leftItemsSupplementBackButton = true
  555. }
  556. func getNavigationTitle() -> String {
  557. let activeAccount = NCManageDatabase.shared.getActiveAccount()
  558. guard let userAlias = activeAccount?.alias, !userAlias.isEmpty else {
  559. return NCBrandOptions.shared.brand
  560. }
  561. return userAlias
  562. }
  563. // MARK: - Empty
  564. func emptyDataSetView(_ view: NCEmptyView) {
  565. self.emptyDataSet?.setOffset(getHeaderHeight())
  566. if isSearching {
  567. view.emptyImage.image = UIImage(named: "search")?.image(color: .gray, size: UIScreen.main.bounds.width)
  568. if isReloadDataSourceNetworkInProgress {
  569. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  570. } else {
  571. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  572. }
  573. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  574. } else if isReloadDataSourceNetworkInProgress {
  575. view.emptyImage.image = UIImage(named: "networkInProgress")?.image(color: .gray, size: UIScreen.main.bounds.width)
  576. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  577. view.emptyDescription.text = ""
  578. } else {
  579. if serverUrl == "" {
  580. view.emptyImage.image = emptyImage
  581. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  582. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  583. } else {
  584. view.emptyImage.image = UIImage(named: "folder")?.image(color: NCBrandColor.shared.brandElement, size: UIScreen.main.bounds.width)
  585. view.emptyTitle.text = NSLocalizedString("_files_no_files_", comment: "")
  586. view.emptyDescription.text = NSLocalizedString("_no_file_pull_down_", comment: "")
  587. }
  588. }
  589. }
  590. // MARK: - SEARCH
  591. func updateSearchResults(for searchController: UISearchController) {
  592. self.literalSearch = searchController.searchBar.text
  593. }
  594. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  595. self.isSearching = true
  596. self.providers?.removeAll()
  597. self.dataSource.clearDataSource()
  598. self.collectionView.reloadData()
  599. // TIP
  600. self.tipView?.dismiss()
  601. }
  602. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  603. if self.isSearching && self.literalSearch?.count ?? 0 >= 2 {
  604. reloadDataSourceNetwork()
  605. }
  606. }
  607. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  608. DispatchQueue.global().async {
  609. NCNetworking.shared.cancelUnifiedSearchFiles()
  610. self.isSearching = false
  611. self.literalSearch = ""
  612. self.providers?.removeAll()
  613. self.dataSource.clearDataSource()
  614. self.reloadDataSource()
  615. }
  616. }
  617. // MARK: - TAP EVENT
  618. func accountRequestChangeAccount(account: String) {
  619. NCManageDatabase.shared.setAccountActive(account)
  620. if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
  621. NCOperationQueue.shared.cancelAllQueue()
  622. NCNetworking.shared.cancelAllTask()
  623. appDelegate.settingAccount(activeAccount.account, urlBase: activeAccount.urlBase, user: activeAccount.user, userId: activeAccount.userId, password: CCUtility.getPassword(activeAccount.account))
  624. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterInitialize)
  625. }
  626. }
  627. func accountRequestAddAccount() {
  628. appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
  629. }
  630. func tapButtonSwitch(_ sender: Any) {
  631. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  632. // list layout
  633. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  634. layoutForView?.layout = NCGlobal.shared.layoutList
  635. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  636. self.groupByField = "name"
  637. if self.dataSource.groupByField != self.groupByField {
  638. self.dataSource.changeGroupByField(self.groupByField)
  639. }
  640. self.collectionView.reloadData()
  641. self.collectionView.collectionViewLayout.invalidateLayout()
  642. self.collectionView.setCollectionViewLayout(self.listLayout, animated: true)
  643. } else {
  644. // grid layout
  645. headerMenu?.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  646. layoutForView?.layout = NCGlobal.shared.layoutGrid
  647. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layoutForView?.layout)
  648. if self.isSearching {
  649. self.groupByField = "name"
  650. } else {
  651. self.groupByField = "classFile"
  652. }
  653. if self.dataSource.groupByField != self.groupByField {
  654. self.dataSource.changeGroupByField(self.groupByField)
  655. }
  656. self.collectionView.reloadData()
  657. self.collectionView.collectionViewLayout.invalidateLayout()
  658. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: true)
  659. }
  660. }
  661. func tapButtonOrder(_ sender: Any) {
  662. let sortMenu = NCSortMenu()
  663. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  664. }
  665. func tapButton1(_ sender: Any) {
  666. NCAskAuthorization.shared.askAuthorizationPhotoLibrary(viewController: self) { hasPermission in
  667. if hasPermission {
  668. NCPhotosPickerViewController.init(viewController: self, maxSelectedAssets: 0, singleSelectedMode: false)
  669. }
  670. }
  671. }
  672. func tapButton2(_ sender: Any) {
  673. guard !appDelegate.activeServerUrl.isEmpty else { return }
  674. let alertController = UIAlertController.createFolder(serverUrl: appDelegate.activeServerUrl, urlBase: appDelegate)
  675. appDelegate.window?.rootViewController?.present(alertController, animated: true, completion: nil)
  676. }
  677. func tapButton3(_ sender: Any) {
  678. if #available(iOS 13.0, *) {
  679. if let viewController = appDelegate.window?.rootViewController {
  680. NCCreateScanDocument.shared.openScannerDocument(viewController: viewController)
  681. }
  682. }
  683. }
  684. func tapMoreListItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  685. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, image: image, sender: sender)
  686. }
  687. func tapShareListItem(with objectId: String, sender: Any) {
  688. if isEditMode { return }
  689. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  690. NCFunctionCenter.shared.openShare(viewController: self, metadata: metadata, indexPage: .sharing)
  691. }
  692. func tapMoreGridItem(with objectId: String, namedButtonMore: String, image: UIImage?, sender: Any) {
  693. if isEditMode { return }
  694. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(objectId) else { return }
  695. if namedButtonMore == NCGlobal.shared.buttonMoreMore || namedButtonMore == NCGlobal.shared.buttonMoreLock {
  696. toggleMenu(metadata: metadata, imageIcon: image)
  697. } else if namedButtonMore == NCGlobal.shared.buttonMoreStop {
  698. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  699. }
  700. }
  701. func tapRichWorkspace(_ sender: Any) {
  702. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  703. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  704. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  705. viewerRichWorkspace.serverUrl = serverUrl
  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. // VIEW IN FOLDER
  958. if layoutKey == NCGlobal.shared.layoutViewViewInFolder && !pushed {
  959. if let viewController: NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as? NCFileViewInFolder {
  960. viewController.serverUrl = serverUrlPush
  961. viewController.titleCurrentFolder = metadata.fileNameView
  962. pushViewController(viewController: viewController)
  963. }
  964. }
  965. // SHARES ( for push use Files ... he he he )
  966. if layoutKey == NCGlobal.shared.layoutViewShares && !pushed {
  967. if let viewController = appDelegate.listFilesVC[serverUrlPush] {
  968. if viewController.isViewLoaded {
  969. pushViewController(viewController: viewController)
  970. }
  971. } else {
  972. if let viewController: NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as? NCFiles {
  973. viewController.isRoot = false
  974. viewController.serverUrl = serverUrlPush
  975. viewController.titleCurrentFolder = metadata.fileNameView
  976. appDelegate.listFilesVC[serverUrlPush] = viewController
  977. pushViewController(viewController: viewController)
  978. }
  979. }
  980. }
  981. }
  982. }
  983. // MARK: - Collection View
  984. extension NCCollectionViewCommon: UICollectionViewDelegate {
  985. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  986. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  987. appDelegate.activeMetadata = metadata
  988. let metadataSourceForAllSections = dataSource.getMetadataSourceForAllSections()
  989. if isEditMode {
  990. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  991. selectOcId.remove(at: index)
  992. } else {
  993. selectOcId.append(metadata.ocId)
  994. }
  995. collectionView.reloadItems(at: [indexPath])
  996. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(metadataSourceForAllSections.count)"
  997. return
  998. }
  999. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  1000. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorE2EENotEnabled)
  1001. return
  1002. }
  1003. if metadata.directory {
  1004. pushMetadata(metadata)
  1005. } else if !(self is NCFileViewInFolder) {
  1006. let imageIcon = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1007. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  1008. var metadatas: [tableMetadata] = []
  1009. for metadata in metadataSourceForAllSections {
  1010. if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.audio.rawValue {
  1011. metadatas.append(metadata)
  1012. }
  1013. }
  1014. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: metadatas, imageIcon: imageIcon)
  1015. return
  1016. }
  1017. if CCUtility.fileProviderStorageExists(metadata) {
  1018. NCViewer.shared.view(viewController: self, metadata: metadata, metadatas: [metadata], imageIcon: imageIcon)
  1019. } else if NCCommunication.shared.isNetworkReachable() {
  1020. NCNetworking.shared.download(metadata: metadata, selector: NCGlobal.shared.selectorLoadFileView) { _ in }
  1021. } else {
  1022. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorOffline)
  1023. }
  1024. }
  1025. }
  1026. func pushViewController(viewController: UIViewController) {
  1027. if pushed { return }
  1028. pushed = true
  1029. navigationController?.pushViewController(viewController, animated: true)
  1030. }
  1031. @available(iOS 13.0, *)
  1032. func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1033. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  1034. if isEditMode || metadata.classFile == NCCommunicationCommon.typeClassFile.url.rawValue { return nil }
  1035. let identifier = indexPath as NSCopying
  1036. var image: UIImage?
  1037. let cell = collectionView.cellForItem(at: indexPath)
  1038. if cell is NCListCell {
  1039. image = (cell as! NCListCell).imageItem.image
  1040. } else if cell is NCGridCell {
  1041. image = (cell as! NCGridCell).imageItem.image
  1042. }
  1043. return UIContextMenuConfiguration(identifier: identifier, previewProvider: {
  1044. return NCViewerProviderContextMenu(metadata: metadata, image: image)
  1045. }, actionProvider: { _ in
  1046. return NCFunctionCenter.shared.contextMenuConfiguration(ocId: metadata.ocId, viewController: self, enableDeleteLocal: true, enableViewInFolder: false, image: image)
  1047. })
  1048. }
  1049. @available(iOS 13.0, *)
  1050. func collectionView(_ collectionView: UICollectionView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) {
  1051. animator.addCompletion {
  1052. if let indexPath = configuration.identifier as? IndexPath {
  1053. self.collectionView(collectionView, didSelectItemAt: indexPath)
  1054. }
  1055. }
  1056. }
  1057. }
  1058. extension NCCollectionViewCommon: UICollectionViewDataSource {
  1059. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  1060. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  1061. // Thumbnail
  1062. if !metadata.directory {
  1063. if metadata.name == NCGlobal.shared.appName {
  1064. let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  1065. let iconImagePath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  1066. if FileManager().fileExists(atPath: iconImagePath) {
  1067. (cell as! NCCellProtocol).filePreviewImageView?.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1068. } else if metadata.status > NCGlobal.shared.metadataStatusNormal && metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue && FileManager().fileExists(atPath: filePath) {
  1069. 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) {
  1070. do {
  1071. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  1072. (cell as! NCCellProtocol).filePreviewImageView?.image = image
  1073. } catch { }
  1074. }
  1075. } else if metadata.status > NCGlobal.shared.metadataStatusNormal && metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue && FileManager().fileExists(atPath: filePath) {
  1076. 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) {
  1077. do {
  1078. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  1079. (cell as! NCCellProtocol).filePreviewImageView?.image = image
  1080. } catch { }
  1081. }
  1082. } else {
  1083. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, placeholder: true, cell: cell, view: collectionView)
  1084. }
  1085. } else {
  1086. // Unified search
  1087. switch metadata.iconName {
  1088. case let str where str.contains("contacts"):
  1089. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconContacts
  1090. case let str where str.contains("conversation"):
  1091. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1092. case let str where str.contains("calendar"):
  1093. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconCalendar
  1094. case let str where str.contains("deck"):
  1095. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconDeck
  1096. case let str where str.contains("mail"):
  1097. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconMail
  1098. case let str where str.contains("talk"):
  1099. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconTalk
  1100. case let str where str.contains("confirm"):
  1101. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconConfirm
  1102. case let str where str.contains("pages"):
  1103. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.iconPages
  1104. default:
  1105. (cell as! NCCellProtocol).filePreviewImageView?.image = NCBrandColor.cacheImages.file
  1106. }
  1107. if !metadata.iconUrl.isEmpty {
  1108. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata), let cell = cell as? NCCellProtocol {
  1109. let fileName = metadata.userBaseUrl + "-" + ownerId + ".png"
  1110. NCOperationQueue.shared.downloadAvatar(user: ownerId, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1111. }
  1112. }
  1113. // if metadata.iconName.contains("contacts"), let subline = metadata.subline, !subline.isEmpty, let cell = cell as? NCCellProtocol {
  1114. // let components = subline.components(separatedBy: "@")
  1115. // if let user = components.first {
  1116. // let fileName = metadata.userBaseUrl + "-" + user + ".png"
  1117. // NCOperationQueue.shared.downloadAvatar(user: user, dispalyName: nil, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.filePreviewImageView)
  1118. // }
  1119. // }
  1120. }
  1121. }
  1122. // Avatar
  1123. if metadata.ownerId.count > 0,
  1124. metadata.ownerId != appDelegate.userId,
  1125. appDelegate.account == metadata.account,
  1126. let cell = cell as? NCCellProtocol {
  1127. let fileName = metadata.userBaseUrl + "-" + metadata.ownerId + ".png"
  1128. NCOperationQueue.shared.downloadAvatar(user: metadata.ownerId, dispalyName: metadata.ownerDisplayName, fileName: fileName, cell: cell, view: collectionView, cellImageView: cell.fileAvatarImageView)
  1129. }
  1130. }
  1131. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { }
  1132. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1133. return dataSource.numberOfSections()
  1134. }
  1135. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1136. let numberItems = dataSource.numberOfItemsInSection(section)
  1137. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1138. return numberItems
  1139. }
  1140. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1141. var cell: NCCellProtocol & UICollectionViewCell
  1142. // LAYOUT LIST
  1143. if layoutForView?.layout == NCGlobal.shared.layoutList {
  1144. guard let listCell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as? NCListCell else { return UICollectionViewCell() }
  1145. listCell.delegate = self
  1146. cell = listCell
  1147. } else {
  1148. // LAYOUT GRID
  1149. guard let gridCell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as? NCGridCell else { return UICollectionViewCell() }
  1150. gridCell.delegate = self
  1151. cell = gridCell
  1152. }
  1153. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return cell }
  1154. let tableShare = dataSource.metadatasForSection[indexPath.section].metadataShare[metadata.ocId]
  1155. let tableDirectory = dataSource.metadatasForSection[indexPath.section].directories?.filter({ $0.ocId == metadata.ocId }).first
  1156. var isShare = false
  1157. var isMounted = false
  1158. var a11yValues: [String] = []
  1159. if metadataFolder != nil {
  1160. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  1161. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  1162. }
  1163. cell.fileSelectImage?.image = nil
  1164. cell.fileStatusImage?.image = nil
  1165. cell.fileLocalImage?.image = nil
  1166. cell.fileFavoriteImage?.image = nil
  1167. cell.fileSharedImage?.image = nil
  1168. cell.fileMoreImage?.image = nil
  1169. cell.filePreviewImageView?.image = nil
  1170. cell.filePreviewImageView?.backgroundColor = nil
  1171. cell.fileObjectId = metadata.ocId
  1172. cell.fileUser = metadata.ownerId
  1173. cell.fileProgressView?.isHidden = true
  1174. cell.fileProgressView?.progress = 0.0
  1175. cell.hideButtonShare(false)
  1176. cell.hideButtonMore(false)
  1177. cell.titleInfoTrailingDefault()
  1178. if isSearching {
  1179. cell.fileTitleLabel?.text = metadata.fileName
  1180. cell.fileTitleLabel?.lineBreakMode = .byTruncatingTail
  1181. if metadata.name == NCGlobal.shared.appName {
  1182. cell.fileInfoLabel?.text = NSLocalizedString("_in_", comment: "") + " " + NCUtilityFileSystem.shared.getPath(metadata: metadata, withFileName: false)
  1183. } else {
  1184. cell.fileInfoLabel?.text = metadata.subline
  1185. cell.titleInfoTrailingFull()
  1186. }
  1187. } else {
  1188. cell.fileTitleLabel?.text = metadata.fileNameView
  1189. cell.fileTitleLabel?.lineBreakMode = .byTruncatingMiddle
  1190. cell.writeInfoDateSize(date: metadata.date, size: metadata.size)
  1191. }
  1192. if metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1193. cell.fileProgressView?.isHidden = false
  1194. }
  1195. // Accessibility [shared]
  1196. if metadata.ownerId != appDelegate.userId, appDelegate.account == metadata.account {
  1197. a11yValues.append(NSLocalizedString("_shared_with_you_by_", comment: "") + " " + metadata.ownerDisplayName)
  1198. }
  1199. if metadata.directory {
  1200. if metadata.e2eEncrypted {
  1201. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderEncrypted
  1202. } else if isShare {
  1203. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderSharedWithMe
  1204. } else if tableShare != nil && tableShare?.shareType != 3 {
  1205. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderSharedWithMe
  1206. } else if tableShare != nil && tableShare?.shareType == 3 {
  1207. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderPublic
  1208. } else if metadata.mountType == "group" {
  1209. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderGroup
  1210. } else if isMounted {
  1211. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderExternal
  1212. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1213. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folderAutomaticUpload
  1214. if cell is NCListCell {
  1215. cell.fileTitleLabel?.text = (cell.fileTitleLabel?.text ?? "") + " - " + NSLocalizedString("_auto_upload_folder_", comment: "")
  1216. }
  1217. } else {
  1218. cell.filePreviewImageView?.image = NCBrandColor.cacheImages.folder
  1219. }
  1220. // Local image: offline
  1221. if let tableDirectory = tableDirectory, tableDirectory.offline {
  1222. cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag
  1223. }
  1224. // color folder
  1225. cell.filePreviewImageView?.image = cell.filePreviewImageView?.image?.colorizeFolder(metadata: metadata, tableDirectory: tableDirectory)
  1226. } else {
  1227. // image local
  1228. if dataSource.metadatasForSection[indexPath.section].metadataOffLine.contains(metadata.ocId) {
  1229. a11yValues.append(NSLocalizedString("_offline_", comment: ""))
  1230. cell.fileLocalImage?.image = NCBrandColor.cacheImages.offlineFlag
  1231. } else if CCUtility.fileProviderStorageExists(metadata) {
  1232. cell.fileLocalImage?.image = NCBrandColor.cacheImages.local
  1233. }
  1234. }
  1235. // image Favorite
  1236. if metadata.favorite {
  1237. cell.fileFavoriteImage?.image = NCBrandColor.cacheImages.favorite
  1238. a11yValues.append(NSLocalizedString("_favorite_", comment: ""))
  1239. }
  1240. // Share image
  1241. if isShare {
  1242. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1243. } else if tableShare != nil && tableShare?.shareType == 3 {
  1244. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shareByLink
  1245. } else if tableShare != nil && tableShare?.shareType != 3 {
  1246. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1247. } else {
  1248. cell.fileSharedImage?.image = NCBrandColor.cacheImages.canShare
  1249. }
  1250. if appDelegate.account != metadata.account {
  1251. cell.fileSharedImage?.image = NCBrandColor.cacheImages.shared
  1252. }
  1253. // Button More
  1254. if metadata.status == NCGlobal.shared.metadataStatusInDownload || metadata.status == NCGlobal.shared.metadataStatusDownloading || metadata.status == NCGlobal.shared.metadataStatusInUpload || metadata.status == NCGlobal.shared.metadataStatusUploading {
  1255. cell.setButtonMore(named: NCGlobal.shared.buttonMoreStop, image: NCBrandColor.cacheImages.buttonStop)
  1256. } else if metadata.lock == true {
  1257. cell.setButtonMore(named: NCGlobal.shared.buttonMoreLock, image: NCBrandColor.cacheImages.buttonMoreLock)
  1258. a11yValues.append(String(format: NSLocalizedString("_locked_by_", comment: ""), metadata.lockOwnerDisplayName))
  1259. } else {
  1260. cell.setButtonMore(named: NCGlobal.shared.buttonMoreMore, image: NCBrandColor.cacheImages.buttonMore)
  1261. }
  1262. // Write status on Label Info
  1263. switch metadata.status {
  1264. case NCGlobal.shared.metadataStatusWaitDownload:
  1265. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1266. break
  1267. case NCGlobal.shared.metadataStatusInDownload:
  1268. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1269. break
  1270. case NCGlobal.shared.metadataStatusDownloading:
  1271. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↓ …"
  1272. break
  1273. case NCGlobal.shared.metadataStatusWaitUpload:
  1274. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1275. break
  1276. case NCGlobal.shared.metadataStatusInUpload:
  1277. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1278. break
  1279. case NCGlobal.shared.metadataStatusUploading:
  1280. cell.fileInfoLabel?.text = CCUtility.transformedSize(metadata.size) + " - ↑ …"
  1281. break
  1282. case NCGlobal.shared.metadataStatusUploadError:
  1283. if metadata.sessionError != "" {
  1284. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "") + " " + metadata.sessionError
  1285. } else {
  1286. cell.fileInfoLabel?.text = NSLocalizedString("_status_wait_upload_", comment: "")
  1287. }
  1288. break
  1289. default:
  1290. break
  1291. }
  1292. // Live Photo
  1293. if metadata.livePhoto {
  1294. cell.fileStatusImage?.image = NCBrandColor.cacheImages.livePhoto
  1295. a11yValues.append(NSLocalizedString("_upload_mov_livephoto_", comment: ""))
  1296. }
  1297. // E2EE
  1298. if metadata.e2eEncrypted || isEncryptedFolder {
  1299. cell.hideButtonShare(true)
  1300. }
  1301. // URL
  1302. if metadata.classFile == NCCommunicationCommon.typeClassFile.url.rawValue {
  1303. cell.fileLocalImage?.image = nil
  1304. cell.hideButtonShare(true)
  1305. cell.hideButtonMore(true)
  1306. if let ownerId = NCUtility.shared.getAvatarFromIconUrl(metadata: metadata) {
  1307. cell.fileUser = ownerId
  1308. }
  1309. }
  1310. // Disable Share Button
  1311. if appDelegate.disableSharesView {
  1312. cell.hideButtonShare(true)
  1313. }
  1314. // Separator
  1315. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 || isSearching {
  1316. cell.cellSeparatorView?.isHidden = true
  1317. } else {
  1318. cell.cellSeparatorView?.isHidden = false
  1319. }
  1320. // Edit mode
  1321. if isEditMode {
  1322. cell.selectMode(true)
  1323. if selectOcId.contains(metadata.ocId) {
  1324. cell.selected(true)
  1325. a11yValues.append(NSLocalizedString("_selected_", comment: ""))
  1326. } else {
  1327. cell.selected(false)
  1328. }
  1329. } else {
  1330. cell.selectMode(false)
  1331. }
  1332. // Accessibility
  1333. cell.setAccessibility(label: metadata.fileNameView + ", " + (cell.fileInfoLabel?.text ?? ""), value: a11yValues.joined(separator: ", "))
  1334. // Color string find in search
  1335. if isSearching, let literalSearch = self.literalSearch, let title = cell.fileTitleLabel?.text {
  1336. let longestWordRange = (title.lowercased() as NSString).range(of: literalSearch)
  1337. let attributedString = NSMutableAttributedString(string: title, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15)])
  1338. attributedString.setAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 15), NSAttributedString.Key.foregroundColor : NCBrandColor.shared.annotationColor], range: longestWordRange)
  1339. cell.fileTitleLabel?.attributedText = attributedString
  1340. }
  1341. return cell
  1342. }
  1343. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  1344. if kind == UICollectionView.elementKindSectionHeader {
  1345. if indexPath.section == 0 {
  1346. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  1347. let (_, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: indexPath.section)
  1348. self.headerMenu = header
  1349. if layoutForView?.layout == NCGlobal.shared.layoutGrid {
  1350. header.setImageSwitchList()
  1351. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_list_view_", comment: "")
  1352. } else {
  1353. header.setImageSwitchGrid()
  1354. header.buttonSwitch.accessibilityLabel = NSLocalizedString("_grid_view_", comment: "")
  1355. }
  1356. header.delegate = self
  1357. if headerMenuButtonsCommand && !isSearching {
  1358. 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: ""))
  1359. } else {
  1360. header.setButtonsCommand(heigt: 0)
  1361. }
  1362. if headerMenuButtonsView {
  1363. header.setStatusButtonsView(enable: !dataSource.getMetadataSourceForAllSections().isEmpty)
  1364. header.setButtonsView(heigt: NCGlobal.shared.heightButtonsView)
  1365. header.setSortedTitle(layoutForView?.titleButtonHeader ?? "")
  1366. } else {
  1367. header.setButtonsView(heigt: 0)
  1368. }
  1369. header.setRichWorkspaceHeight(heightHeaderRichWorkspace)
  1370. header.setRichWorkspaceText(richWorkspaceText)
  1371. header.setSectionHeight(heightHeaderSection)
  1372. if heightHeaderSection == 0 {
  1373. header.labelSection.text = ""
  1374. } else {
  1375. header.labelSection.text = self.dataSource.getSectionValue(indexPath: indexPath)
  1376. }
  1377. header.labelSection.textColor = NCBrandColor.shared.label
  1378. return header
  1379. } else {
  1380. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) as! NCSectionHeader
  1381. header.labelSection.text = self.dataSource.getSectionValue(indexPath: indexPath)
  1382. header.labelSection.textColor = NCBrandColor.shared.label
  1383. return header
  1384. }
  1385. } else {
  1386. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1387. let sections = dataSource.numberOfSections()
  1388. let section = indexPath.section
  1389. let metadataForSection = self.dataSource.getMetadataForSection(indexPath.section)
  1390. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1391. let metadatasCount: Int = metadataForSection?.metadatas.count ?? 0
  1392. let unifiedSearchInProgress = metadataForSection?.unifiedSearchInProgress ?? false
  1393. footer.delegate = self
  1394. footer.metadataForSection = metadataForSection
  1395. footer.setTitleLabel("")
  1396. footer.setButtonText(NSLocalizedString("_show_more_results_", comment: ""))
  1397. footer.separatorIsHidden(true)
  1398. footer.buttonIsHidden(true)
  1399. footer.hideActivityIndicatorSection()
  1400. if isSearching {
  1401. if sections > 1 && section != sections - 1 {
  1402. footer.separatorIsHidden(false)
  1403. }
  1404. if isSearching && isPaginated && metadatasCount > 0 {
  1405. footer.buttonIsHidden(false)
  1406. }
  1407. if unifiedSearchInProgress {
  1408. footer.showActivityIndicatorSection()
  1409. }
  1410. } else {
  1411. if sections == 1 || section == sections - 1 {
  1412. let info = dataSource.getFooterInformationAllMetadatas()
  1413. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size)
  1414. } else {
  1415. footer.separatorIsHidden(false)
  1416. }
  1417. }
  1418. return footer
  1419. }
  1420. }
  1421. }
  1422. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1423. func getHeaderHeight() -> CGFloat {
  1424. var size: CGFloat = 0
  1425. if headerMenuButtonsCommand && !isSearching {
  1426. size += NCGlobal.shared.heightButtonsCommand
  1427. }
  1428. if headerMenuButtonsView {
  1429. size += NCGlobal.shared.heightButtonsView
  1430. }
  1431. return size
  1432. }
  1433. func getHeaderHeight(section:Int) -> (heightHeaderCommands: CGFloat, heightHeaderRichWorkspace: CGFloat, heightHeaderSection: CGFloat) {
  1434. var headerRichWorkspace: CGFloat = 0
  1435. if let richWorkspaceText = richWorkspaceText, !headerRichWorkspaceDisable {
  1436. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1437. if trimmed.count > 0 && !isSearching {
  1438. headerRichWorkspace = UIScreen.main.bounds.size.height / 6
  1439. }
  1440. }
  1441. if isSearching || layoutForView?.layout == NCGlobal.shared.layoutGrid || dataSource.numberOfSections() > 1 {
  1442. if section == 0 {
  1443. return (getHeaderHeight(), headerRichWorkspace, NCGlobal.shared.heightSection)
  1444. } else {
  1445. return (0, 0, NCGlobal.shared.heightSection)
  1446. }
  1447. } else {
  1448. return (getHeaderHeight(), headerRichWorkspace, 0)
  1449. }
  1450. }
  1451. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1452. let (heightHeaderCommands, heightHeaderRichWorkspace, heightHeaderSection) = getHeaderHeight(section: section)
  1453. let heightHeader = heightHeaderCommands + heightHeaderRichWorkspace + heightHeaderSection
  1454. return CGSize(width: collectionView.frame.width, height: heightHeader)
  1455. }
  1456. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1457. let sections = dataSource.numberOfSections()
  1458. let metadataForSection = self.dataSource.getMetadataForSection(section)
  1459. let isPaginated = metadataForSection?.lastSearchResult?.isPaginated ?? false
  1460. let metadatasCount: Int = metadataForSection?.lastSearchResult?.entries.count ?? 0
  1461. var size = CGSize(width: collectionView.frame.width, height: 0)
  1462. if section == sections - 1 {
  1463. size.height += NCGlobal.shared.endHeightFooter
  1464. } else {
  1465. size.height += NCGlobal.shared.heightFooter
  1466. }
  1467. if isSearching && isPaginated && metadatasCount > 0 {
  1468. size.height += NCGlobal.shared.heightFooterButton
  1469. }
  1470. return size
  1471. }
  1472. }
  1473. extension NCCollectionViewCommon: EasyTipViewDelegate {
  1474. func easyTipViewDidTap(_ tipView: EasyTipView) {
  1475. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1476. }
  1477. func easyTipViewDidDismiss(_ tipView: EasyTipView) { }
  1478. func dismissTip() {
  1479. NCManageDatabase.shared.addTip(NCGlobal.shared.tipNCCollectionViewCommonAccountRequest)
  1480. self.tipView?.dismiss()
  1481. }
  1482. }