NCManageDatabase.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. //
  2. // NCManageDatabase.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 06/05/17.
  6. // Copyright © 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. // Author Henrik Storch <henrik.storch@nextcloud.com>
  10. //
  11. // This program is free software: you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published by
  13. // the Free Software Foundation, either version 3 of the License, or
  14. // (at your option) any later version.
  15. //
  16. // This program is distributed in the hope that it will be useful,
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. // GNU General Public License for more details.
  20. //
  21. // You should have received a copy of the GNU General Public License
  22. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. //
  24. import UIKit
  25. import RealmSwift
  26. import NextcloudKit
  27. import CoreMedia
  28. import Photos
  29. protocol DateCompareable {
  30. var dateKey: Date { get }
  31. }
  32. class NCManageDatabase: NSObject {
  33. @objc static let shared: NCManageDatabase = {
  34. let instance = NCManageDatabase()
  35. return instance
  36. }()
  37. let utilityFileSystem = NCUtilityFileSystem()
  38. override init() {
  39. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  40. let databaseFileUrlPath = dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + databaseName)
  41. if let databaseFilePath = databaseFileUrlPath?.path {
  42. if FileManager.default.fileExists(atPath: databaseFilePath) {
  43. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] DATABASE FOUND in " + databaseFilePath)
  44. } else {
  45. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] DATABASE NOT FOUND in " + databaseFilePath)
  46. }
  47. }
  48. // Disable file protection for directory DB
  49. // https://docs.mongodb.com/realm/sdk/ios/examples/configure-and-open-a-realm/#std-label-ios-open-a-local-realm
  50. if let folderPathURL = dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud) {
  51. let folderPath = folderPathURL.path
  52. do {
  53. try FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: folderPath)
  54. } catch {
  55. print("Dangerous error")
  56. }
  57. }
  58. do {
  59. _ = try Realm(configuration: Realm.Configuration(
  60. fileURL: databaseFileUrlPath,
  61. schemaVersion: databaseSchemaVersion,
  62. migrationBlock: { migration, oldSchemaVersion in
  63. if oldSchemaVersion < 354 {
  64. migration.deleteData(forType: NCDBLayoutForView.className())
  65. }
  66. }, shouldCompactOnLaunch: { totalBytes, usedBytes in
  67. // totalBytes refers to the size of the file on disk in bytes (data + free space)
  68. // usedBytes refers to the number of bytes used by data in the file
  69. // Compact if the file is over 100MB in size and less than 50% 'used'
  70. let oneHundredMB = 100 * 1024 * 1024
  71. return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
  72. }
  73. ))
  74. } catch let error {
  75. if let databaseFileUrlPath = databaseFileUrlPath {
  76. do {
  77. #if !EXTENSION
  78. let nkError = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: error.localizedDescription)
  79. NCContentPresenter().showError(error: nkError, priority: .max)
  80. #endif
  81. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] DATABASE ERROR: \(error.localizedDescription)")
  82. try FileManager.default.removeItem(at: databaseFileUrlPath)
  83. } catch {}
  84. }
  85. }
  86. Realm.Configuration.defaultConfiguration = Realm.Configuration(
  87. fileURL: dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + databaseName),
  88. schemaVersion: databaseSchemaVersion
  89. )
  90. // Verify Database, if corrupt remove it
  91. do {
  92. _ = try Realm()
  93. } catch let error {
  94. if let databaseFileUrlPath = databaseFileUrlPath {
  95. do {
  96. #if !EXTENSION
  97. let nkError = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: error.localizedDescription)
  98. NCContentPresenter().showError(error: nkError, priority: .max)
  99. #endif
  100. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] DATABASE ERROR: \(error.localizedDescription)")
  101. try FileManager.default.removeItem(at: databaseFileUrlPath)
  102. } catch { }
  103. }
  104. }
  105. do {
  106. _ = try Realm()
  107. } catch let error as NSError {
  108. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not open database: \(error)")
  109. }
  110. }
  111. // MARK: -
  112. // MARK: Utility Database
  113. func clearTable(_ table: Object.Type, account: String? = nil) {
  114. do {
  115. let realm = try Realm()
  116. try realm.write {
  117. var results: Results<Object>
  118. if let account = account {
  119. results = realm.objects(table).filter("account == %@", account)
  120. } else {
  121. results = realm.objects(table)
  122. }
  123. realm.delete(results)
  124. }
  125. } catch let error {
  126. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  127. }
  128. }
  129. func clearDatabase(account: String?, removeAccount: Bool) {
  130. if removeAccount {
  131. self.clearTable(tableAccount.self, account: account)
  132. }
  133. self.clearTable(tableActivity.self, account: account)
  134. self.clearTable(tableActivityLatestId.self, account: account)
  135. self.clearTable(tableActivityPreview.self, account: account)
  136. self.clearTable(tableActivitySubjectRich.self, account: account)
  137. self.clearTable(tableAvatar.self)
  138. self.clearTable(tableCapabilities.self, account: account)
  139. self.clearTable(tableChunk.self, account: account)
  140. self.clearTable(tableComments.self, account: account)
  141. self.clearTable(tableDashboardWidget.self, account: account)
  142. self.clearTable(tableDashboardWidgetButton.self, account: account)
  143. self.clearTable(tableDirectEditingCreators.self, account: account)
  144. self.clearTable(tableDirectEditingEditors.self, account: account)
  145. self.clearTable(tableDirectory.self, account: account)
  146. self.clearTablesE2EE(account: account)
  147. self.clearTable(tableExternalSites.self, account: account)
  148. self.clearTable(tableGPS.self, account: nil)
  149. self.clearTable(TableGroupfolders.self, account: account)
  150. self.clearTable(TableGroupfoldersGroups.self, account: account)
  151. self.clearTable(tableLocalFile.self, account: account)
  152. self.clearTable(tableMetadata.self, account: account)
  153. self.clearTable(tablePhotoLibrary.self, account: account)
  154. self.clearTable(tableShare.self, account: account)
  155. self.clearTable(TableSecurityGuardDiagnostics.self, account: account)
  156. self.clearTable(tableTag.self, account: account)
  157. self.clearTable(tableTrash.self, account: account)
  158. self.clearTable(tableUserStatus.self, account: account)
  159. self.clearTable(tableVideo.self, account: account)
  160. }
  161. func clearTablesE2EE(account: String?) {
  162. self.clearTable(tableE2eEncryption.self, account: account)
  163. self.clearTable(tableE2eEncryptionLock.self, account: account)
  164. self.clearTable(tableE2eMetadata12.self, account: account)
  165. self.clearTable(tableE2eMetadata.self, account: account)
  166. self.clearTable(tableE2eUsers.self, account: account)
  167. self.clearTable(tableE2eCounter.self, account: account)
  168. }
  169. @objc func removeDB() {
  170. let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
  171. let realmURLs = [
  172. realmURL,
  173. realmURL.appendingPathExtension("lock"),
  174. realmURL.appendingPathExtension("note"),
  175. realmURL.appendingPathExtension("management")
  176. ]
  177. for URL in realmURLs {
  178. do {
  179. try FileManager.default.removeItem(at: URL)
  180. } catch let error {
  181. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  182. }
  183. }
  184. }
  185. func getThreadConfined(_ object: Object) -> Any {
  186. return ThreadSafeReference(to: object)
  187. }
  188. func putThreadConfined(_ tableRef: ThreadSafeReference<Object>) -> Object? {
  189. do {
  190. let realm = try Realm()
  191. return realm.resolve(tableRef)
  192. } catch let error as NSError {
  193. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  194. }
  195. return nil
  196. }
  197. // MARK: -
  198. // MARK: Func T
  199. func fetchPagedResults<T: Object>(ofType type: T.Type, primaryKey: String, recordsPerPage: Int, pageNumber: Int, filter: NSPredicate? = nil, sortedByKeyPath: String? = nil, sortedAscending: Bool = true) -> Results<T>? {
  200. let startIndex = recordsPerPage * (pageNumber - 1)
  201. do {
  202. let realm = try Realm()
  203. var results = realm.objects(type)
  204. if let filter, let sortedByKeyPath {
  205. results = results.filter(filter).sorted(byKeyPath: sortedByKeyPath, ascending: sortedAscending)
  206. }
  207. guard startIndex < results.count else {
  208. return nil
  209. }
  210. let pagedResults = results.dropFirst(startIndex).prefix(recordsPerPage)
  211. let pagedResultsKeys = pagedResults.compactMap { $0.value(forKey: primaryKey) as? String }
  212. return realm.objects(type).filter("\(primaryKey) IN %@", Array(pagedResultsKeys))
  213. } catch {
  214. print("Error opening Realm: \(error)")
  215. return nil
  216. }
  217. }
  218. // MARK: -
  219. // MARK: SWIFTUI PREVIEW
  220. func previewCreateDB() {
  221. /// Account
  222. let account = "marinofaggiana https://cloudtest.nextcloud.com"
  223. let account2 = "mariorossi https://cloudtest.nextcloud.com"
  224. NCManageDatabase.shared.addAccount(account, urlBase: "https://cloudtest.nextcloud.com", user: "marinofaggiana", userId: "marinofaggiana", password: "password")
  225. NCManageDatabase.shared.addAccount(account2, urlBase: "https://cloudtest.nextcloud.com", user: "mariorossi", userId: "mariorossi", password: "password")
  226. let userProfile = NKUserProfile()
  227. userProfile.displayName = "Marino Faggiana"
  228. userProfile.address = "Hirschstrasse 26, 70192 Stuttgart, Germany"
  229. userProfile.phone = "+49 (711) 252 428 - 90"
  230. userProfile.email = "cloudtest@nextcloud.com"
  231. NCManageDatabase.shared.setAccountUserProfile(account: account, userProfile: userProfile)
  232. let userProfile2 = NKUserProfile()
  233. userProfile2.displayName = "Mario Rossi"
  234. userProfile2.email = "cloudtest@nextcloud.com"
  235. NCManageDatabase.shared.setAccountUserProfile(account: account2, userProfile: userProfile2)
  236. }
  237. }