NCDataSource.swift 22 KB

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