NCDataSource.swift 22 KB

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