NCDataSource.swift 22 KB

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