NCCollectionViewCommon.swift 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  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 Foundation
  24. import NCCommunication
  25. class NCCollectionViewCommon: UIViewController, UIGestureRecognizerDelegate, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, NCListCellDelegate, NCGridCellDelegate, NCSectionHeaderMenuDelegate, UIAdaptivePresentationControllerDelegate, NCEmptyDataSetDelegate {
  26. @IBOutlet weak var collectionView: UICollectionView!
  27. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  28. internal let refreshControl = UIRefreshControl()
  29. internal var searchController: UISearchController?
  30. internal var emptyDataSet: NCEmptyDataSet?
  31. internal var serverUrl: String = ""
  32. internal var isEncryptedFolder = false
  33. internal var isEditMode = false
  34. internal var selectOcId: [String] = []
  35. internal var metadatasSource: [tableMetadata] = []
  36. internal var metadataFolder: tableMetadata?
  37. internal var metadataTouch: tableMetadata?
  38. internal var dataSource = NCDataSource()
  39. internal var richWorkspaceText: String?
  40. internal var layout = ""
  41. internal var sort: String = ""
  42. internal var ascending: Bool = true
  43. internal var directoryOnTop: Bool = true
  44. internal var groupBy = ""
  45. internal var titleButton = ""
  46. internal var itemForLine = 0
  47. private var autoUploadFileName = ""
  48. private var autoUploadDirectory = ""
  49. internal var listLayout: NCListLayout!
  50. internal var gridLayout: NCGridLayout!
  51. private let headerHeight: CGFloat = 50
  52. private var headerRichWorkspaceHeight: CGFloat = 0
  53. private let footerHeight: CGFloat = 100
  54. private var timerInputSearch: Timer?
  55. internal var literalSearch: String?
  56. internal var isSearching: Bool = false
  57. internal var isReloadDataSourceNetworkInProgress: Bool = false
  58. var photos: [UIImage] = []
  59. var selectedIndexPath: IndexPath!
  60. var currentLeftSafeAreaInset: CGFloat = 0.0
  61. var currentRightSafeAreaInset: CGFloat = 0.0
  62. // DECLARE
  63. internal var layoutKey = ""
  64. internal var titleCurrentFolder = ""
  65. internal var enableSearchBar: Bool = false
  66. internal var emptyImage: UIImage?
  67. internal var emptyTitle: String = ""
  68. internal var emptyDescription: String = ""
  69. required init?(coder aDecoder: NSCoder) {
  70. super.init(coder: aDecoder)
  71. }
  72. override func viewDidLoad() {
  73. super.viewDidLoad()
  74. if enableSearchBar {
  75. searchController = UISearchController(searchResultsController: nil)
  76. searchController?.searchResultsUpdater = self
  77. searchController?.dimsBackgroundDuringPresentation = false
  78. searchController?.delegate = self
  79. searchController?.searchBar.delegate = self
  80. navigationItem.searchController = searchController
  81. navigationItem.hidesSearchBarWhenScrolling = false
  82. }
  83. // Cell
  84. collectionView.register(UINib.init(nibName: "NCListCell", bundle: nil), forCellWithReuseIdentifier: "listCell")
  85. collectionView.register(UINib.init(nibName: "NCGridCell", bundle: nil), forCellWithReuseIdentifier: "gridCell")
  86. collectionView.register(UINib.init(nibName: "NCTransferCell", bundle: nil), forCellWithReuseIdentifier: "transferCell")
  87. // Header
  88. collectionView.register(UINib.init(nibName: "NCSectionHeaderMenu", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "sectionHeaderMenu")
  89. // Footer
  90. collectionView.register(UINib.init(nibName: "NCSectionFooter", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "sectionFooter")
  91. collectionView.alwaysBounceVertical = true
  92. listLayout = NCListLayout()
  93. gridLayout = NCGridLayout()
  94. // Refresh Control
  95. collectionView.addSubview(refreshControl)
  96. refreshControl.tintColor = .gray
  97. refreshControl.addTarget(self, action: #selector(reloadDataSourceNetworkRefreshControl), for: .valueChanged)
  98. // Empty
  99. emptyDataSet = NCEmptyDataSet.init(view: collectionView, offset: 80, delegate: self)
  100. // 3D Touch peek and pop
  101. if traitCollection.forceTouchCapability == .available {
  102. registerForPreviewing(with: self, sourceView: view)
  103. }
  104. // Long Press on CollectionView
  105. let longPressedGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressCollecationView(_:)))
  106. longPressedGesture.minimumPressDuration = 0.5
  107. longPressedGesture.delegate = self
  108. longPressedGesture.delaysTouchesBegan = true
  109. collectionView.addGestureRecognizer(longPressedGesture)
  110. // Notification
  111. NotificationCenter.default.addObserver(self, selector: #selector(initializeMain), name: NSNotification.Name(rawValue: k_notificationCenter_initializeMain), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSource(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSource), object: nil)
  114. NotificationCenter.default.addObserver(self, selector: #selector(reloadDataSourceNetworkForced(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_reloadDataSourceNetworkForced), object: nil)
  115. NotificationCenter.default.addObserver(self, selector: #selector(changeStatusFolderE2EE(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_changeStatusFolderE2EE), object: nil)
  116. NotificationCenter.default.addObserver(self, selector: #selector(closeRichWorkspaceWebView), name: NSNotification.Name(rawValue: k_notificationCenter_closeRichWorkspaceWebView), object: nil)
  117. NotificationCenter.default.addObserver(self, selector: #selector(deleteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_deleteFile), object: nil)
  118. NotificationCenter.default.addObserver(self, selector: #selector(moveFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_moveFile), object: nil)
  119. NotificationCenter.default.addObserver(self, selector: #selector(copyFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_copyFile), object: nil)
  120. NotificationCenter.default.addObserver(self, selector: #selector(renameFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_renameFile), object: nil)
  121. NotificationCenter.default.addObserver(self, selector: #selector(createFolder(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_createFolder), object: nil)
  122. NotificationCenter.default.addObserver(self, selector: #selector(favoriteFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_favoriteFile), object: nil)
  123. NotificationCenter.default.addObserver(self, selector: #selector(downloadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadStartFile), object: nil)
  124. NotificationCenter.default.addObserver(self, selector: #selector(downloadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadedFile), object: nil)
  125. NotificationCenter.default.addObserver(self, selector: #selector(downloadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_downloadCancelFile), object: nil)
  126. NotificationCenter.default.addObserver(self, selector: #selector(uploadStartFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadStartFile), object: nil)
  127. NotificationCenter.default.addObserver(self, selector: #selector(uploadedFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadedFile), object: nil)
  128. NotificationCenter.default.addObserver(self, selector: #selector(uploadCancelFile(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_uploadCancelFile), object: nil)
  129. NotificationCenter.default.addObserver(self, selector: #selector(triggerProgressTask(_:)), name: NSNotification.Name(rawValue: k_notificationCenter_progressTask), object:nil)
  130. changeTheming()
  131. }
  132. override func viewWillAppear(_ animated: Bool) {
  133. super.viewWillAppear(animated)
  134. appDelegate.activeViewController = self
  135. if serverUrl == "" {
  136. appDelegate.activeServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  137. } else {
  138. appDelegate.activeServerUrl = serverUrl
  139. }
  140. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  141. gridLayout.itemForLine = CGFloat(itemForLine)
  142. if layout == k_layout_list {
  143. collectionView?.collectionViewLayout = listLayout
  144. } else {
  145. collectionView?.collectionViewLayout = gridLayout
  146. }
  147. navigationController?.navigationBar.prefersLargeTitles = true
  148. navigationController?.setNavigationBarHidden(false, animated: false)
  149. setNavigationItem()
  150. reloadDataSource()
  151. }
  152. override func viewDidAppear(_ animated: Bool) {
  153. super.viewDidAppear(animated)
  154. reloadDataSourceNetwork()
  155. }
  156. override func viewSafeAreaInsetsDidChange() {
  157. currentLeftSafeAreaInset = view.safeAreaInsets.left
  158. currentRightSafeAreaInset = view.safeAreaInsets.right
  159. }
  160. func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
  161. let viewController = presentationController.presentedViewController
  162. if viewController is NCViewerRichWorkspaceWebView {
  163. closeRichWorkspaceWebView()
  164. } else if viewController is UINavigationController {
  165. if (viewController as! UINavigationController).topViewController is NCFileViewInFolder {
  166. appDelegate.activeFileViewInFolder = nil
  167. }
  168. }
  169. }
  170. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  171. super.viewWillTransition(to: size, with: coordinator)
  172. coordinator.animate(alongsideTransition: nil) { _ in
  173. self.collectionView?.collectionViewLayout.invalidateLayout()
  174. }
  175. }
  176. override var canBecomeFirstResponder: Bool {
  177. return true
  178. }
  179. func setNavigationItem() {
  180. if isEditMode {
  181. navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.init(named: "navigationMore"), style: .plain, target: self, action:#selector(tapSelectMenu(sender:)))
  182. navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: .plain, target: self, action: #selector(tapSelect(sender:)))
  183. navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  184. } else {
  185. navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_select_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(tapSelect(sender:)))
  186. navigationItem.leftBarButtonItem = nil
  187. navigationItem.title = titleCurrentFolder
  188. }
  189. }
  190. // MARK: - NotificationCenter
  191. @objc func initializeMain() {
  192. if appDelegate.account.count == 0 { return }
  193. if searchController?.isActive ?? false {
  194. searchController?.isActive = false
  195. }
  196. // set active serverUrl
  197. if self.view?.window != nil {
  198. if serverUrl == "" {
  199. appDelegate.activeServerUrl = NCUtility.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account)
  200. } else {
  201. appDelegate.activeServerUrl = serverUrl
  202. }
  203. }
  204. self.navigationController?.popToRootViewController(animated: false)
  205. appDelegate.listFilesVC.removeAllObjects()
  206. appDelegate.listFavoriteVC.removeAllObjects()
  207. appDelegate.listOfflineVC.removeAllObjects()
  208. reloadDataSource()
  209. }
  210. @objc func changeTheming() {
  211. view.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  212. collectionView.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  213. collectionView.reloadData()
  214. }
  215. @objc func reloadDataSource(_ notification: NSNotification) {
  216. if self.view?.window == nil { return }
  217. reloadDataSource()
  218. }
  219. @objc func reloadDataSourceNetworkForced(_ notification: NSNotification) {
  220. if self.view?.window == nil { return }
  221. if let userInfo = notification.userInfo as NSDictionary? {
  222. if let serverUrl = userInfo["serverUrl"] as? String {
  223. if serverUrl == self.serverUrl {
  224. reloadDataSourceNetwork(forced: true)
  225. }
  226. }
  227. } else {
  228. reloadDataSourceNetwork(forced: true)
  229. }
  230. }
  231. @objc func changeStatusFolderE2EE(_ notification: NSNotification) {
  232. if self.view?.window == nil { return }
  233. reloadDataSource()
  234. }
  235. @objc func closeRichWorkspaceWebView() {
  236. if self.view?.window == nil { return }
  237. reloadDataSourceNetwork()
  238. }
  239. @objc func deleteFile(_ notification: NSNotification) {
  240. if self.view?.window == nil { return }
  241. if let userInfo = notification.userInfo as NSDictionary? {
  242. if let metadata = userInfo["metadata"] as? tableMetadata, let onlyLocal = userInfo["onlyLocal"] as? Bool {
  243. if onlyLocal {
  244. reloadDataSource()
  245. } else if metadata.fileNameView.lowercased() == k_fileNameRichWorkspace.lowercased() {
  246. reloadDataSourceNetwork(forced: true)
  247. } else {
  248. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  249. let indexPath = IndexPath(row: row, section: 0)
  250. collectionView?.performBatchUpdates({
  251. collectionView?.deleteItems(at: [indexPath])
  252. }, completion: { (_) in
  253. self.collectionView?.reloadData()
  254. })
  255. }
  256. }
  257. }
  258. }
  259. }
  260. @objc func moveFile(_ notification: NSNotification) {
  261. if self.view?.window == nil { return }
  262. if let userInfo = notification.userInfo as NSDictionary? {
  263. if let metadata = userInfo["metadata"] as? tableMetadata, let metadataNew = userInfo["metadataNew"] as? tableMetadata {
  264. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  265. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  266. let indexPath = IndexPath(row: row, section: 0)
  267. collectionView?.performBatchUpdates({
  268. collectionView?.deleteItems(at: [indexPath])
  269. }, completion: { (_) in
  270. self.collectionView?.reloadData()
  271. })
  272. }
  273. } else if metadataNew.serverUrl == serverUrl && metadata.account == appDelegate.account {
  274. if let row = dataSource.addMetadata(metadataNew) {
  275. let indexPath = IndexPath(row: row, section: 0)
  276. collectionView?.performBatchUpdates({
  277. collectionView?.insertItems(at: [indexPath])
  278. }, completion: { (_) in
  279. self.collectionView?.reloadData()
  280. })
  281. }
  282. }
  283. }
  284. }
  285. }
  286. @objc func copyFile(_ notification: NSNotification) {
  287. if self.view?.window == nil { return }
  288. if let userInfo = notification.userInfo as NSDictionary? {
  289. if let serverUrlTo = userInfo["serverUrlTo"] as? String {
  290. if serverUrlTo == self.serverUrl {
  291. reloadDataSource()
  292. }
  293. }
  294. }
  295. }
  296. @objc func renameFile(_ notification: NSNotification) {
  297. if self.view?.window == nil { return }
  298. reloadDataSource()
  299. }
  300. @objc func createFolder(_ notification: NSNotification) {
  301. if self.view?.window == nil { return }
  302. if let userInfo = notification.userInfo as NSDictionary? {
  303. if let metadata = userInfo["metadata"] as? tableMetadata {
  304. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  305. if let row = dataSource.addMetadata(metadata) {
  306. let indexPath = IndexPath(row: row, section: 0)
  307. collectionView?.performBatchUpdates({
  308. collectionView?.insertItems(at: [indexPath])
  309. }, completion: { (_) in
  310. self.collectionView?.reloadData()
  311. })
  312. }
  313. }
  314. }
  315. } else {
  316. reloadDataSourceNetwork()
  317. }
  318. }
  319. @objc func favoriteFile(_ notification: NSNotification) {
  320. if self.view?.window == nil { return }
  321. if let userInfo = notification.userInfo as NSDictionary? {
  322. if let metadata = userInfo["metadata"] as? tableMetadata {
  323. if dataSource.getIndexMetadata(ocId: metadata.ocId) != nil {
  324. reloadDataSource()
  325. }
  326. }
  327. }
  328. }
  329. @objc func downloadStartFile(_ notification: NSNotification) {
  330. if self.view?.window == nil { return }
  331. if let userInfo = notification.userInfo as NSDictionary? {
  332. if let metadata = userInfo["metadata"] as? tableMetadata {
  333. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  334. let indexPath = IndexPath(row: row, section: 0)
  335. collectionView?.reloadItems(at: [indexPath])
  336. }
  337. }
  338. }
  339. }
  340. @objc func downloadedFile(_ notification: NSNotification) {
  341. if self.view?.window == nil { return }
  342. if let userInfo = notification.userInfo as NSDictionary? {
  343. if let metadata = userInfo["metadata"] as? tableMetadata, let _ = userInfo["errorCode"] as? Int {
  344. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  345. let indexPath = IndexPath(row: row, section: 0)
  346. collectionView?.reloadItems(at: [indexPath])
  347. }
  348. }
  349. }
  350. }
  351. @objc func downloadCancelFile(_ notification: NSNotification) {
  352. if self.view?.window == nil { return }
  353. if let userInfo = notification.userInfo as NSDictionary? {
  354. if let metadata = userInfo["metadata"] as? tableMetadata {
  355. if let row = dataSource.reloadMetadata(ocId: metadata.ocId) {
  356. let indexPath = IndexPath(row: row, section: 0)
  357. collectionView?.reloadItems(at: [indexPath])
  358. }
  359. }
  360. }
  361. }
  362. @objc func uploadStartFile(_ notification: NSNotification) {
  363. if self.view?.window == nil { return }
  364. if let userInfo = notification.userInfo as NSDictionary? {
  365. if let metadata = userInfo["metadata"] as? tableMetadata {
  366. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  367. if let row = dataSource.addMetadata(metadata) {
  368. let indexPath = IndexPath(row: row, section: 0)
  369. collectionView?.performBatchUpdates({
  370. collectionView?.insertItems(at: [indexPath])
  371. }, completion: { (_) in
  372. self.collectionView?.reloadData()
  373. })
  374. }
  375. }
  376. }
  377. }
  378. }
  379. @objc func uploadedFile(_ notification: NSNotification) {
  380. if self.view?.window == nil { return }
  381. if let userInfo = notification.userInfo as NSDictionary? {
  382. if let metadata = userInfo["metadata"] as? tableMetadata, let ocIdTemp = userInfo["ocIdTemp"] as? String, let _ = userInfo["errorCode"] as? Int {
  383. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  384. dataSource.reloadMetadata(ocId: metadata.ocId, ocIdTemp: ocIdTemp)
  385. collectionView?.reloadData()
  386. }
  387. }
  388. }
  389. }
  390. @objc func uploadCancelFile(_ notification: NSNotification) {
  391. if self.view?.window == nil { return }
  392. if let userInfo = notification.userInfo as NSDictionary? {
  393. if let metadata = userInfo["metadata"] as? tableMetadata {
  394. if metadata.serverUrl == serverUrl && metadata.account == appDelegate.account {
  395. if let row = dataSource.deleteMetadata(ocId: metadata.ocId) {
  396. let indexPath = IndexPath(row: row, section: 0)
  397. collectionView?.performBatchUpdates({
  398. collectionView?.deleteItems(at: [indexPath])
  399. }, completion: { (_) in
  400. self.collectionView?.reloadData()
  401. })
  402. } else {
  403. self.reloadDataSource()
  404. }
  405. }
  406. }
  407. }
  408. }
  409. @objc func triggerProgressTask(_ notification: NSNotification) {
  410. if self.view?.window == nil { return }
  411. if let userInfo = notification.userInfo as NSDictionary? {
  412. if let ocId = userInfo["ocId"] as? String {
  413. let _ = userInfo["account"] as? String ?? ""
  414. let _ = userInfo["serverUrl"] as? String ?? ""
  415. let progressNumber = userInfo["progress"] as? NSNumber ?? 0
  416. let progress = progressNumber.floatValue
  417. let status = userInfo["status"] as? Int ?? Int(k_metadataStatusNormal)
  418. let totalBytes = userInfo["totalBytes"] as? Double ?? 0
  419. let totalBytesExpected = userInfo["totalBytesExpected"] as? Double ?? 0
  420. appDelegate.listProgressMetadata.setObject([progress as NSNumber, totalBytes as NSNumber, totalBytesExpected as NSNumber], forKey: userInfo["ocId"] as? NSString ?? "")
  421. if let index = dataSource.getIndexMetadata(ocId: ocId) {
  422. if let cell = collectionView?.cellForItem(at: IndexPath(row: index, section: 0)) {
  423. if cell is NCListCell {
  424. let cell = cell as! NCListCell
  425. if progress > 0 {
  426. cell.progressView?.isHidden = false
  427. cell.progressView?.progress = progress
  428. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  429. if status == k_metadataStatusInDownload {
  430. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  431. } else if status == k_metadataStatusInUpload {
  432. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  433. }
  434. }
  435. } else if cell is NCTransferCell {
  436. let cell = cell as! NCTransferCell
  437. if progress > 0 {
  438. cell.progressView?.isHidden = false
  439. cell.progressView?.progress = progress
  440. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  441. if status == k_metadataStatusInDownload {
  442. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  443. } else if status == k_metadataStatusInUpload {
  444. cell.labelInfo.text = CCUtility.transformedSize(totalBytesExpected) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  445. }
  446. }
  447. } else if cell is NCGridCell {
  448. let cell = cell as! NCGridCell
  449. if progress > 0 {
  450. cell.progressView.isHidden = false
  451. cell.progressView.progress = progress
  452. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  453. }
  454. }
  455. }
  456. }
  457. }
  458. }
  459. }
  460. // MARK: - Empty
  461. func emptyDataSetView(_ view: NCEmptyView) {
  462. if searchController?.isActive ?? false {
  463. view.emptyImage.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "search"), width: 300, height: 300, color: .gray)
  464. if isReloadDataSourceNetworkInProgress {
  465. view.emptyTitle.text = NSLocalizedString("_search_in_progress_", comment: "")
  466. } else {
  467. view.emptyTitle.text = NSLocalizedString("_search_no_record_found_", comment: "")
  468. }
  469. view.emptyDescription.text = NSLocalizedString("_search_instruction_", comment: "")
  470. } else if isReloadDataSourceNetworkInProgress {
  471. view.emptyImage.image = CCGraphics.changeThemingColorImage(UIImage.init(named: "networkInProgress"), width: 300, height: 300, color: .gray)
  472. view.emptyTitle.text = NSLocalizedString("_request_in_progress_", comment: "")
  473. view.emptyDescription.text = ""
  474. } else {
  475. view.emptyImage.image = emptyImage
  476. view.emptyTitle.text = NSLocalizedString(emptyTitle, comment: "")
  477. view.emptyDescription.text = NSLocalizedString(emptyDescription, comment: "")
  478. }
  479. }
  480. // MARK: - SEARCH
  481. func updateSearchResults(for searchController: UISearchController) {
  482. timerInputSearch?.invalidate()
  483. timerInputSearch = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(reloadDataSourceNetwork), userInfo: nil, repeats: false)
  484. literalSearch = searchController.searchBar.text
  485. collectionView?.reloadData()
  486. }
  487. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  488. isSearching = true
  489. metadatasSource.removeAll()
  490. reloadDataSource()
  491. }
  492. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  493. isSearching = false
  494. literalSearch = ""
  495. reloadDataSource()
  496. }
  497. // MARK: - TAP EVENT
  498. @objc func tapSelect(sender: Any) {
  499. isEditMode = !isEditMode
  500. selectOcId.removeAll()
  501. setNavigationItem()
  502. self.collectionView.reloadData()
  503. }
  504. func tapSwitchHeader(sender: Any) {
  505. if collectionView.collectionViewLayout == gridLayout {
  506. // list layout
  507. UIView.animate(withDuration: 0.0, animations: {
  508. self.collectionView.collectionViewLayout.invalidateLayout()
  509. self.collectionView.setCollectionViewLayout(self.listLayout, animated: false, completion: { (_) in
  510. self.collectionView.reloadData()
  511. })
  512. })
  513. layout = k_layout_list
  514. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  515. } else {
  516. // grid layout
  517. UIView.animate(withDuration: 0.0, animations: {
  518. self.collectionView.collectionViewLayout.invalidateLayout()
  519. self.collectionView.setCollectionViewLayout(self.gridLayout, animated: false, completion: { (_) in
  520. self.collectionView.reloadData()
  521. })
  522. })
  523. layout = k_layout_grid
  524. NCUtility.shared.setLayoutForView(key: layoutKey, serverUrl: serverUrl, layout: layout)
  525. }
  526. }
  527. func tapOrderHeader(sender: Any) {
  528. let sortMenu = NCSortMenu()
  529. sortMenu.toggleMenu(viewController: self, key: layoutKey, sortButton: sender as? UIButton, serverUrl: serverUrl)
  530. }
  531. @objc func tapSelectMenu(sender: Any) {
  532. guard let tabBarController = self.tabBarController else { return }
  533. toggleMoreSelect(viewController: tabBarController, selectOcId: selectOcId)
  534. }
  535. func tapMoreHeader(sender: Any) { }
  536. func tapMoreListItem(with objectId: String, namedButtonMore: String, sender: Any) {
  537. tapMoreGridItem(with: objectId, namedButtonMore: namedButtonMore, sender: sender)
  538. }
  539. func tapShareListItem(with objectId: String, sender: Any) {
  540. if isEditMode { return }
  541. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  542. NCNetworkingNotificationCenter.shared.openShare(ViewController: self, metadata: metadata, indexPage: 2)
  543. }
  544. func tapMoreGridItem(with objectId: String, namedButtonMore: String, sender: Any) {
  545. if isEditMode { return }
  546. guard let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) else { return }
  547. if namedButtonMore == k_buttonMoreMore {
  548. toggleMoreMenu(viewController: self, metadata: metadata)
  549. } else if namedButtonMore == k_buttonMoreStop {
  550. NCNetworking.shared.cancelTransferMetadata(metadata) { }
  551. }
  552. }
  553. func tapRichWorkspace(sender: Any) {
  554. if let navigationController = UIStoryboard(name: "NCViewerRichWorkspace", bundle: nil).instantiateInitialViewController() as? UINavigationController {
  555. if let viewerRichWorkspace = navigationController.topViewController as? NCViewerRichWorkspace {
  556. viewerRichWorkspace.richWorkspaceText = richWorkspaceText ?? ""
  557. viewerRichWorkspace.serverUrl = serverUrl
  558. navigationController.modalPresentationStyle = .fullScreen
  559. self.present(navigationController, animated: true, completion: nil)
  560. }
  561. }
  562. }
  563. func longPressListItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  564. openMenuItems(with: objectId, gestureRecognizer: gestureRecognizer)
  565. }
  566. func longPressGridItem(with objectId: String, gestureRecognizer: UILongPressGestureRecognizer) {
  567. openMenuItems(with: objectId, gestureRecognizer: gestureRecognizer)
  568. }
  569. func longPressMoreListItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  570. }
  571. func longPressMoreGridItem(with objectId: String, namedButtonMore: String, gestureRecognizer: UILongPressGestureRecognizer) {
  572. }
  573. @objc func longPressCollecationView(_ gestureRecognizer: UILongPressGestureRecognizer) {
  574. openMenuItems(with: nil, gestureRecognizer: gestureRecognizer)
  575. }
  576. func openMenuItems(with objectId: String?, gestureRecognizer: UILongPressGestureRecognizer) {
  577. if gestureRecognizer.state != .began { return }
  578. if serverUrl == "" { return }
  579. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(objectId) {
  580. metadataTouch = metadata
  581. } else {
  582. metadataTouch = nil
  583. }
  584. var listMenuItems: [UIMenuItem] = []
  585. let touchPoint = gestureRecognizer.location(in: collectionView)
  586. becomeFirstResponder()
  587. if metadataTouch != nil {
  588. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_copy_file_", comment: ""), action: #selector(copyFileMenu(_:))))
  589. }
  590. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_paste_file_", comment: ""), action: #selector(pasteFilesMenu(_:))))
  591. if metadataTouch != nil {
  592. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_quicklook_", comment: ""), action: #selector(openQuickLookMenu(_:))))
  593. if !NCBrandOptions.sharedInstance.disable_openin_file {
  594. listMenuItems.append(UIMenuItem.init(title: NSLocalizedString("_open_in_", comment: ""), action: #selector(openInMenu(_:))))
  595. }
  596. }
  597. if listMenuItems.count > 0 {
  598. UIMenuController.shared.menuItems = listMenuItems
  599. UIMenuController.shared.setTargetRect(CGRect(x: touchPoint.x, y: touchPoint.y, width: 0, height: 0), in: collectionView)
  600. UIMenuController.shared.setMenuVisible(true, animated: true)
  601. }
  602. }
  603. // MARK: - Menu Item
  604. override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
  605. if (#selector(pasteFilesMenu(_:)) == action) {
  606. if UIPasteboard.general.items.count > 0 {
  607. return true
  608. }
  609. }
  610. if (#selector(openQuickLookMenu(_:)) == action || #selector(openInMenu(_:)) == action || #selector(copyFileMenu(_:)) == action) {
  611. guard let metadata = metadataTouch else { return false }
  612. if !metadata.directory && metadata.status == k_metadataStatusNormal {
  613. return true
  614. }
  615. }
  616. return false
  617. }
  618. @objc func copyFileMenu(_ notification: Any) {
  619. var metadatas: [tableMetadata] = []
  620. var items = [[String : Any]]()
  621. if isEditMode {
  622. for ocId in selectOcId {
  623. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  624. metadatas.append(metadata)
  625. }
  626. }
  627. } else {
  628. guard let metadata = metadataTouch else { return }
  629. metadatas.append(metadata)
  630. }
  631. for metadata in metadatas {
  632. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  633. do {
  634. let etagPasteboard = try NSKeyedArchiver.archivedData(withRootObject: metadata.ocId, requiringSecureCoding: false)
  635. items.append([k_metadataKeyedUnarchiver:etagPasteboard])
  636. } catch {
  637. print("error")
  638. }
  639. } else {
  640. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadCopy, setFavorite: false) { (_) in }
  641. }
  642. }
  643. UIPasteboard.general.setItems(items, options: [:])
  644. if isEditMode {
  645. tapSelect(sender: self)
  646. }
  647. }
  648. @objc func pasteFilesMenu(_ notification: Any) {
  649. var listData: [String] = []
  650. for item in UIPasteboard.general.items {
  651. for object in item {
  652. let contentType = object.key
  653. let data = object.value
  654. if contentType == k_metadataKeyedUnarchiver {
  655. do {
  656. if let ocId = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as! Data) as? String{
  657. uploadPasteOcId(ocId)
  658. }
  659. } catch {
  660. print("error")
  661. }
  662. continue
  663. }
  664. if data is String {
  665. if listData.contains(data as! String) {
  666. continue
  667. } else {
  668. listData.append(data as! String)
  669. }
  670. }
  671. let type = NCCommunicationCommon.shared.convertUTItoResultType(fileUTI: contentType as CFString)
  672. if type.resultTypeFile != NCCommunicationCommon.typeFile.unknow.rawValue && type.resultExtension != "" {
  673. uploadPasteFile(fileName: type.resultFilename, ext: type.resultExtension, contentType: contentType, data: data)
  674. }
  675. }
  676. }
  677. }
  678. private func uploadPasteFile(fileName: String, ext: String, contentType: String, data: Any) {
  679. do {
  680. let fileNameView = fileName + "_" + CCUtility.getIncrementalNumber() + "." + ext
  681. let ocId = UUID().uuidString
  682. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  683. if data is UIImage {
  684. try (data as? UIImage)?.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: filePath))
  685. } else if data is Data {
  686. try (data as? Data)?.write(to: URL(fileURLWithPath: filePath))
  687. } else if data is String {
  688. try (data as? String)?.write(to: URL(fileURLWithPath: filePath), atomically: true, encoding: .utf8)
  689. } else {
  690. return
  691. }
  692. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: contentType, livePhoto: false)
  693. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  694. metadataForUpload.sessionSelector = selectorUploadFile
  695. metadataForUpload.size = Double(NCUtilityFileSystem.shared.getFileSize(filePath: filePath))
  696. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  697. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  698. } catch { }
  699. }
  700. private func uploadPasteOcId(_ ocId: String) {
  701. if let metadata = NCManageDatabase.sharedInstance.getMetadataFromOcId(ocId) {
  702. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  703. let fileNameView = NCUtility.shared.createFileName(metadata.fileNameView, serverUrl: serverUrl, account: appDelegate.account)
  704. let ocId = NSUUID().uuidString
  705. CCUtility.copyFile(atPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView), toPath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView))
  706. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.account, fileName: fileNameView, ocId: ocId, serverUrl: serverUrl, urlBase: appDelegate.urlBase, url: "", contentType: "", livePhoto: false)
  707. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  708. metadataForUpload.sessionSelector = selectorUploadFile
  709. metadataForUpload.size = metadata.size
  710. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  711. NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  712. }
  713. }
  714. }
  715. @objc func openQuickLookMenu(_ notification: Any) {
  716. guard let metadata = metadataTouch else { return }
  717. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  718. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorLoadFileQuickLook, "errorCode": 0, "errorDescription": "" ])
  719. } else {
  720. NCNetworking.shared.download(metadata: metadata, selector: selectorLoadFileQuickLook) { (_) in }
  721. }
  722. }
  723. @objc func openInMenu(_ notification: Any) {
  724. guard let metadata = metadataTouch else { return }
  725. if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  726. NotificationCenter.default.postOnMainThread(name: k_notificationCenter_downloadedFile, userInfo: ["metadata": metadata, "selector": selectorOpenIn, "errorCode": 0, "errorDescription": "" ])
  727. } else {
  728. NCNetworking.shared.download(metadata: metadata, selector: selectorOpenIn) { (_) in }
  729. }
  730. }
  731. // MARK: - DataSource + NC Endpoint
  732. @objc func reloadDataSource() {
  733. if appDelegate.account.count == 0 { return }
  734. // Get richWorkspace Text
  735. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, serverUrl))
  736. richWorkspaceText = directory?.richWorkspace
  737. // E2EE
  738. isEncryptedFolder = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: metadataFolder?.e2eEncrypted ?? false, account: appDelegate.account, urlBase: appDelegate.urlBase)
  739. // get auto upload folder
  740. autoUploadFileName = NCManageDatabase.sharedInstance.getAccountAutoUploadFileName()
  741. autoUploadDirectory = NCManageDatabase.sharedInstance.getAccountAutoUploadDirectory(urlBase: appDelegate.urlBase, account: appDelegate.account)
  742. // get layout for view
  743. (layout, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: layoutKey, serverUrl: serverUrl)
  744. }
  745. @objc func reloadDataSourceNetwork(forced: Bool = false) { }
  746. @objc func reloadDataSourceNetworkRefreshControl() {
  747. reloadDataSourceNetwork(forced: true)
  748. }
  749. @objc func networkSearch() {
  750. if appDelegate.account.count == 0 { return }
  751. if literalSearch?.count ?? 0 > 1 {
  752. isReloadDataSourceNetworkInProgress = true
  753. collectionView?.reloadData()
  754. NCNetworking.shared.searchFiles(urlBase: appDelegate.urlBase, user: appDelegate.user, literal: literalSearch!) { (account, metadatas, errorCode, errorDescription) in
  755. if self.searchController?.isActive ?? false && errorCode == 0 {
  756. self.metadatasSource = metadatas!
  757. }
  758. self.refreshControl.endRefreshing()
  759. self.isReloadDataSourceNetworkInProgress = false
  760. self.reloadDataSource()
  761. }
  762. } else {
  763. self.refreshControl.endRefreshing()
  764. }
  765. }
  766. @objc func networkReadFolder(forced: Bool, completion: @escaping(_ metadatas: [tableMetadata]?, _ metadatasUpdate: [tableMetadata]?, _ errorCode: Int, _ errorDescription: String)->()) {
  767. NCNetworking.shared.readFile(serverUrlFileName: serverUrl, account: appDelegate.account) { (account, metadata, errorCode, errorDescription) in
  768. if errorCode == 0 {
  769. let directory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", self.appDelegate.account, self.serverUrl))
  770. if forced || directory?.etag != metadata?.etag || directory?.e2eEncrypted ?? false {
  771. NCNetworking.shared.readFolder(serverUrl: self.serverUrl, account: self.appDelegate.account) { (account, metadataFolder, metadatas, metadatasUpdate, metadatasLocalUpdate, errorCode, errorDescription) in
  772. if errorCode == 0 {
  773. self.metadataFolder = metadataFolder
  774. // E2EE
  775. if let metadataFolder = metadataFolder {
  776. if metadataFolder.e2eEncrypted && CCUtility.isEnd(toEndEnabled: self.appDelegate.account) {
  777. NCCommunication.shared.getE2EEMetadata(fileId: metadataFolder.ocId, e2eToken: nil) { (account, e2eMetadata, errorCode, errorDescription) in
  778. if errorCode == 0 && e2eMetadata != nil {
  779. if !NCEndToEndMetadata.sharedInstance.decoderMetadata(e2eMetadata!, privateKey: CCUtility.getEndToEndPrivateKey(account), serverUrl: self.serverUrl, account: account, urlBase: self.appDelegate.urlBase) {
  780. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorDecodeMetadata), forced: true)
  781. } else {
  782. self.reloadDataSource()
  783. }
  784. } else if errorCode != k_CCErrorResourceNotFound {
  785. NCContentPresenter.shared.messageNotification("_error_e2ee_", description: "_e2e_error_decode_metadata_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorDecodeMetadata), forced: true)
  786. }
  787. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  788. }
  789. } else {
  790. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  791. }
  792. } else {
  793. completion(metadatas, metadatasUpdate, errorCode, errorDescription)
  794. }
  795. } else {
  796. completion(nil, nil, errorCode, errorDescription)
  797. }
  798. }
  799. } else {
  800. completion(nil, nil, 0, "")
  801. }
  802. } else {
  803. completion(nil, nil, errorCode, errorDescription)
  804. }
  805. }
  806. }
  807. }
  808. // MARK: - 3D Touch peek and pop
  809. extension NCCollectionViewCommon: UIViewControllerPreviewingDelegate {
  810. func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
  811. guard let point = collectionView?.convert(location, from: collectionView?.superview) else { return nil }
  812. guard let indexPath = collectionView?.indexPathForItem(at: point) else { return nil }
  813. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return nil }
  814. guard let viewController = UIStoryboard(name: "CCPeekPop", bundle: nil).instantiateViewController(withIdentifier: "PeekPopImagePreview") as? CCPeekPop else { return nil }
  815. viewController.metadata = metadata
  816. if layout == k_layout_grid {
  817. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCGridCell else { return nil }
  818. previewingContext.sourceRect = cell.frame
  819. viewController.imageFile = cell.imageItem.image
  820. } else {
  821. guard let cell = collectionView?.cellForItem(at: indexPath) as? NCListCell else { return nil }
  822. previewingContext.sourceRect = cell.frame
  823. viewController.imageFile = cell.imageItem.image
  824. }
  825. viewController.showOpenIn = true
  826. viewController.showOpenQuickLook = NCUtility.shared.isQuickLookDisplayable(metadata: metadata)
  827. viewController.showShare = false
  828. return viewController
  829. }
  830. func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
  831. guard let indexPath = collectionView?.indexPathForItem(at: previewingContext.sourceRect.origin) else { return }
  832. collectionView(collectionView, didSelectItemAt: indexPath)
  833. }
  834. }
  835. // MARK: - Collection View
  836. extension NCCollectionViewCommon: UICollectionViewDelegate {
  837. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  838. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  839. metadataTouch = metadata
  840. selectedIndexPath = indexPath
  841. if isEditMode {
  842. if let index = selectOcId.firstIndex(of: metadata.ocId) {
  843. selectOcId.remove(at: index)
  844. } else {
  845. selectOcId.append(metadata.ocId)
  846. }
  847. collectionView.reloadItems(at: [indexPath])
  848. self.navigationItem.title = NSLocalizedString("_selected_", comment: "") + " : \(selectOcId.count)" + " / \(dataSource.metadatas.count)"
  849. return
  850. }
  851. if metadata.e2eEncrypted && !CCUtility.isEnd(toEndEnabled: appDelegate.account) {
  852. NCContentPresenter.shared.messageNotification("_info_", description: "_e2e_goto_settings_for_enable_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorE2EENotEnabled), forced: true)
  853. return
  854. }
  855. if metadata.directory {
  856. guard let serverUrlPush = CCUtility.stringAppendServerUrl(metadataTouch!.serverUrl, addFileName: metadataTouch!.fileName) else { return }
  857. // FILES
  858. if layoutKey == k_layout_view_files {
  859. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  860. guard let vcFiles = (viewController as? NCFiles) else { return }
  861. if vcFiles.isViewLoaded {
  862. self.navigationController?.pushViewController(vcFiles, animated: true)
  863. }
  864. } else {
  865. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  866. vcFiles.isRoot = false
  867. vcFiles.serverUrl = serverUrlPush
  868. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  869. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  870. self.navigationController?.pushViewController(vcFiles, animated: true)
  871. }
  872. }
  873. // FAVORITE
  874. if layoutKey == k_layout_view_favorite {
  875. if let viewController = appDelegate.listFavoriteVC.value(forKey: serverUrlPush) {
  876. guard let vcFavorite = (viewController as? NCFavorite) else { return }
  877. if vcFavorite.isViewLoaded {
  878. self.navigationController?.pushViewController(vcFavorite, animated: true)
  879. }
  880. } else {
  881. let vcFavorite:NCFavorite = UIStoryboard(name: "NCFavorite", bundle: nil).instantiateInitialViewController() as! NCFavorite
  882. vcFavorite.serverUrl = serverUrlPush
  883. vcFavorite.titleCurrentFolder = metadataTouch!.fileNameView
  884. appDelegate.listFavoriteVC.setValue(vcFavorite, forKey: serverUrlPush)
  885. self.navigationController?.pushViewController(vcFavorite, animated: true)
  886. }
  887. }
  888. // OFFLINE
  889. if layoutKey == k_layout_view_offline {
  890. if let viewController = appDelegate.listOfflineVC.value(forKey: serverUrlPush) {
  891. guard let vcOffline = (viewController as? NCOffline) else { return }
  892. if vcOffline.isViewLoaded {
  893. self.navigationController?.pushViewController(vcOffline, animated: true)
  894. }
  895. } else {
  896. let vcOffline:NCOffline = UIStoryboard(name: "NCOffline", bundle: nil).instantiateInitialViewController() as! NCOffline
  897. vcOffline.serverUrl = serverUrlPush
  898. vcOffline.titleCurrentFolder = metadataTouch!.fileNameView
  899. appDelegate.listOfflineVC.setValue(vcOffline, forKey: serverUrlPush)
  900. self.navigationController?.pushViewController(vcOffline, animated: true)
  901. }
  902. }
  903. // RECENT ( for push use Files ... he he he )
  904. if layoutKey == k_layout_view_recent {
  905. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  906. guard let vcFiles = (viewController as? NCFiles) else { return }
  907. if vcFiles.isViewLoaded {
  908. self.navigationController?.pushViewController(vcFiles, animated: true)
  909. }
  910. } else {
  911. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  912. vcFiles.isRoot = false
  913. vcFiles.serverUrl = serverUrlPush
  914. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  915. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  916. self.navigationController?.pushViewController(vcFiles, animated: true)
  917. }
  918. }
  919. //VIEW IN FOLDER
  920. if layoutKey == k_layout_view_viewInFolder {
  921. let vcFileViewInFolder:NCFileViewInFolder = UIStoryboard(name: "NCFileViewInFolder", bundle: nil).instantiateInitialViewController() as! NCFileViewInFolder
  922. vcFileViewInFolder.serverUrl = serverUrlPush
  923. vcFileViewInFolder.titleCurrentFolder = metadataTouch!.fileNameView
  924. self.navigationController?.pushViewController(vcFileViewInFolder, animated: true)
  925. }
  926. // SHARES ( for push use Files ... he he he )
  927. if layoutKey == k_layout_view_shares {
  928. if let viewController = appDelegate.listFilesVC.value(forKey: serverUrlPush) {
  929. guard let vcFiles = (viewController as? NCFiles) else { return }
  930. if vcFiles.isViewLoaded {
  931. self.navigationController?.pushViewController(vcFiles, animated: true)
  932. }
  933. } else {
  934. let vcFiles:NCFiles = UIStoryboard(name: "NCFiles", bundle: nil).instantiateInitialViewController() as! NCFiles
  935. vcFiles.isRoot = false
  936. vcFiles.serverUrl = serverUrlPush
  937. vcFiles.titleCurrentFolder = metadataTouch!.fileNameView
  938. appDelegate.listFilesVC.setValue(vcFiles, forKey: serverUrlPush)
  939. self.navigationController?.pushViewController(vcFiles, animated: true)
  940. }
  941. }
  942. } else {
  943. guard let metadataTouch = metadataTouch else { return }
  944. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isDirectEditing(account: metadata.account, contentType: metadata.contentType) != nil {
  945. if NCCommunication.shared.isNetworkReachable() {
  946. NCViewer.shared.view(viewController: self, metadata: metadataTouch)
  947. } else {
  948. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  949. }
  950. return
  951. }
  952. if metadata.typeFile == k_metadataTypeFile_document && NCUtility.shared.isRichDocument(metadata) {
  953. if NCCommunication.shared.isNetworkReachable() {
  954. NCViewer.shared.view(viewController: self, metadata: metadataTouch)
  955. } else {
  956. NCContentPresenter.shared.messageNotification("_info_", description: "_go_online_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorOffline), forced: true)
  957. }
  958. return
  959. }
  960. if metadata.typeFile == k_metadataTypeFile_video {
  961. NCViewer.shared.view(viewController: self, metadata: metadataTouch)
  962. return
  963. }
  964. if metadata.typeFile == k_metadataTypeFile_image {
  965. var metadatas: [tableMetadata] = []
  966. for metadata in dataSource.metadatas {
  967. if metadata.typeFile == k_metadataTypeFile_image || metadata.typeFile == k_metadataTypeFile_video {
  968. metadatas.append(metadata)
  969. }
  970. }
  971. NCViewer.shared.view(viewController: self, metadata: metadataTouch, metadatas: metadatas)
  972. return
  973. }
  974. if CCUtility.fileProviderStorageExists(metadataTouch.ocId, fileNameView: metadataTouch.fileNameView) {
  975. NCViewer.shared.view(viewController: self, metadata: metadataTouch)
  976. } else {
  977. NCNetworking.shared.download(metadata: metadataTouch, selector: selectorLoadFileView) { (_) in }
  978. }
  979. }
  980. }
  981. func collectionViewSelectAll() {
  982. selectOcId.removeAll()
  983. for metadata in metadatasSource {
  984. selectOcId.append(metadata.ocId)
  985. }
  986. collectionView.reloadData()
  987. }
  988. }
  989. extension NCCollectionViewCommon: UICollectionViewDataSource {
  990. func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  991. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  992. NCOperationQueue.shared.downloadThumbnail(metadata: metadata, urlBase: appDelegate.urlBase, view: collectionView, indexPath: indexPath)
  993. }
  994. func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  995. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else { return }
  996. NCOperationQueue.shared.cancelDownloadThumbnail(metadata: metadata)
  997. }
  998. func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  999. if kind == UICollectionView.elementKindSectionHeader {
  1000. let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeaderMenu", for: indexPath) as! NCSectionHeaderMenu
  1001. if collectionView.collectionViewLayout == gridLayout {
  1002. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchList"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  1003. } else {
  1004. header.buttonSwitch.setImage(CCGraphics.changeThemingColorImage(UIImage.init(named: "switchGrid"), width: 100, height: 100, color: NCBrandColor.sharedInstance.icon), for: .normal)
  1005. }
  1006. header.delegate = self
  1007. header.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  1008. header.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  1009. header.setStatusButton(count: dataSource.metadatas.count)
  1010. header.setTitleSorted(datasourceTitleButton: titleButton)
  1011. header.viewRichWorkspaceHeightConstraint.constant = headerRichWorkspaceHeight
  1012. header.setRichWorkspaceText(richWorkspaceText: richWorkspaceText)
  1013. return header
  1014. } else {
  1015. let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionFooter", for: indexPath) as! NCSectionFooter
  1016. let info = dataSource.getFilesInformation()
  1017. footer.setTitleLabel(directories: info.directories, files: info.files, size: info.size )
  1018. return footer
  1019. }
  1020. }
  1021. func numberOfSections(in collectionView: UICollectionView) -> Int {
  1022. return 1
  1023. }
  1024. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  1025. let numberItems = dataSource.numberOfItems()
  1026. emptyDataSet?.numberOfItemsInSection(numberItems, section: section)
  1027. return numberItems
  1028. }
  1029. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  1030. guard let metadata = dataSource.cellForItemAt(indexPath: indexPath) else {
  1031. return UICollectionViewCell()
  1032. }
  1033. var tableShare: tableShare?
  1034. var isShare = false
  1035. var isMounted = false
  1036. if metadataFolder != nil {
  1037. isShare = metadata.permissions.contains(k_permission_shared) && !metadataFolder!.permissions.contains(k_permission_shared)
  1038. isMounted = metadata.permissions.contains(k_permission_mounted) && !metadataFolder!.permissions.contains(k_permission_mounted)
  1039. }
  1040. if dataSource.metadataShare[metadata.ocId] != nil {
  1041. tableShare = dataSource.metadataShare[metadata.ocId]
  1042. }
  1043. //
  1044. // LAYOUT LIST
  1045. //
  1046. if layout == k_layout_list {
  1047. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listCell", for: indexPath) as! NCListCell
  1048. cell.delegate = self
  1049. cell.objectId = metadata.ocId
  1050. cell.indexPath = indexPath
  1051. cell.labelTitle.text = metadata.fileNameView
  1052. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  1053. cell.separator.backgroundColor = NCBrandColor.sharedInstance.separator
  1054. cell.imageSelect.image = nil
  1055. cell.imageStatus.image = nil
  1056. cell.imageLocal.image = nil
  1057. cell.imageFavorite.image = nil
  1058. cell.imageShared.image = nil
  1059. cell.imageMore.image = nil
  1060. cell.imageItem.image = nil
  1061. cell.imageItem.backgroundColor = nil
  1062. cell.progressView.progress = 0.0
  1063. if metadata.directory {
  1064. if metadata.e2eEncrypted {
  1065. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1066. } else if isShare {
  1067. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1068. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1069. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1070. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1071. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1072. } else if metadata.mountType == "group" {
  1073. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1074. } else if isMounted {
  1075. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1076. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1077. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1078. } else {
  1079. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1080. }
  1081. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date)
  1082. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1083. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1084. // Local image: offline
  1085. if tableDirectory != nil && tableDirectory!.offline {
  1086. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1087. }
  1088. } else {
  1089. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1090. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1091. } else {
  1092. if metadata.hasPreview {
  1093. cell.imageItem.backgroundColor = .lightGray
  1094. } else {
  1095. if metadata.iconName.count > 0 {
  1096. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1097. } else {
  1098. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1099. }
  1100. }
  1101. }
  1102. if cell.imageItem.image != nil {
  1103. self.photos.append(cell.imageItem.image!)
  1104. }
  1105. cell.labelInfo.text = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  1106. // image local
  1107. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1108. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1109. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1110. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1111. }
  1112. }
  1113. // image Favorite
  1114. if metadata.favorite {
  1115. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1116. }
  1117. // Share image
  1118. if (isShare) {
  1119. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  1120. } else if (tableShare != nil && tableShare?.shareType == 3) {
  1121. cell.imageShared.image = NCCollectionCommon.images.cellShareByLinkImage
  1122. } else if (tableShare != nil && tableShare?.shareType != 3) {
  1123. cell.imageShared.image = NCCollectionCommon.images.cellSharedImage
  1124. } else {
  1125. cell.imageShared.image = NCCollectionCommon.images.cellCanShareImage
  1126. }
  1127. if metadata.ownerId.count > 0 && metadata.ownerId != appDelegate.userID {
  1128. // Load avatar
  1129. let fileNameSource = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-" + metadata.ownerId + ".png"
  1130. let fileNameSourceAvatar = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(appDelegate.user, urlBase: appDelegate.urlBase) + "-avatar-" + metadata.ownerId + ".png"
  1131. if FileManager.default.fileExists(atPath: fileNameSourceAvatar) {
  1132. cell.imageShared.image = UIImage(contentsOfFile: fileNameSourceAvatar)
  1133. } else if FileManager.default.fileExists(atPath: fileNameSource) {
  1134. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  1135. } else {
  1136. NCCommunication.shared.downloadAvatar(userID: metadata.ownerId, fileNameLocalPath: fileNameSource, size: Int(k_avatar_size)) { (account, data, errorCode, errorMessage) in
  1137. if errorCode == 0 && account == self.appDelegate.account {
  1138. cell.imageShared.image = NCUtility.shared.createAvatar(fileNameSource: fileNameSource, fileNameSourceAvatar: fileNameSourceAvatar)
  1139. }
  1140. }
  1141. }
  1142. }
  1143. // Transfer
  1144. var progress: Float = 0.0
  1145. var totalBytes: Double = 0.0
  1146. let progressArray = appDelegate.listProgressMetadata.object(forKey: metadata.ocId) as? NSArray
  1147. if progressArray != nil && progressArray?.count == 3 {
  1148. progress = progressArray?.object(at: 0) as? Float ?? 0
  1149. totalBytes = progressArray?.object(at: 1) as? Double ?? 0
  1150. }
  1151. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  1152. cell.progressView.isHidden = false
  1153. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1154. } else {
  1155. cell.progressView.isHidden = true
  1156. cell.progressView.progress = progress
  1157. cell.setButtonMore(named: k_buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1158. }
  1159. // Write status on Label Info
  1160. switch metadata.status {
  1161. case Int(k_metadataStatusWaitDownload):
  1162. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_download_", comment: "")
  1163. break
  1164. case Int(k_metadataStatusInDownload):
  1165. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_download_", comment: "")
  1166. break
  1167. case Int(k_metadataStatusDownloading):
  1168. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↓ " + CCUtility.transformedSize(totalBytes)
  1169. break
  1170. case Int(k_metadataStatusWaitUpload):
  1171. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_wait_upload_", comment: "")
  1172. break
  1173. case Int(k_metadataStatusInUpload):
  1174. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - " + NSLocalizedString("_status_in_upload_", comment: "")
  1175. break
  1176. case Int(k_metadataStatusUploading):
  1177. cell.labelInfo.text = CCUtility.transformedSize(metadata.size) + " - ↑ " + CCUtility.transformedSize(totalBytes)
  1178. break
  1179. default:
  1180. break
  1181. }
  1182. // Live Photo
  1183. if metadata.livePhoto {
  1184. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1185. }
  1186. // E2EE
  1187. if metadata.e2eEncrypted || isEncryptedFolder {
  1188. cell.hideButtonShare(true)
  1189. } else {
  1190. cell.hideButtonShare(false)
  1191. }
  1192. // Remove last separator
  1193. if collectionView.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 {
  1194. cell.separator.isHidden = true
  1195. } else {
  1196. cell.separator.isHidden = false
  1197. }
  1198. // Edit mode
  1199. if isEditMode {
  1200. cell.selectMode(true)
  1201. if selectOcId.contains(metadata.ocId) {
  1202. cell.selected(true)
  1203. } else {
  1204. cell.selected(false)
  1205. }
  1206. } else {
  1207. cell.selectMode(false)
  1208. }
  1209. return cell
  1210. }
  1211. //
  1212. // LAYOUT GRID
  1213. //
  1214. if layout == k_layout_grid {
  1215. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath) as! NCGridCell
  1216. cell.delegate = self
  1217. cell.objectId = metadata.ocId
  1218. cell.indexPath = indexPath
  1219. cell.labelTitle.text = metadata.fileNameView
  1220. cell.labelTitle.textColor = NCBrandColor.sharedInstance.textView
  1221. cell.imageSelect.image = nil
  1222. cell.imageStatus.image = nil
  1223. cell.imageLocal.image = nil
  1224. cell.imageFavorite.image = nil
  1225. cell.imageItem.image = nil
  1226. cell.imageItem.backgroundColor = nil
  1227. cell.progressView.progress = 0.0
  1228. if metadata.directory {
  1229. if metadata.e2eEncrypted {
  1230. cell.imageItem.image = NCCollectionCommon.images.cellFolderEncryptedImage
  1231. } else if isShare {
  1232. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1233. } else if (tableShare != nil && tableShare!.shareType != 3) {
  1234. cell.imageItem.image = NCCollectionCommon.images.cellFolderSharedWithMeImage
  1235. } else if (tableShare != nil && tableShare!.shareType == 3) {
  1236. cell.imageItem.image = NCCollectionCommon.images.cellFolderPublicImage
  1237. } else if metadata.mountType == "group" {
  1238. cell.imageItem.image = NCCollectionCommon.images.cellFolderGroupImage
  1239. } else if isMounted {
  1240. cell.imageItem.image = NCCollectionCommon.images.cellFolderExternalImage
  1241. } else if metadata.fileName == autoUploadFileName && metadata.serverUrl == autoUploadDirectory {
  1242. cell.imageItem.image = NCCollectionCommon.images.cellFolderAutomaticUploadImage
  1243. } else {
  1244. cell.imageItem.image = NCCollectionCommon.images.cellFolderImage
  1245. }
  1246. let lockServerUrl = CCUtility.stringAppendServerUrl(metadata.serverUrl, addFileName: metadata.fileName)!
  1247. let tableDirectory = NCManageDatabase.sharedInstance.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", appDelegate.account, lockServerUrl))
  1248. // Local image: offline
  1249. if tableDirectory != nil && tableDirectory!.offline {
  1250. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1251. }
  1252. } else {
  1253. if FileManager().fileExists(atPath: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)) {
  1254. cell.imageItem.image = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag))
  1255. } else {
  1256. if metadata.hasPreview {
  1257. cell.imageItem.backgroundColor = .lightGray
  1258. } else {
  1259. if metadata.iconName.count > 0 {
  1260. cell.imageItem.image = UIImage.init(named: metadata.iconName)
  1261. } else {
  1262. cell.imageItem.image = NCCollectionCommon.images.cellFileImage
  1263. }
  1264. }
  1265. }
  1266. if cell.imageItem.image != nil {
  1267. self.photos.append(cell.imageItem.image!)
  1268. }
  1269. // image Local
  1270. if dataSource.metadataOffLine.contains(metadata.ocId) {
  1271. cell.imageLocal.image = NCCollectionCommon.images.cellOfflineFlag
  1272. } else if CCUtility.fileProviderStorageExists(metadata.ocId, fileNameView: metadata.fileNameView) {
  1273. cell.imageLocal.image = NCCollectionCommon.images.cellLocal
  1274. }
  1275. }
  1276. // image Favorite
  1277. if metadata.favorite {
  1278. cell.imageFavorite.image = NCCollectionCommon.images.cellFavouriteImage
  1279. }
  1280. // Transfer
  1281. if metadata.status == k_metadataStatusInDownload || metadata.status == k_metadataStatusDownloading || metadata.status >= k_metadataStatusTypeUpload {
  1282. cell.progressView.isHidden = false
  1283. cell.setButtonMore(named: k_buttonMoreStop, image: NCCollectionCommon.images.cellButtonStop)
  1284. } else {
  1285. cell.progressView.isHidden = true
  1286. cell.progressView.progress = 0.0
  1287. cell.setButtonMore(named: k_buttonMoreMore, image: NCCollectionCommon.images.cellButtonMore)
  1288. }
  1289. // Live Photo
  1290. if metadata.livePhoto {
  1291. cell.imageStatus.image = NCCollectionCommon.images.cellLivePhotoImage
  1292. }
  1293. // Edit mode
  1294. if isEditMode {
  1295. cell.selectMode(true)
  1296. if selectOcId.contains(metadata.ocId) {
  1297. cell.selected(true)
  1298. } else {
  1299. cell.selected(false)
  1300. }
  1301. } else {
  1302. cell.selectMode(false)
  1303. }
  1304. return cell
  1305. }
  1306. return UICollectionViewCell()
  1307. }
  1308. }
  1309. extension NCCollectionViewCommon: UICollectionViewDelegateFlowLayout {
  1310. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  1311. headerRichWorkspaceHeight = 0
  1312. if let richWorkspaceText = richWorkspaceText {
  1313. let trimmed = richWorkspaceText.trimmingCharacters(in: .whitespaces)
  1314. if trimmed.count > 0 && !isSearching {
  1315. headerRichWorkspaceHeight = UIScreen.main.bounds.size.height / 4
  1316. }
  1317. }
  1318. return CGSize(width: collectionView.frame.width, height: headerHeight + headerRichWorkspaceHeight)
  1319. }
  1320. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  1321. return CGSize(width: collectionView.frame.width, height: footerHeight)
  1322. }
  1323. }
  1324. extension NCCollectionViewCommon: PhotoPageContainerViewControllerDelegate {
  1325. func containerViewController(_ containerViewController: PhotoPageContainerViewController, indexDidUpdate currentIndex: Int) {
  1326. self.selectedIndexPath = IndexPath(row: currentIndex, section: 0)
  1327. self.collectionView.scrollToItem(at: self.selectedIndexPath, at: .centeredVertically, animated: false)
  1328. }
  1329. }
  1330. extension NCCollectionViewCommon: ZoomAnimatorDelegate {
  1331. func transitionWillStartWith(zoomAnimator: ZoomAnimator) {
  1332. }
  1333. func transitionDidEndWith(zoomAnimator: ZoomAnimator) {
  1334. var cellFrame: CGRect = CGRect.init()
  1335. let cell = self.collectionView.cellForItem(at: self.selectedIndexPath)
  1336. if cell is NCListCell {
  1337. cellFrame = self.collectionView.convert((cell as! NCListCell).frame, to: self.view)
  1338. } else if cell is NCGridCell {
  1339. cellFrame = self.collectionView.convert((cell as! NCGridCell).frame, to: self.view)
  1340. }
  1341. if cellFrame.minY < self.collectionView.contentInset.top {
  1342. self.collectionView.scrollToItem(at: self.selectedIndexPath, at: .top, animated: false)
  1343. } else if cellFrame.maxY > self.view.frame.height - self.collectionView.contentInset.bottom {
  1344. self.collectionView.scrollToItem(at: self.selectedIndexPath, at: .bottom, animated: false)
  1345. }
  1346. }
  1347. func referenceImageView(for zoomAnimator: ZoomAnimator) -> UIImageView? {
  1348. let cell = collectionView.cellForItem(at: selectedIndexPath)
  1349. if cell is NCListCell {
  1350. return (cell as! NCListCell).imageItem
  1351. } else if cell is NCGridCell {
  1352. return (cell as! NCGridCell).imageItem
  1353. }
  1354. return nil
  1355. }
  1356. func referenceImageViewFrameInTransitioningView(for zoomAnimator: ZoomAnimator) -> CGRect? {
  1357. var unconvertedFrame: CGRect = CGRect()
  1358. view.layoutIfNeeded()
  1359. collectionView.layoutIfNeeded()
  1360. let visibleCells = collectionView.indexPathsForVisibleItems
  1361. if !visibleCells.contains(selectedIndexPath) {
  1362. collectionView.scrollToItem(at: selectedIndexPath, at: .centeredVertically, animated: false)
  1363. collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems)
  1364. collectionView.layoutIfNeeded()
  1365. let cell = collectionView.cellForItem(at: selectedIndexPath)
  1366. if cell is NCListCell {
  1367. unconvertedFrame = (cell as! NCListCell).frame
  1368. } else if cell is NCGridCell {
  1369. unconvertedFrame = (cell as! NCGridCell).frame
  1370. }
  1371. } else {
  1372. let cell = collectionView.cellForItem(at: self.selectedIndexPath)
  1373. if cell is NCListCell {
  1374. unconvertedFrame = (cell as! NCListCell).frame
  1375. } else if cell is NCGridCell {
  1376. unconvertedFrame = (cell as! NCGridCell).frame
  1377. }
  1378. }
  1379. let cellFrame = self.collectionView.convert(unconvertedFrame, to: view)
  1380. if cellFrame.minY < collectionView.contentInset.top {
  1381. return CGRect(x: cellFrame.minX, y: collectionView.contentInset.top, width: cellFrame.width, height: cellFrame.height - (collectionView.contentInset.top - cellFrame.minY))
  1382. }
  1383. return cellFrame
  1384. }
  1385. }