NCDataSource.swift 17 KB

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