NCDataSource.swift 23 KB

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