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