NCManageDatabase.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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.capabilitiesGroups)
  40. let databaseFileUrlPath = dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + databaseName)
  41. let bundleUrl: URL = Bundle.main.bundleURL
  42. let bundlePathExtension: String = bundleUrl.pathExtension
  43. let isAppex: Bool = bundlePathExtension == "appex"
  44. if let databaseFilePath = databaseFileUrlPath?.path {
  45. if FileManager.default.fileExists(atPath: databaseFilePath) {
  46. NextcloudKit.shared.nkCommonInstance.writeLog("DATABASE FOUND in " + databaseFilePath)
  47. } else {
  48. NextcloudKit.shared.nkCommonInstance.writeLog("DATABASE NOT FOUND in " + databaseFilePath)
  49. }
  50. }
  51. // Disable file protection for directory DB
  52. // https://docs.mongodb.com/realm/sdk/ios/examples/configure-and-open-a-realm/#std-label-ios-open-a-local-realm
  53. if let folderPathURL = dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud) {
  54. let folderPath = folderPathURL.path
  55. do {
  56. try FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: folderPath)
  57. } catch {
  58. print("Dangerous error")
  59. }
  60. }
  61. if isAppex {
  62. Realm.Configuration.defaultConfiguration = Realm.Configuration(
  63. fileURL: dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + databaseName),
  64. schemaVersion: databaseSchemaVersion,
  65. objectTypes: [tableMetadata.self,
  66. tableLocalFile.self,
  67. tableDirectory.self,
  68. tableTag.self,
  69. tableAccount.self,
  70. tableCapabilities.self,
  71. tablePhotoLibrary.self,
  72. tableE2eEncryption.self,
  73. tableE2eEncryptionLock.self,
  74. tableE2eMetadata12.self,
  75. tableE2eMetadata.self,
  76. tableE2eUsers.self,
  77. tableE2eCounter.self,
  78. tableE2eUsersFiledrop.self,
  79. tableShare.self,
  80. tableChunk.self,
  81. tableAvatar.self,
  82. tableDashboardWidget.self,
  83. tableDashboardWidgetButton.self,
  84. NCDBLayoutForView.self]
  85. )
  86. } else {
  87. do {
  88. _ = try Realm(configuration: Realm.Configuration(
  89. fileURL: databaseFileUrlPath,
  90. schemaVersion: databaseSchemaVersion,
  91. migrationBlock: { migration, oldSchemaVersion in
  92. if oldSchemaVersion < 255 {
  93. migration.deleteData(forType: tableActivity.className())
  94. migration.deleteData(forType: tableActivityLatestId.className())
  95. migration.deleteData(forType: tableActivityPreview.className())
  96. migration.deleteData(forType: tableActivitySubjectRich.className())
  97. migration.deleteData(forType: tableDirectory.className())
  98. migration.deleteData(forType: tableMetadata.className())
  99. }
  100. if oldSchemaVersion < 292 {
  101. migration.deleteData(forType: tableVideo.className())
  102. }
  103. if oldSchemaVersion < 319 {
  104. migration.deleteData(forType: tableChunk.className())
  105. migration.deleteData(forType: tableMetadata.className())
  106. migration.deleteData(forType: tableDirectory.className())
  107. migration.deleteData(forType: tableE2eEncryptionLock.className())
  108. migration.deleteData(forType: tableGPS.className())
  109. }
  110. }, shouldCompactOnLaunch: { totalBytes, usedBytes in
  111. // totalBytes refers to the size of the file on disk in bytes (data + free space)
  112. // usedBytes refers to the number of bytes used by data in the file
  113. // Compact if the file is over 100MB in size and less than 50% 'used'
  114. let oneHundredMB = 100 * 1024 * 1024
  115. return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
  116. }
  117. ))
  118. } catch let error {
  119. if let databaseFileUrlPath = databaseFileUrlPath {
  120. do {
  121. #if !EXTENSION
  122. let nkError = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: error.localizedDescription)
  123. NCContentPresenter().showError(error: nkError, priority: .max)
  124. #endif
  125. NextcloudKit.shared.nkCommonInstance.writeLog("DATABASE ERROR: \(error.localizedDescription)")
  126. try FileManager.default.removeItem(at: databaseFileUrlPath)
  127. } catch {}
  128. }
  129. }
  130. Realm.Configuration.defaultConfiguration = Realm.Configuration(
  131. fileURL: dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + databaseName),
  132. schemaVersion: databaseSchemaVersion
  133. )
  134. }
  135. // Verify Database, if corrupt remove it
  136. do {
  137. _ = try Realm()
  138. } catch let error {
  139. if let databaseFileUrlPath = databaseFileUrlPath {
  140. do {
  141. #if !EXTENSION
  142. let nkError = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: error.localizedDescription)
  143. NCContentPresenter().showError(error: nkError, priority: .max)
  144. #endif
  145. NextcloudKit.shared.nkCommonInstance.writeLog("DATABASE ERROR: \(error.localizedDescription)")
  146. try FileManager.default.removeItem(at: databaseFileUrlPath)
  147. } catch { }
  148. }
  149. }
  150. do {
  151. _ = try Realm()
  152. } catch let error as NSError {
  153. NextcloudKit.shared.nkCommonInstance.writeLog("Could not open database: \(error)")
  154. }
  155. }
  156. // MARK: -
  157. // MARK: Utility Database
  158. @objc func clearTable(_ table: Object.Type, account: String? = nil) {
  159. do {
  160. let realm = try Realm()
  161. try realm.write {
  162. var results: Results<Object>
  163. if let account = account {
  164. results = realm.objects(table).filter("account == %@", account)
  165. } else {
  166. results = realm.objects(table)
  167. }
  168. realm.delete(results)
  169. }
  170. } catch let error {
  171. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  172. }
  173. }
  174. @objc func clearDatabase(account: String?, removeAccount: Bool) {
  175. if removeAccount {
  176. self.clearTable(tableAccount.self, account: account)
  177. }
  178. self.clearTable(tableActivity.self, account: account)
  179. self.clearTable(tableActivityLatestId.self, account: account)
  180. self.clearTable(tableActivityPreview.self, account: account)
  181. self.clearTable(tableActivitySubjectRich.self, account: account)
  182. self.clearTable(tableAvatar.self)
  183. self.clearTable(tableCapabilities.self, account: account)
  184. self.clearTable(tableChunk.self, account: account)
  185. self.clearTable(tableComments.self, account: account)
  186. self.clearTable(tableDashboardWidget.self, account: account)
  187. self.clearTable(tableDashboardWidgetButton.self, account: account)
  188. self.clearTable(tableDirectEditingCreators.self, account: account)
  189. self.clearTable(tableDirectEditingEditors.self, account: account)
  190. self.clearTable(tableDirectory.self, account: account)
  191. self.clearTablesE2EE(account: account)
  192. self.clearTable(tableExternalSites.self, account: account)
  193. self.clearTable(tableGPS.self, account: nil)
  194. self.clearTable(TableGroupfolders.self, account: account)
  195. self.clearTable(TableGroupfoldersGroups.self, account: account)
  196. self.clearTable(NCDBLayoutForView.self, account: account)
  197. self.clearTable(tableLocalFile.self, account: account)
  198. self.clearTable(tableMetadata.self, account: account)
  199. self.clearTable(tablePhotoLibrary.self, account: account)
  200. self.clearTable(tableShare.self, account: account)
  201. self.clearTable(tableTag.self, account: account)
  202. self.clearTable(tableTip.self)
  203. self.clearTable(tableTrash.self, account: account)
  204. self.clearTable(tableUserStatus.self, account: account)
  205. self.clearTable(tableVideo.self, account: account)
  206. }
  207. func clearTablesE2EE(account: String?) {
  208. self.clearTable(tableE2eEncryption.self, account: account)
  209. self.clearTable(tableE2eEncryptionLock.self, account: account)
  210. self.clearTable(tableE2eMetadata12.self, account: account)
  211. self.clearTable(tableE2eMetadata.self, account: account)
  212. self.clearTable(tableE2eUsers.self, account: account)
  213. self.clearTable(tableE2eCounter.self, account: account)
  214. self.clearTable(tableE2eUsersFiledrop.self, account: account)
  215. }
  216. @objc func removeDB() {
  217. let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
  218. let realmURLs = [
  219. realmURL,
  220. realmURL.appendingPathExtension("lock"),
  221. realmURL.appendingPathExtension("note"),
  222. realmURL.appendingPathExtension("management")
  223. ]
  224. for URL in realmURLs {
  225. do {
  226. try FileManager.default.removeItem(at: URL)
  227. } catch let error {
  228. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  229. }
  230. }
  231. }
  232. func getThreadConfined(_ object: Object) -> Any {
  233. return ThreadSafeReference(to: object)
  234. }
  235. func putThreadConfined(_ tableRef: ThreadSafeReference<Object>) -> Object? {
  236. do {
  237. let realm = try Realm()
  238. return realm.resolve(tableRef)
  239. } catch let error as NSError {
  240. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  241. }
  242. return nil
  243. }
  244. }