NCDataSource.swift 22 KB

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