NCDataSource.swift 22 KB

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