NCDataSource.swift 21 KB

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