NCManageDatabase.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. import CommonCrypto
  30. protocol DateCompareable {
  31. var dateKey: Date { get }
  32. }
  33. class NCManageDatabase: NSObject {
  34. @objc static let shared: NCManageDatabase = {
  35. let instance = NCManageDatabase()
  36. return instance
  37. }()
  38. let utilityFileSystem = NCUtilityFileSystem()
  39. override init() {
  40. func migrationSchema(_ migration: Migration, _ oldSchemaVersion: UInt64) {
  41. if oldSchemaVersion < 365 {
  42. migration.deleteData(forType: tableMetadata.className())
  43. migration.enumerateObjects(ofType: tableDirectory.className()) { _, newObject in
  44. newObject?["etag"] = ""
  45. }
  46. }
  47. }
  48. func compactDB(_ totalBytes: Int, _ usedBytes: Int) -> Bool {
  49. let usedPercentage = (Double(usedBytes) / Double(totalBytes)) * 100
  50. /// Compact the database if more than 25% of the space is free
  51. let shouldCompact = (usedPercentage < 75.0) && (totalBytes > 100 * 1024 * 1024)
  52. return shouldCompact
  53. }
  54. var realm: Realm?
  55. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  56. let databaseFileUrlPath = dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + databaseName)
  57. let bundleUrl: URL = Bundle.main.bundleURL
  58. let bundlePathExtension: String = bundleUrl.pathExtension
  59. let bundleFileName: String = (bundleUrl.path as NSString).lastPathComponent
  60. let isAppex: Bool = bundlePathExtension == "appex"
  61. var objectTypesAppex = [NCKeyValue.self,
  62. tableMetadata.self,
  63. tableLocalFile.self,
  64. tableDirectory.self,
  65. tableTag.self,
  66. tableAccount.self,
  67. tableCapabilities.self,
  68. tablePhotoLibrary.self,
  69. tableE2eEncryption.self,
  70. tableE2eEncryptionLock.self,
  71. tableE2eMetadata12.self,
  72. tableE2eMetadata.self,
  73. tableE2eUsers.self,
  74. tableE2eCounter.self,
  75. tableShare.self,
  76. tableChunk.self,
  77. tableAvatar.self,
  78. tableDashboardWidget.self,
  79. tableDashboardWidgetButton.self,
  80. NCDBLayoutForView.self,
  81. TableSecurityGuardDiagnostics.self]
  82. // Disable file protection for directory DB
  83. // https://docs.mongodb.com/realm/sdk/ios/examples/configure-and-open-a-realm/#std-label-ios-open-a-local-realm
  84. if let folderPathURL = dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud) {
  85. let folderPath = folderPathURL.path
  86. do {
  87. try FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: folderPath)
  88. } catch {
  89. print("Dangerous error")
  90. }
  91. }
  92. if isAppex {
  93. if bundleFileName == "File Provider Extension.appex" {
  94. objectTypesAppex = [NCKeyValue.self,
  95. tableMetadata.self,
  96. tableLocalFile.self,
  97. tableDirectory.self,
  98. tableTag.self,
  99. tableAccount.self,
  100. tableCapabilities.self,
  101. tableE2eEncryption.self]
  102. }
  103. do {
  104. Realm.Configuration.defaultConfiguration =
  105. Realm.Configuration(fileURL: databaseFileUrlPath,
  106. schemaVersion: databaseSchemaVersion,
  107. migrationBlock: { migration, oldSchemaVersion in
  108. migrationSchema(migration, oldSchemaVersion)
  109. }, shouldCompactOnLaunch: { totalBytes, usedBytes in
  110. compactDB(totalBytes, usedBytes)
  111. }, objectTypes: objectTypesAppex)
  112. realm = try Realm()
  113. if let realm, let url = realm.configuration.fileURL {
  114. print("Realm is located at: \(url)")
  115. }
  116. } catch let error {
  117. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] DATABASE ERROR: \(error.localizedDescription)")
  118. }
  119. } else {
  120. do {
  121. Realm.Configuration.defaultConfiguration =
  122. Realm.Configuration(fileURL: databaseFileUrlPath,
  123. schemaVersion: databaseSchemaVersion,
  124. migrationBlock: { migration, oldSchemaVersion in
  125. migrationSchema(migration, oldSchemaVersion)
  126. }, shouldCompactOnLaunch: { totalBytes, usedBytes in
  127. compactDB(totalBytes, usedBytes)
  128. })
  129. realm = try Realm()
  130. if let realm, let url = realm.configuration.fileURL {
  131. print("Realm is located at: \(url)")
  132. }
  133. } catch let error {
  134. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] DATABASE ERROR: \(error.localizedDescription)")
  135. }
  136. }
  137. }
  138. // MARK: -
  139. // MARK: Utility Database
  140. func clearTable(_ table: Object.Type, account: String? = nil) {
  141. do {
  142. let realm = try Realm()
  143. try realm.write {
  144. var results: Results<Object>
  145. if let account = account {
  146. results = realm.objects(table).filter("account == %@", account)
  147. } else {
  148. results = realm.objects(table)
  149. }
  150. realm.delete(results)
  151. }
  152. } catch let error {
  153. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  154. }
  155. }
  156. func clearDatabase(account: String? = nil, removeAccount: Bool = false) {
  157. if removeAccount {
  158. self.clearTable(tableAccount.self, account: account)
  159. }
  160. self.clearTable(tableActivity.self, account: account)
  161. self.clearTable(tableActivityLatestId.self, account: account)
  162. self.clearTable(tableActivityPreview.self, account: account)
  163. self.clearTable(tableActivitySubjectRich.self, account: account)
  164. self.clearTable(tableAvatar.self)
  165. self.clearTable(tableCapabilities.self, account: account)
  166. self.clearTable(tableChunk.self, account: account)
  167. self.clearTable(tableComments.self, account: account)
  168. self.clearTable(tableDashboardWidget.self, account: account)
  169. self.clearTable(tableDashboardWidgetButton.self, account: account)
  170. self.clearTable(tableDirectEditingCreators.self, account: account)
  171. self.clearTable(tableDirectEditingEditors.self, account: account)
  172. self.clearTable(tableDirectory.self, account: account)
  173. self.clearTablesE2EE(account: account)
  174. self.clearTable(tableExternalSites.self, account: account)
  175. self.clearTable(tableGPS.self, account: nil)
  176. self.clearTable(TableGroupfolders.self, account: account)
  177. self.clearTable(TableGroupfoldersGroups.self, account: account)
  178. self.clearTable(tableLocalFile.self, account: account)
  179. self.clearTable(tableMetadata.self, account: account)
  180. self.clearTable(tablePhotoLibrary.self, account: account)
  181. self.clearTable(tableShare.self, account: account)
  182. self.clearTable(TableSecurityGuardDiagnostics.self, account: account)
  183. self.clearTable(tableTag.self, account: account)
  184. self.clearTable(tableTrash.self, account: account)
  185. self.clearTable(tableUserStatus.self, account: account)
  186. self.clearTable(tableVideo.self, account: account)
  187. }
  188. func clearTablesE2EE(account: String?) {
  189. self.clearTable(tableE2eEncryption.self, account: account)
  190. self.clearTable(tableE2eEncryptionLock.self, account: account)
  191. self.clearTable(tableE2eMetadata12.self, account: account)
  192. self.clearTable(tableE2eMetadata.self, account: account)
  193. self.clearTable(tableE2eUsers.self, account: account)
  194. self.clearTable(tableE2eCounter.self, account: account)
  195. }
  196. func getThreadConfined(_ object: Object) -> Any {
  197. return ThreadSafeReference(to: object)
  198. }
  199. func putThreadConfined(_ tableRef: ThreadSafeReference<Object>) -> Object? {
  200. do {
  201. let realm = try Realm()
  202. return realm.resolve(tableRef)
  203. } catch let error as NSError {
  204. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  205. }
  206. return nil
  207. }
  208. func realmRefresh() {
  209. do {
  210. let realm = try Realm()
  211. realm.refresh()
  212. } catch let error as NSError {
  213. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not refresh database: \(error)")
  214. }
  215. }
  216. func sha256Hash(_ input: String) -> String {
  217. let data = Data(input.utf8)
  218. var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
  219. data.withUnsafeBytes {
  220. _ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &digest)
  221. }
  222. return digest.map { String(format: "%02hhx", $0) }.joined()
  223. }
  224. // MARK: -
  225. // MARK: Func T
  226. 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>? {
  227. let startIndex = recordsPerPage * (pageNumber - 1)
  228. do {
  229. let realm = try Realm()
  230. var results = realm.objects(type)
  231. if let filter, let sortedByKeyPath {
  232. results = results.filter(filter).sorted(byKeyPath: sortedByKeyPath, ascending: sortedAscending)
  233. }
  234. guard startIndex < results.count else {
  235. return nil
  236. }
  237. let pagedResults = results.dropFirst(startIndex).prefix(recordsPerPage)
  238. let pagedResultsKeys = pagedResults.compactMap { $0.value(forKey: primaryKey) as? String }
  239. return realm.objects(type).filter("\(primaryKey) IN %@", Array(pagedResultsKeys))
  240. } catch {
  241. print("Error opening Realm: \(error)")
  242. return nil
  243. }
  244. }
  245. // MARK: -
  246. // MARK: SWIFTUI PREVIEW
  247. func previewCreateDB() {
  248. /// Account
  249. let account = "marinofaggiana https://cloudtest.nextcloud.com"
  250. let account2 = "mariorossi https://cloudtest.nextcloud.com"
  251. addAccount(account, urlBase: "https://cloudtest.nextcloud.com", user: "marinofaggiana", userId: "marinofaggiana", password: "password")
  252. addAccount(account2, urlBase: "https://cloudtest.nextcloud.com", user: "mariorossi", userId: "mariorossi", password: "password")
  253. let userProfile = NKUserProfile()
  254. userProfile.displayName = "Marino Faggiana"
  255. userProfile.address = "Hirschstrasse 26, 70192 Stuttgart, Germany"
  256. userProfile.phone = "+49 (711) 252 428 - 90"
  257. userProfile.email = "cloudtest@nextcloud.com"
  258. setAccountUserProfile(account: account, userProfile: userProfile)
  259. let userProfile2 = NKUserProfile()
  260. userProfile2.displayName = "Mario Rossi"
  261. userProfile2.email = "cloudtest@nextcloud.com"
  262. setAccountUserProfile(account: account2, userProfile: userProfile2)
  263. }
  264. }
  265. class NCKeyValue: Object {
  266. @Persisted var key: String = ""
  267. @Persisted var value: String?
  268. }