NCDataSource.swift 18 KB

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