NCDataSource.swift 21 KB

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