NCDataSource.swift 16 KB

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