NCManageDatabase+Problems.swift 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // NCManageDatabase+Problems.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 15/03/22.
  6. // Copyright © 2022 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 Foundation
  24. import RealmSwift
  25. import NextcloudKit
  26. class tableProblems: Object {
  27. @Persisted var account = ""
  28. @Persisted(primaryKey: true) var primaryKey = ""
  29. @Persisted var type: String = ""
  30. @Persisted var count: Int = 0
  31. @Persisted var oldest: Double = 0
  32. }
  33. extension NCManageDatabase {
  34. func addProblem(account: String, type: String, error: NKError) {
  35. do {
  36. let realm = try Realm()
  37. try realm.write {
  38. let primaryKey = account + type
  39. if let result = realm.objects(tableProblems.self).filter("primaryKey %@", primaryKey).first {
  40. result.count += 1
  41. result.oldest = Date().timeIntervalSince1970
  42. realm.add(result, update: .all)
  43. } else {
  44. let result = tableProblems()
  45. result.count = 1
  46. result.oldest = Date().timeIntervalSince1970
  47. realm.add(result, update: .all)
  48. }
  49. }
  50. } catch let error {
  51. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  52. }
  53. }
  54. func getProblems(account: String) -> Results<tableProblems>? {
  55. do {
  56. let realm = try Realm()
  57. realm.refresh()
  58. return realm.objects(tableProblems.self).filter("account == %@", account)
  59. } catch let error as NSError {
  60. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  61. }
  62. return nil
  63. }
  64. func deleteProblems(account: String) {
  65. do {
  66. let realm = try Realm()
  67. try realm.write {
  68. let result = realm.objects(tableProblems.self).filter("account == %@", account)
  69. realm.delete(result)
  70. }
  71. } catch let error {
  72. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  73. }
  74. }
  75. }