NCCollectionViewCommon.swift 91 KB

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