NCDataSource.swift 21 KB

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