NCCollectionViewDataSource.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. //
  2. // NCCollectionViewDataSource.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 06/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 NextcloudKit
  25. import RealmSwift
  26. class NCCollectionViewDataSource: NSObject {
  27. private let utilityFileSystem = NCUtilityFileSystem()
  28. private let utility = NCUtility()
  29. private let global = NCGlobal.shared
  30. private var sectionsValue: [String] = []
  31. private var providers: [NKSearchProvider]?
  32. private var searchResults: [NKSearchResult]?
  33. private var metadatas: [tableMetadata] = []
  34. private var metadatasForSection: [NCMetadataForSection] = []
  35. private var layoutForView: NCDBLayoutForView?
  36. private var metadataIndexPath = ThreadSafeDictionary<IndexPath, tableMetadata>()
  37. override init() { super.init() }
  38. init(metadatas: [tableMetadata],
  39. layoutForView: NCDBLayoutForView? = nil,
  40. providers: [NKSearchProvider]? = nil,
  41. searchResults: [NKSearchResult]? = nil) {
  42. super.init()
  43. removeAll()
  44. self.metadatas = metadatas
  45. self.layoutForView = layoutForView
  46. /// unified search
  47. self.providers = providers
  48. self.searchResults = searchResults
  49. if let providers, !providers.isEmpty || (layoutForView?.groupBy != "none") {
  50. createSections()
  51. }
  52. }
  53. // MARK: -
  54. func removeAll() {
  55. self.metadatas.removeAll()
  56. self.metadataIndexPath.removeAll()
  57. self.metadatasForSection.removeAll()
  58. self.sectionsValue.removeAll()
  59. self.providers = nil
  60. self.searchResults = nil
  61. }
  62. func addSection(metadatas: [tableMetadata], searchResult: NKSearchResult?) {
  63. self.metadatas.append(contentsOf: metadatas)
  64. if let searchResult = searchResult {
  65. self.searchResults?.append(searchResult)
  66. }
  67. createSections()
  68. }
  69. internal func createSections() {
  70. for metadata in self.metadatas {
  71. /// skipped livePhoto VIDEO part
  72. if metadata.isLivePhoto, metadata.classFile == NKCommon.TypeClassFile.video.rawValue {
  73. continue
  74. }
  75. let section = NSLocalizedString(self.getSectionValue(metadata: metadata), comment: "")
  76. if !self.sectionsValue.contains(section) {
  77. self.sectionsValue.append(section)
  78. }
  79. }
  80. /// Unified search
  81. if let providers = self.providers, !providers.isEmpty {
  82. let sectionsDictionary = ThreadSafeDictionary<String, Int>()
  83. for section in self.sectionsValue {
  84. if let provider = providers.filter({ $0.id == section}).first {
  85. sectionsDictionary[section] = provider.order
  86. }
  87. }
  88. self.sectionsValue.removeAll()
  89. let sectionsDictionarySorted = sectionsDictionary.sorted(by: {$0.value < $1.value })
  90. for section in sectionsDictionarySorted {
  91. if section.key == global.appName {
  92. self.sectionsValue.insert(section.key, at: 0)
  93. } else {
  94. self.sectionsValue.append(section.key)
  95. }
  96. }
  97. } else {
  98. /// normal
  99. let directory = NSLocalizedString("directory", comment: "").lowercased().firstUppercased
  100. self.sectionsValue = self.sectionsValue.sorted {
  101. if let directoryOnTop = layoutForView?.directoryOnTop,
  102. directoryOnTop,
  103. $0 == directory {
  104. return true
  105. } else if let directoryOnTop = layoutForView?.directoryOnTop,
  106. directoryOnTop,
  107. $1 == directory {
  108. return false
  109. }
  110. if let ascending = layoutForView?.ascending,
  111. ascending {
  112. return $0 < $1
  113. } else {
  114. return $0 > $1
  115. }
  116. }
  117. }
  118. for sectionValue in self.sectionsValue {
  119. if !existsMetadataForSection(sectionValue: sectionValue) {
  120. print("DATASOURCE: create metadata for section: " + sectionValue)
  121. createMetadataForSection(sectionValue: sectionValue)
  122. }
  123. }
  124. }
  125. internal func createMetadataForSection(sectionValue: String) {
  126. var searchResult: NKSearchResult?
  127. if let providers = self.providers, !providers.isEmpty, let searchResults = self.searchResults {
  128. searchResult = searchResults.filter({ $0.id == sectionValue}).first
  129. }
  130. let metadatas = self.metadatas.filter({ getSectionValue(metadata: $0) == sectionValue})
  131. let metadataForSection = NCMetadataForSection(sectionValue: sectionValue,
  132. metadatas: metadatas,
  133. lastSearchResult: searchResult,
  134. layoutForView: self.layoutForView)
  135. metadatasForSection.append(metadataForSection)
  136. }
  137. // MARK: -
  138. func appendMetadatasToSection(_ metadatas: [tableMetadata], metadataForSection: NCMetadataForSection, lastSearchResult: NKSearchResult) {
  139. guard let sectionIndex = getSectionIndex(metadataForSection.sectionValue) else { return }
  140. var indexPaths: [IndexPath] = []
  141. self.metadatas.append(contentsOf: metadatas)
  142. metadataForSection.metadatas.append(contentsOf: metadatas)
  143. metadataForSection.lastSearchResult = lastSearchResult
  144. metadataForSection.createMetadatas()
  145. for metadata in metadatas {
  146. if let rowIndex = metadataForSection.metadatas.firstIndex(where: {$0.ocId == metadata.ocId}) {
  147. indexPaths.append(IndexPath(row: rowIndex, section: sectionIndex))
  148. }
  149. }
  150. }
  151. // MARK: -
  152. func getMetadatas() -> [tableMetadata] {
  153. return self.metadatas
  154. }
  155. func isEmpty() -> Bool {
  156. return self.metadatas.isEmpty
  157. }
  158. func getIndexPathMetadata(ocId: String) -> IndexPath? {
  159. guard self.sectionsValue.isEmpty else { return nil }
  160. let validMetadatas = self.metadatas.filter { !$0.isInvalidated }
  161. if let rowIndex = validMetadatas.firstIndex(where: {$0.ocId == ocId}) {
  162. return IndexPath(row: rowIndex, section: 0)
  163. }
  164. return nil
  165. }
  166. func numberOfSections() -> Int {
  167. guard !self.sectionsValue.isEmpty else { return 1 }
  168. return self.sectionsValue.count
  169. }
  170. func numberOfItemsInSection(_ section: Int) -> Int {
  171. if self.sectionsValue.isEmpty {
  172. let validMetadatas = metadatas.filter { !$0.isInvalidated }
  173. return validMetadatas.count
  174. }
  175. guard !self.metadatas.isEmpty,
  176. let metadataForSection = getMetadataForSection(section)
  177. else { return 0}
  178. return metadataForSection.metadatas.count
  179. }
  180. func getSectionValueLocalization(indexPath: IndexPath) -> String {
  181. guard !metadatasForSection.isEmpty, let metadataForSection = self.getMetadataForSection(indexPath.section) else { return ""}
  182. if let searchResults = self.searchResults, let searchResult = searchResults.filter({ $0.id == metadataForSection.sectionValue}).first {
  183. return searchResult.name
  184. }
  185. return metadataForSection.sectionValue
  186. }
  187. func getFooterInformation() -> (directories: Int, files: Int, size: Int64) {
  188. let validMetadatas = metadatas.filter { !$0.isInvalidated }
  189. let directories = validMetadatas.filter({ $0.directory == true})
  190. let files = validMetadatas.filter({ $0.directory == false})
  191. var size: Int64 = 0
  192. files.forEach { metadata in
  193. size += metadata.size
  194. }
  195. return (directories.count, files.count, size)
  196. }
  197. func getResultMetadata(indexPath: IndexPath) -> tableMetadata? {
  198. let validMetadatas = metadatas.filter { !$0.isInvalidated }
  199. if indexPath.row < validMetadatas.count {
  200. return validMetadatas[indexPath.row]
  201. }
  202. return nil
  203. }
  204. func getMetadata(indexPath: IndexPath) -> tableMetadata? {
  205. if !metadatasForSection.isEmpty, indexPath.section < metadatasForSection.count {
  206. if let metadataForSection = getMetadataForSection(indexPath.section),
  207. indexPath.row < metadataForSection.metadatas.count,
  208. !metadataForSection.metadatas[indexPath.row].isInvalidated {
  209. return tableMetadata(value: metadataForSection.metadatas[indexPath.row])
  210. }
  211. } else if indexPath.row < self.metadatas.count {
  212. if let metadata = metadataIndexPath[indexPath] {
  213. return metadata
  214. } else {
  215. let validMetadatas = self.metadatas.filter { !$0.isInvalidated }
  216. let metadata = tableMetadata(value: validMetadatas[indexPath.row])
  217. metadataIndexPath[indexPath] = metadata
  218. return metadata
  219. }
  220. }
  221. return nil
  222. }
  223. func caching(metadatas: [tableMetadata], dataSourceMetadatas: [tableMetadata], completion: @escaping (_ update: Bool) -> Void) {
  224. var counter: Int = 0
  225. var updated: Bool = dataSourceMetadatas.isEmpty
  226. DispatchQueue.global().async {
  227. for metadata in metadatas {
  228. let indexPath = IndexPath(row: counter, section: 0)
  229. if indexPath.row < dataSourceMetadatas.count {
  230. if !metadata.isEqual(dataSourceMetadatas[indexPath.row]) {
  231. updated = true
  232. }
  233. } else {
  234. updated = true
  235. }
  236. self.metadataIndexPath[indexPath] = tableMetadata(value: metadata)
  237. /// caching preview
  238. ///
  239. if metadata.isImageOrVideo,
  240. NCImageCache.shared.getImageCache(ocId: metadata.ocId, etag: metadata.etag, ext: self.global.previewExt256) == nil,
  241. let image = self.utility.getImage(ocId: metadata.ocId, etag: metadata.etag, ext: self.global.previewExt256) {
  242. NCImageCache.shared.addImageCache(ocId: metadata.ocId, etag: metadata.etag, image: image, ext: self.global.previewExt256, cost: counter)
  243. }
  244. counter += 1
  245. }
  246. DispatchQueue.main.async {
  247. return completion(updated)
  248. }
  249. }
  250. }
  251. func removeImageCache() {
  252. DispatchQueue.global().async {
  253. for metadata in self.metadatas {
  254. NCImageCache.shared.removeImageCache(ocIdPlusEtag: metadata.ocId + metadata.etag)
  255. }
  256. }
  257. }
  258. // MARK: -
  259. internal func isSameNumbersOfSections(numberOfSections: Int) -> Bool {
  260. guard !self.metadatasForSection.isEmpty else { return false }
  261. return numberOfSections == self.numberOfSections()
  262. }
  263. internal func getSectionValue(metadata: tableMetadata) -> String {
  264. switch self.layoutForView?.groupBy {
  265. case "name", "none":
  266. return NSLocalizedString(metadata.name, comment: "")
  267. case "classFile":
  268. return NSLocalizedString(metadata.classFile, comment: "").lowercased().firstUppercased
  269. default:
  270. return NSLocalizedString(metadata.name, comment: "")
  271. }
  272. }
  273. internal func getIndexMetadatasForSection(_ sectionValue: String) -> Int? {
  274. return self.metadatasForSection.firstIndex(where: {$0.sectionValue == sectionValue })
  275. }
  276. internal func getSectionIndex(_ sectionValue: String) -> Int? {
  277. return self.sectionsValue.firstIndex(where: {$0 == sectionValue })
  278. }
  279. internal func existsMetadataForSection(sectionValue: String) -> Bool {
  280. return !self.metadatasForSection.filter({ $0.sectionValue == sectionValue }).isEmpty
  281. }
  282. internal func getMetadataForSection(_ section: Int) -> NCMetadataForSection? {
  283. guard section < sectionsValue.count, let metadataForSection = self.metadatasForSection.filter({ $0.sectionValue == sectionsValue[section]}).first else { return nil }
  284. return metadataForSection
  285. }
  286. internal func getMetadataForSection(_ sectionValue: String) -> NCMetadataForSection? {
  287. guard let metadataForSection = self.metadatasForSection.filter({ $0.sectionValue == sectionValue }).first else { return nil }
  288. return metadataForSection
  289. }
  290. }
  291. // MARK: -
  292. class NCMetadataForSection: NSObject {
  293. var sectionValue: String
  294. var metadatas: [tableMetadata]
  295. var lastSearchResult: NKSearchResult?
  296. var unifiedSearchInProgress: Bool = false
  297. var layoutForView: NCDBLayoutForView?
  298. private var metadatasSorted: [tableMetadata] = []
  299. private var metadatasFavoriteDirectory: [tableMetadata] = []
  300. private var metadatasFavoriteFile: [tableMetadata] = []
  301. private var metadatasDirectory: [tableMetadata] = []
  302. private var metadatasFile: [tableMetadata] = []
  303. public var numDirectory: Int = 0
  304. public var numFile: Int = 0
  305. public var totalSize: Int64 = 0
  306. init(sectionValue: String, metadatas: [tableMetadata], lastSearchResult: NKSearchResult?, layoutForView: NCDBLayoutForView?) {
  307. self.sectionValue = sectionValue
  308. self.metadatas = metadatas
  309. self.lastSearchResult = lastSearchResult
  310. self.layoutForView = layoutForView
  311. super.init()
  312. createMetadatas()
  313. }
  314. func createMetadatas() {
  315. // Clear
  316. //
  317. metadatasSorted.removeAll()
  318. metadatasFavoriteDirectory.removeAll()
  319. metadatasFavoriteFile.removeAll()
  320. metadatasDirectory.removeAll()
  321. metadatasFile.removeAll()
  322. numDirectory = 0
  323. numFile = 0
  324. totalSize = 0
  325. var ocIds: [String] = []
  326. let metadataInSession = metadatas.filter({ !$0.session.isEmpty })
  327. // Metadata order
  328. //
  329. if let layoutForView = self.layoutForView, layoutForView.sort != "none" && !layoutForView.sort.isEmpty {
  330. metadatasSorted = metadatas.sorted {
  331. switch layoutForView.sort {
  332. case "date":
  333. if layoutForView.ascending {
  334. return ($0.date as Date) < ($1.date as Date)
  335. } else {
  336. return ($0.date as Date) > ($1.date as Date)
  337. }
  338. case "size":
  339. if layoutForView.ascending {
  340. return $0.size < $1.size
  341. } else {
  342. return $0.size > $1.size
  343. }
  344. default:
  345. if layoutForView.ascending {
  346. return $0.fileNameView.lowercased() < $1.fileNameView.lowercased()
  347. } else {
  348. return $0.fileNameView.lowercased() > $1.fileNameView.lowercased()
  349. }
  350. }
  351. }
  352. } else {
  353. metadatasSorted = metadatas
  354. }
  355. // Initialize datasource
  356. //
  357. for metadata in metadatasSorted {
  358. // skipped the root file
  359. if metadata.fileName == "." || metadata.serverUrl == ".." {
  360. continue
  361. }
  362. // skipped livePhoto VIDEO part
  363. if metadata.isLivePhoto,
  364. metadata.classFile == NKCommon.TypeClassFile.video.rawValue {
  365. continue
  366. }
  367. // Upload [REPLACE] skip
  368. if metadata.session.isEmpty && !metadataInSession.filter({ $0.fileNameView == metadata.fileNameView }).isEmpty {
  369. continue
  370. }
  371. // Upload [REPLACE] skip
  372. if metadata.session.isEmpty && !metadataInSession.filter({ $0.fileNameView == metadata.fileNameView }).isEmpty {
  373. continue
  374. }
  375. // Organized the metadata
  376. if metadata.favorite {
  377. if metadata.directory {
  378. metadatasFavoriteDirectory.append(metadata)
  379. } else {
  380. metadatasFavoriteFile.append(metadata)
  381. }
  382. } else if metadata.directory && layoutForView?.directoryOnTop ?? true {
  383. metadatasDirectory.append(metadata)
  384. } else {
  385. metadatasFile.append(metadata)
  386. }
  387. if metadata.directory {
  388. ocIds.append(metadata.ocId)
  389. numDirectory += 1
  390. } else {
  391. numFile += 1
  392. totalSize += metadata.size
  393. }
  394. }
  395. metadatas.removeAll()
  396. // Struct view : favorite dir -> favorite file -> directory -> files
  397. metadatas += metadatasFavoriteDirectory
  398. metadatas += metadatasFavoriteFile
  399. metadatas += metadatasDirectory
  400. metadatas += metadatasFile
  401. }
  402. }