NCDataSource.swift 17 KB

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