NCCollectionViewCommon.swift 89 KB

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