NCManageDatabase.swift 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824
  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 NCCommunication
  27. import SwiftyJSON
  28. import CoreMedia
  29. class NCManageDatabase: NSObject {
  30. @objc static let shared: NCManageDatabase = {
  31. let instance = NCManageDatabase()
  32. return instance
  33. }()
  34. override init() {
  35. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.shared.capabilitiesGroups)
  36. let databaseFilePath = dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + NCGlobal.shared.databaseDefault)
  37. let bundleUrl: URL = Bundle.main.bundleURL
  38. let bundlePathExtension: String = bundleUrl.pathExtension
  39. let isAppex: Bool = bundlePathExtension == "appex"
  40. // Disable file protection for directory DB
  41. // https://docs.mongodb.com/realm/sdk/ios/examples/configure-and-open-a-realm/#std-label-ios-open-a-local-realm
  42. if let folderPathURL = dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud) {
  43. let folderPath = folderPathURL.path
  44. do {
  45. try FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: folderPath)
  46. } catch {
  47. print("Dangerous error")
  48. }
  49. }
  50. if isAppex {
  51. // App Extension config
  52. let config = Realm.Configuration(
  53. fileURL: dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + NCGlobal.shared.databaseDefault),
  54. schemaVersion: NCGlobal.shared.databaseSchemaVersion,
  55. objectTypes: [tableMetadata.self, tableLocalFile.self, tableDirectory.self, tableTag.self, tableAccount.self, tableCapabilities.self, tableE2eEncryption.self, tableE2eEncryptionLock.self, tableShare.self, tableChunk.self, tableAvatar.self]
  56. )
  57. Realm.Configuration.defaultConfiguration = config
  58. } else {
  59. // App config
  60. let configCompact = Realm.Configuration(
  61. fileURL: databaseFilePath,
  62. schemaVersion: NCGlobal.shared.databaseSchemaVersion,
  63. migrationBlock: { migration, oldSchemaVersion in
  64. if oldSchemaVersion < 61 {
  65. migration.deleteData(forType: tableShare.className())
  66. }
  67. if oldSchemaVersion < 74 {
  68. migration.enumerateObjects(ofType: tableLocalFile.className()) { oldObject, newObject in
  69. newObject!["ocId"] = oldObject!["fileID"]
  70. }
  71. migration.enumerateObjects(ofType: tableTrash.className()) { oldObject, newObject in
  72. newObject!["fileId"] = oldObject!["fileID"]
  73. }
  74. migration.enumerateObjects(ofType: tableTag.className()) { oldObject, newObject in
  75. newObject!["ocId"] = oldObject!["fileID"]
  76. }
  77. migration.enumerateObjects(ofType: tableE2eEncryptionLock.className()) { oldObject, newObject in
  78. newObject!["ocId"] = oldObject!["fileID"]
  79. }
  80. }
  81. if oldSchemaVersion < 87 {
  82. migration.deleteData(forType: tableActivity.className())
  83. migration.deleteData(forType: tableActivityPreview.className())
  84. migration.deleteData(forType: tableActivitySubjectRich.className())
  85. migration.deleteData(forType: tableExternalSites.className())
  86. migration.deleteData(forType: tableGPS.className())
  87. migration.deleteData(forType: tableTag.className())
  88. }
  89. if oldSchemaVersion < 120 {
  90. migration.deleteData(forType: tableCapabilities.className())
  91. migration.deleteData(forType: tableComments.className())
  92. }
  93. if oldSchemaVersion < 134 {
  94. migration.deleteData(forType: tableDirectEditingCreators.className())
  95. migration.deleteData(forType: tableDirectEditingEditors.className())
  96. migration.deleteData(forType: tableExternalSites.className())
  97. }
  98. if oldSchemaVersion < 141 {
  99. migration.enumerateObjects(ofType: tableAccount.className()) { oldObject, newObject in
  100. newObject!["urlBase"] = oldObject!["url"]
  101. }
  102. }
  103. if oldSchemaVersion < 162 {
  104. migration.enumerateObjects(ofType: tableAccount.className()) { oldObject, newObject in
  105. newObject!["userId"] = oldObject!["userID"]
  106. migration.deleteData(forType: tableMetadata.className())
  107. }
  108. }
  109. if oldSchemaVersion < 212 {
  110. migration.deleteData(forType: tableDirectory.className())
  111. migration.deleteData(forType: tableE2eEncryption.className())
  112. migration.deleteData(forType: tableE2eEncryptionLock.className())
  113. migration.deleteData(forType: tableMetadata.className())
  114. migration.deleteData(forType: tableShare.className())
  115. migration.deleteData(forType: tableTrash.className())
  116. migration.deleteData(forType: tableVideo.className())
  117. // Delete OLD avatar image
  118. if var pathUrl = CCUtility.getDirectoryGroup() {
  119. pathUrl.appendPathComponent(NCGlobal.shared.appUserData)
  120. do {
  121. let fileURLs = try FileManager.default.contentsOfDirectory(at: pathUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
  122. for fileURL in fileURLs {
  123. try FileManager.default.removeItem(at: fileURL)
  124. }
  125. } catch { }
  126. }
  127. }
  128. }, shouldCompactOnLaunch: { totalBytes, usedBytes in
  129. // totalBytes refers to the size of the file on disk in bytes (data + free space)
  130. // usedBytes refers to the number of bytes used by data in the file
  131. // Compact if the file is over 100MB in size and less than 50% 'used'
  132. let oneHundredMB = 100 * 1024 * 1024
  133. return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
  134. }
  135. )
  136. do {
  137. _ = try Realm(configuration: configCompact)
  138. } catch {
  139. if let databaseFilePath = databaseFilePath {
  140. do {
  141. #if !EXTENSION
  142. NCContentPresenter.shared.messageNotification("_error_", description: "_database_corrupt_", delay: NCGlobal.shared.dismissAfterSecondLong, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
  143. #endif
  144. try FileManager.default.removeItem(at: databaseFilePath)
  145. } catch {}
  146. }
  147. }
  148. let config = Realm.Configuration(
  149. fileURL: dirGroup?.appendingPathComponent(NCGlobal.shared.appDatabaseNextcloud + "/" + NCGlobal.shared.databaseDefault),
  150. schemaVersion: NCGlobal.shared.databaseSchemaVersion
  151. )
  152. Realm.Configuration.defaultConfiguration = config
  153. }
  154. // Verify Database, if corrupr remove it
  155. do {
  156. _ = try Realm()
  157. } catch {
  158. if let databaseFilePath = databaseFilePath {
  159. do {
  160. #if !EXTENSION
  161. NCContentPresenter.shared.messageNotification("_error_", description: "_database_corrupt_", delay: NCGlobal.shared.dismissAfterSecondLong, type: NCContentPresenter.messageType.info, errorCode: NCGlobal.shared.errorInternalError, priority: .max)
  162. #endif
  163. try FileManager.default.removeItem(at: databaseFilePath)
  164. } catch {}
  165. }
  166. }
  167. // Open Real
  168. _ = try! Realm()
  169. }
  170. // MARK: -
  171. // MARK: Utility Database
  172. @objc func clearTable(_ table: Object.Type, account: String? = nil) {
  173. let realm = try! Realm()
  174. do {
  175. try realm.safeWrite {
  176. var results: Results<Object>
  177. if let account = account {
  178. results = realm.objects(table).filter("account == %@", account)
  179. } else {
  180. results = realm.objects(table)
  181. }
  182. realm.delete(results)
  183. }
  184. } catch let error {
  185. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  186. }
  187. }
  188. @objc func clearDatabase(account: String?, removeAccount: Bool) {
  189. self.clearTable(tableActivity.self, account: account)
  190. self.clearTable(tableActivityLatestId.self, account: account)
  191. self.clearTable(tableActivityPreview.self, account: account)
  192. self.clearTable(tableActivitySubjectRich.self, account: account)
  193. self.clearTable(tableAvatar.self)
  194. self.clearTable(tableCapabilities.self, account: account)
  195. self.clearTable(tableChunk.self, account: account)
  196. self.clearTable(tableComments.self, account: account)
  197. self.clearTable(tableDirectEditingCreators.self, account: account)
  198. self.clearTable(tableDirectEditingEditors.self, account: account)
  199. self.clearTable(tableDirectory.self, account: account)
  200. self.clearTable(tableE2eEncryption.self, account: account)
  201. self.clearTable(tableE2eEncryptionLock.self, account: account)
  202. self.clearTable(tableExternalSites.self, account: account)
  203. self.clearTable(tableGPS.self, account: nil)
  204. self.clearTable(tableLocalFile.self, account: account)
  205. self.clearTable(tableMetadata.self, account: account)
  206. self.clearTable(tablePhotoLibrary.self, account: account)
  207. self.clearTable(tableShare.self, account: account)
  208. self.clearTable(tableTag.self, account: account)
  209. self.clearTable(tableTrash.self, account: account)
  210. self.clearTable(tableUserStatus.self, account: account)
  211. self.clearTable(tableVideo.self, account: account)
  212. if removeAccount {
  213. self.clearTable(tableAccount.self, account: account)
  214. }
  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. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  229. }
  230. }
  231. }
  232. @objc func getThreadConfined(_ object: Object) -> Any {
  233. // id tradeReference = [[NCManageDatabase shared] getThreadConfined:metadata];
  234. return ThreadSafeReference(to: object)
  235. }
  236. @objc func putThreadConfined(_ tableRef: Any) -> Object? {
  237. // tableMetadata *metadataThread = (tableMetadata *)[[NCManageDatabase shared] putThreadConfined:tradeReference];
  238. let realm = try! Realm()
  239. return realm.resolve(tableRef as! ThreadSafeReference<Object>)
  240. }
  241. @objc func isTableInvalidated(_ object: Object) -> Bool {
  242. return object.isInvalidated
  243. }
  244. // MARK: -
  245. // MARK: Table Avatar
  246. @objc func addAvatar(fileName: String, etag: String) {
  247. let realm = try! Realm()
  248. do {
  249. try realm.safeWrite {
  250. // Add new
  251. let addObject = tableAvatar()
  252. addObject.date = NSDate()
  253. addObject.etag = etag
  254. addObject.fileName = fileName
  255. addObject.loaded = true
  256. realm.add(addObject, update: .all)
  257. }
  258. } catch let error {
  259. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  260. }
  261. }
  262. func getTableAvatar(fileName: String) -> tableAvatar? {
  263. let realm = try! Realm()
  264. guard let result = realm.objects(tableAvatar.self).filter("fileName == %@", fileName).first else {
  265. return nil
  266. }
  267. return tableAvatar.init(value: result)
  268. }
  269. func clearAllAvatarLoaded() {
  270. let realm = try! Realm()
  271. do {
  272. try realm.safeWrite {
  273. let results = realm.objects(tableAvatar.self)
  274. for result in results {
  275. result.loaded = false
  276. realm.add(result, update: .all)
  277. }
  278. }
  279. } catch let error {
  280. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  281. }
  282. }
  283. @discardableResult
  284. func setAvatarLoaded(fileName: String) -> UIImage? {
  285. let realm = try! Realm()
  286. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  287. var image: UIImage?
  288. do {
  289. try realm.safeWrite {
  290. if let result = realm.objects(tableAvatar.self).filter("fileName == %@", fileName).first {
  291. if let imageAvatar = UIImage(contentsOfFile: fileNameLocalPath) {
  292. result.loaded = true
  293. image = imageAvatar
  294. } else {
  295. realm.delete(result)
  296. }
  297. }
  298. }
  299. } catch let error {
  300. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  301. }
  302. return image
  303. }
  304. func getImageAvatarLoaded(fileName: String) -> UIImage? {
  305. let realm = try! Realm()
  306. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  307. let result = realm.objects(tableAvatar.self).filter("fileName == %@", fileName).first
  308. if result == nil {
  309. NCUtilityFileSystem.shared.deleteFile(filePath: fileNameLocalPath)
  310. return nil
  311. } else if result?.loaded == false {
  312. return nil
  313. }
  314. return UIImage(contentsOfFile: fileNameLocalPath)
  315. }
  316. // MARK: -
  317. // MARK: Table Capabilities
  318. @objc func addCapabilitiesJSon(_ data: Data, account: String) {
  319. let realm = try! Realm()
  320. do {
  321. try realm.safeWrite {
  322. let addObject = tableCapabilities()
  323. addObject.account = account
  324. addObject.jsondata = data
  325. realm.add(addObject, update: .all)
  326. }
  327. } catch let error {
  328. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  329. }
  330. }
  331. @objc func getCapabilities(account: String) -> String? {
  332. let realm = try! Realm()
  333. guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
  334. return nil
  335. }
  336. guard let jsondata = result.jsondata else {
  337. return nil
  338. }
  339. let json = JSON(jsondata)
  340. return json.rawString()?.replacingOccurrences(of: "\\/", with: "/")
  341. }
  342. @objc func getCapabilitiesServerString(account: String, elements: [String]) -> String? {
  343. let realm = try! Realm()
  344. guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
  345. return nil
  346. }
  347. guard let jsondata = result.jsondata else {
  348. return nil
  349. }
  350. let json = JSON(jsondata)
  351. return json[elements].string
  352. }
  353. @objc func getCapabilitiesServerInt(account: String, elements: [String]) -> Int {
  354. let realm = try! Realm()
  355. guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first,
  356. let jsondata = result.jsondata else {
  357. return 0
  358. }
  359. let json = JSON(jsondata)
  360. return json[elements].intValue
  361. }
  362. @objc func getCapabilitiesServerBool(account: String, elements: [String], exists: Bool) -> Bool {
  363. let realm = try! Realm()
  364. guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
  365. return false
  366. }
  367. guard let jsondata = result.jsondata else {
  368. return false
  369. }
  370. let json = JSON(jsondata)
  371. if exists {
  372. return json[elements].exists()
  373. } else {
  374. return json[elements].boolValue
  375. }
  376. }
  377. @objc func getCapabilitiesServerArray(account: String, elements: [String]) -> [String]? {
  378. let realm = try! Realm()
  379. var resultArray: [String] = []
  380. guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
  381. return nil
  382. }
  383. guard let jsondata = result.jsondata else {
  384. return nil
  385. }
  386. let json = JSON(jsondata)
  387. if let results = json[elements].array {
  388. for result in results {
  389. resultArray.append(result.string ?? "")
  390. }
  391. return resultArray
  392. }
  393. return nil
  394. }
  395. // MARK: -
  396. // MARK: Table Chunk
  397. func getChunkFolder(account: String, ocId: String) -> String {
  398. let realm = try! Realm()
  399. if let result = realm.objects(tableChunk.self).filter("account == %@ AND ocId == %@", account, ocId).first {
  400. return result.chunkFolder
  401. }
  402. return NSUUID().uuidString
  403. }
  404. func getChunks(account: String, ocId: String) -> [String] {
  405. let realm = try! Realm()
  406. var filesNames: [String] = []
  407. let results = realm.objects(tableChunk.self).filter("account == %@ AND ocId == %@", account, ocId).sorted(byKeyPath: "fileName", ascending: true)
  408. for result in results {
  409. filesNames.append(result.fileName)
  410. }
  411. return filesNames
  412. }
  413. func addChunks(account: String, ocId: String, chunkFolder: String, fileNames: [String]) {
  414. let realm = try! Realm()
  415. var size: Int64 = 0
  416. do {
  417. try realm.safeWrite {
  418. for fileName in fileNames {
  419. let object = tableChunk()
  420. size += NCUtilityFileSystem.shared.getFileSize(filePath: CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!)
  421. object.account = account
  422. object.chunkFolder = chunkFolder
  423. object.fileName = fileName
  424. object.index = ocId + fileName
  425. object.ocId = ocId
  426. object.size = size
  427. realm.add(object, update: .all)
  428. }
  429. }
  430. } catch let error {
  431. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  432. }
  433. }
  434. func getChunk(account: String, fileName: String) -> tableChunk? {
  435. let realm = try! Realm()
  436. if let result = realm.objects(tableChunk.self).filter("account == %@ AND fileName == %@", account, fileName).first {
  437. return tableChunk.init(value: result)
  438. } else {
  439. return nil
  440. }
  441. }
  442. func deleteChunk(account: String, ocId: String, fileName: String) {
  443. let realm = try! Realm()
  444. do {
  445. try realm.safeWrite {
  446. let result = realm.objects(tableChunk.self).filter(NSPredicate(format: "account == %@ AND ocId == %@ AND fileName == %@", account, ocId, fileName))
  447. realm.delete(result)
  448. }
  449. } catch let error {
  450. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  451. }
  452. }
  453. func deleteChunks(account: String, ocId: String) {
  454. let realm = try! Realm()
  455. do {
  456. try realm.safeWrite {
  457. let result = realm.objects(tableChunk.self).filter(NSPredicate(format: "account == %@ AND ocId == %@", account, ocId))
  458. realm.delete(result)
  459. }
  460. } catch let error {
  461. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  462. }
  463. }
  464. // MARK: -
  465. // MARK: Table Direct Editing
  466. @objc func addDirectEditing(account: String, editors: [NCCommunicationEditorDetailsEditors], creators: [NCCommunicationEditorDetailsCreators]) {
  467. let realm = try! Realm()
  468. do {
  469. try realm.safeWrite {
  470. let resultsCreators = realm.objects(tableDirectEditingCreators.self).filter("account == %@", account)
  471. realm.delete(resultsCreators)
  472. let resultsEditors = realm.objects(tableDirectEditingEditors.self).filter("account == %@", account)
  473. realm.delete(resultsEditors)
  474. for creator in creators {
  475. let addObject = tableDirectEditingCreators()
  476. addObject.account = account
  477. addObject.editor = creator.editor
  478. addObject.ext = creator.ext
  479. addObject.identifier = creator.identifier
  480. addObject.mimetype = creator.mimetype
  481. addObject.name = creator.name
  482. addObject.templates = creator.templates
  483. realm.add(addObject)
  484. }
  485. for editor in editors {
  486. let addObject = tableDirectEditingEditors()
  487. addObject.account = account
  488. for mimeType in editor.mimetypes {
  489. addObject.mimetypes.append(mimeType)
  490. }
  491. addObject.name = editor.name
  492. if editor.name.lowercased() == NCGlobal.shared.editorOnlyoffice {
  493. addObject.editor = NCGlobal.shared.editorOnlyoffice
  494. } else {
  495. addObject.editor = NCGlobal.shared.editorText
  496. }
  497. for mimeType in editor.optionalMimetypes {
  498. addObject.optionalMimetypes.append(mimeType)
  499. }
  500. addObject.secure = editor.secure
  501. realm.add(addObject)
  502. }
  503. }
  504. } catch let error {
  505. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  506. }
  507. }
  508. @objc func getDirectEditingCreators(account: String) -> [tableDirectEditingCreators]? {
  509. let realm = try! Realm()
  510. let results = realm.objects(tableDirectEditingCreators.self).filter("account == %@", account)
  511. if results.count > 0 {
  512. return Array(results.map { tableDirectEditingCreators.init(value: $0) })
  513. } else {
  514. return nil
  515. }
  516. }
  517. @objc func getDirectEditingCreators(predicate: NSPredicate) -> [tableDirectEditingCreators]? {
  518. let realm = try! Realm()
  519. let results = realm.objects(tableDirectEditingCreators.self).filter(predicate)
  520. if results.count > 0 {
  521. return Array(results.map { tableDirectEditingCreators.init(value: $0) })
  522. } else {
  523. return nil
  524. }
  525. }
  526. @objc func getDirectEditingEditors(account: String) -> [tableDirectEditingEditors]? {
  527. let realm = try! Realm()
  528. let results = realm.objects(tableDirectEditingEditors.self).filter("account == %@", account)
  529. if results.count > 0 {
  530. return Array(results.map { tableDirectEditingEditors.init(value: $0) })
  531. } else {
  532. return nil
  533. }
  534. }
  535. // MARK: -
  536. // MARK: Table Directory
  537. @objc func copyObject(directory: tableDirectory) -> tableDirectory {
  538. return tableDirectory.init(value: directory)
  539. }
  540. /*
  541. @objc func addDirectoryRichWorkspace(ocId: String, richWorkspace: String?) {
  542. let realm = try! Realm()
  543. do {
  544. try realm.safeWrite {
  545. if let result = realm.objects(tableDirectory.self).filter("ocId == %@", ocId).first {
  546. result.richWorkspace = richWorkspace
  547. }
  548. }
  549. } catch let error {
  550. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  551. }
  552. }
  553. */
  554. @objc func addDirectory(encrypted: Bool, favorite: Bool, ocId: String, fileId: String, etag: String? = nil, permissions: String? = nil, serverUrl: String, account: String) {
  555. let realm = try! Realm()
  556. do {
  557. try realm.safeWrite {
  558. var addObject = tableDirectory()
  559. let result = realm.objects(tableDirectory.self).filter("ocId == %@", ocId).first
  560. if result != nil {
  561. addObject = result!
  562. } else {
  563. addObject.ocId = ocId
  564. }
  565. addObject.account = account
  566. addObject.e2eEncrypted = encrypted
  567. addObject.favorite = favorite
  568. addObject.fileId = fileId
  569. if let etag = etag {
  570. addObject.etag = etag
  571. }
  572. if let permissions = permissions {
  573. addObject.permissions = permissions
  574. }
  575. addObject.serverUrl = serverUrl
  576. realm.add(addObject, update: .all)
  577. }
  578. } catch let error {
  579. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  580. }
  581. }
  582. @objc func deleteDirectoryAndSubDirectory(serverUrl: String, account: String) {
  583. let realm = try! Realm()
  584. let results = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl BEGINSWITH %@", account, serverUrl)
  585. // Delete table Metadata & LocalFile
  586. for result in results {
  587. self.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", result.account, result.serverUrl))
  588. self.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", result.ocId))
  589. }
  590. // Delete table Dirrectory
  591. do {
  592. try realm.safeWrite {
  593. realm.delete(results)
  594. }
  595. } catch let error {
  596. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  597. }
  598. }
  599. @objc func setDirectory(serverUrl: String, serverUrlTo: String? = nil, etag: String? = nil, ocId: String? = nil, fileId: String? = nil, encrypted: Bool, richWorkspace: String? = nil, account: String) {
  600. let realm = try! Realm()
  601. do {
  602. try realm.safeWrite {
  603. guard let result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else {
  604. return
  605. }
  606. let directory = tableDirectory.init(value: result)
  607. realm.delete(result)
  608. directory.e2eEncrypted = encrypted
  609. if let etag = etag {
  610. directory.etag = etag
  611. }
  612. if let ocId = ocId {
  613. directory.ocId = ocId
  614. }
  615. if let fileId = fileId {
  616. directory.fileId = fileId
  617. }
  618. if let serverUrlTo = serverUrlTo {
  619. directory.serverUrl = serverUrlTo
  620. }
  621. if let richWorkspace = richWorkspace {
  622. directory.richWorkspace = richWorkspace
  623. }
  624. realm.add(directory, update: .all)
  625. }
  626. } catch let error {
  627. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  628. }
  629. }
  630. @objc func getTableDirectory(predicate: NSPredicate) -> tableDirectory? {
  631. let realm = try! Realm()
  632. guard let result = realm.objects(tableDirectory.self).filter(predicate).first else {
  633. return nil
  634. }
  635. return tableDirectory.init(value: result)
  636. }
  637. @objc func getTablesDirectory(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableDirectory]? {
  638. let realm = try! Realm()
  639. let results = realm.objects(tableDirectory.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  640. if results.count > 0 {
  641. return Array(results.map { tableDirectory.init(value: $0) })
  642. } else {
  643. return nil
  644. }
  645. }
  646. @objc func renameDirectory(ocId: String, serverUrl: String) {
  647. let realm = try! Realm()
  648. do {
  649. try realm.safeWrite {
  650. let result = realm.objects(tableDirectory.self).filter("ocId == %@", ocId).first
  651. result?.serverUrl = serverUrl
  652. }
  653. } catch let error {
  654. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  655. }
  656. }
  657. @objc func setDirectory(serverUrl: String, offline: Bool, account: String) {
  658. let realm = try! Realm()
  659. do {
  660. try realm.safeWrite {
  661. let result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first
  662. result?.offline = offline
  663. }
  664. } catch let error {
  665. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  666. }
  667. }
  668. @discardableResult
  669. @objc func setDirectory(richWorkspace: String?, serverUrl: String, account: String) -> tableDirectory? {
  670. let realm = try! Realm()
  671. var result: tableDirectory?
  672. do {
  673. try realm.safeWrite {
  674. result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first
  675. result?.richWorkspace = richWorkspace
  676. }
  677. } catch let error {
  678. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  679. }
  680. if let result = result {
  681. return tableDirectory.init(value: result)
  682. } else {
  683. return nil
  684. }
  685. }
  686. // MARK: -
  687. // MARK: Table e2e Encryption
  688. @objc func addE2eEncryption(_ e2e: tableE2eEncryption) {
  689. let realm = try! Realm()
  690. do {
  691. try realm.safeWrite {
  692. realm.add(e2e, update: .all)
  693. }
  694. } catch let error {
  695. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  696. }
  697. }
  698. @objc func deleteE2eEncryption(predicate: NSPredicate) {
  699. let realm = try! Realm()
  700. do {
  701. try realm.safeWrite {
  702. let results = realm.objects(tableE2eEncryption.self).filter(predicate)
  703. realm.delete(results)
  704. }
  705. } catch let error {
  706. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  707. }
  708. }
  709. @objc func getE2eEncryption(predicate: NSPredicate) -> tableE2eEncryption? {
  710. let realm = try! Realm()
  711. guard let result = realm.objects(tableE2eEncryption.self).filter(predicate).sorted(byKeyPath: "metadataKeyIndex", ascending: false).first else {
  712. return nil
  713. }
  714. return tableE2eEncryption.init(value: result)
  715. }
  716. @objc func getE2eEncryptions(predicate: NSPredicate) -> [tableE2eEncryption]? {
  717. guard self.getActiveAccount() != nil else {
  718. return nil
  719. }
  720. let realm = try! Realm()
  721. let results: Results<tableE2eEncryption>
  722. results = realm.objects(tableE2eEncryption.self).filter(predicate)
  723. if results.count > 0 {
  724. return Array(results.map { tableE2eEncryption.init(value: $0) })
  725. } else {
  726. return nil
  727. }
  728. }
  729. @objc func renameFileE2eEncryption(serverUrl: String, fileNameIdentifier: String, newFileName: String, newFileNamePath: String) {
  730. guard let activeAccount = self.getActiveAccount() else {
  731. return
  732. }
  733. let realm = try! Realm()
  734. realm.beginWrite()
  735. guard let result = realm.objects(tableE2eEncryption.self).filter("account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", activeAccount.account, serverUrl, fileNameIdentifier).first else {
  736. realm.cancelWrite()
  737. return
  738. }
  739. let object = tableE2eEncryption.init(value: result)
  740. realm.delete(result)
  741. object.fileName = newFileName
  742. object.fileNamePath = newFileNamePath
  743. realm.add(object)
  744. do {
  745. try realm.commitWrite()
  746. } catch let error {
  747. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  748. }
  749. }
  750. // MARK: -
  751. // MARK: Table e2e Encryption Lock
  752. @objc func getE2ETokenLock(account: String, serverUrl: String) -> tableE2eEncryptionLock? {
  753. let realm = try! Realm()
  754. guard let result = realm.objects(tableE2eEncryptionLock.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else {
  755. return nil
  756. }
  757. return tableE2eEncryptionLock.init(value: result)
  758. }
  759. @objc func setE2ETokenLock(account: String, serverUrl: String, fileId: String, e2eToken: String) {
  760. let realm = try! Realm()
  761. do {
  762. try realm.safeWrite {
  763. let addObject = tableE2eEncryptionLock()
  764. addObject.account = account
  765. addObject.fileId = fileId
  766. addObject.serverUrl = serverUrl
  767. addObject.e2eToken = e2eToken
  768. realm.add(addObject, update: .all)
  769. }
  770. } catch let error {
  771. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  772. }
  773. }
  774. @objc func deteleE2ETokenLock(account: String, serverUrl: String) {
  775. let realm = try! Realm()
  776. do {
  777. try realm.safeWrite {
  778. if let result = realm.objects(tableE2eEncryptionLock.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first {
  779. realm.delete(result)
  780. }
  781. }
  782. } catch let error {
  783. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  784. }
  785. }
  786. // MARK: -
  787. // MARK: Table External Sites
  788. @objc func addExternalSites(_ externalSite: NCCommunicationExternalSite, account: String) {
  789. let realm = try! Realm()
  790. do {
  791. try realm.safeWrite {
  792. let addObject = tableExternalSites()
  793. addObject.account = account
  794. addObject.idExternalSite = externalSite.idExternalSite
  795. addObject.icon = externalSite.icon
  796. addObject.lang = externalSite.lang
  797. addObject.name = externalSite.name
  798. addObject.url = externalSite.url
  799. addObject.type = externalSite.type
  800. realm.add(addObject)
  801. }
  802. } catch let error {
  803. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  804. }
  805. }
  806. @objc func deleteExternalSites(account: String) {
  807. let realm = try! Realm()
  808. do {
  809. try realm.safeWrite {
  810. let results = realm.objects(tableExternalSites.self).filter("account == %@", account)
  811. realm.delete(results)
  812. }
  813. } catch let error {
  814. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  815. }
  816. }
  817. @objc func getAllExternalSites(account: String) -> [tableExternalSites]? {
  818. let realm = try! Realm()
  819. let results = realm.objects(tableExternalSites.self).filter("account == %@", account).sorted(byKeyPath: "idExternalSite", ascending: true)
  820. if results.count > 0 {
  821. return Array(results.map { tableExternalSites.init(value: $0) })
  822. } else {
  823. return nil
  824. }
  825. }
  826. // MARK: -
  827. // MARK: Table GPS
  828. @objc func addGeocoderLocation(_ location: String, placemarkAdministrativeArea: String, placemarkCountry: String, placemarkLocality: String, placemarkPostalCode: String, placemarkThoroughfare: String, latitude: String, longitude: String) {
  829. let realm = try! Realm()
  830. realm.beginWrite()
  831. // Verify if exists
  832. guard realm.objects(tableGPS.self).filter("latitude == %@ AND longitude == %@", latitude, longitude).first == nil else {
  833. realm.cancelWrite()
  834. return
  835. }
  836. // Add new GPS
  837. let addObject = tableGPS()
  838. addObject.latitude = latitude
  839. addObject.location = location
  840. addObject.longitude = longitude
  841. addObject.placemarkAdministrativeArea = placemarkAdministrativeArea
  842. addObject.placemarkCountry = placemarkCountry
  843. addObject.placemarkLocality = placemarkLocality
  844. addObject.placemarkPostalCode = placemarkPostalCode
  845. addObject.placemarkThoroughfare = placemarkThoroughfare
  846. realm.add(addObject)
  847. do {
  848. try realm.commitWrite()
  849. } catch let error {
  850. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  851. }
  852. }
  853. @objc func getLocationFromGeoLatitude(_ latitude: String, longitude: String) -> String? {
  854. let realm = try! Realm()
  855. let result = realm.objects(tableGPS.self).filter("latitude == %@ AND longitude == %@", latitude, longitude).first
  856. return result?.location
  857. }
  858. // MARK: -
  859. // MARK: Table LocalFile
  860. @objc func copyObject(localFile: tableLocalFile) -> tableLocalFile {
  861. return tableLocalFile.init(value: localFile)
  862. }
  863. func addLocalFile(metadata: tableMetadata) {
  864. let realm = try! Realm()
  865. do {
  866. try realm.safeWrite {
  867. let addObject = tableLocalFile()
  868. addObject.account = metadata.account
  869. addObject.etag = metadata.etag
  870. addObject.exifDate = NSDate()
  871. addObject.exifLatitude = "-1"
  872. addObject.exifLongitude = "-1"
  873. addObject.ocId = metadata.ocId
  874. addObject.fileName = metadata.fileName
  875. realm.add(addObject, update: .all)
  876. }
  877. } catch let error {
  878. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  879. }
  880. }
  881. func addLocalFile(account: String, etag: String, ocId: String, fileName: String) {
  882. let realm = try! Realm()
  883. do {
  884. try realm.safeWrite {
  885. let addObject = tableLocalFile()
  886. addObject.account = account
  887. addObject.etag = etag
  888. addObject.exifDate = NSDate()
  889. addObject.exifLatitude = "-1"
  890. addObject.exifLongitude = "-1"
  891. addObject.ocId = ocId
  892. addObject.fileName = fileName
  893. realm.add(addObject, update: .all)
  894. }
  895. } catch let error {
  896. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  897. }
  898. }
  899. @objc func deleteLocalFile(predicate: NSPredicate) {
  900. let realm = try! Realm()
  901. do {
  902. try realm.safeWrite {
  903. let results = realm.objects(tableLocalFile.self).filter(predicate)
  904. realm.delete(results)
  905. }
  906. } catch let error {
  907. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  908. }
  909. }
  910. @objc func setLocalFile(ocId: String, fileName: String?, etag: String?) {
  911. let realm = try! Realm()
  912. do {
  913. try realm.safeWrite {
  914. let result = realm.objects(tableLocalFile.self).filter("ocId == %@", ocId).first
  915. if let fileName = fileName {
  916. result?.fileName = fileName
  917. }
  918. if let etag = etag {
  919. result?.etag = etag
  920. }
  921. }
  922. } catch let error {
  923. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  924. }
  925. }
  926. @objc func setLocalFile(ocId: String, exifDate: NSDate?, exifLatitude: String, exifLongitude: String, exifLensModel: String?) {
  927. let realm = try! Realm()
  928. do {
  929. try realm.safeWrite {
  930. if let result = realm.objects(tableLocalFile.self).filter("ocId == %@", ocId).first {
  931. result.exifDate = exifDate
  932. result.exifLatitude = exifLatitude
  933. result.exifLongitude = exifLongitude
  934. if exifLensModel?.count ?? 0 > 0 {
  935. result.exifLensModel = exifLensModel
  936. }
  937. }
  938. }
  939. } catch let error {
  940. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  941. }
  942. }
  943. @objc func getTableLocalFile(predicate: NSPredicate) -> tableLocalFile? {
  944. let realm = try! Realm()
  945. guard let result = realm.objects(tableLocalFile.self).filter(predicate).first else {
  946. return nil
  947. }
  948. return tableLocalFile.init(value: result)
  949. }
  950. @objc func getTableLocalFiles(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableLocalFile] {
  951. let realm = try! Realm()
  952. let results = realm.objects(tableLocalFile.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  953. return Array(results.map { tableLocalFile.init(value: $0) })
  954. }
  955. @objc func setLocalFile(ocId: String, offline: Bool) {
  956. let realm = try! Realm()
  957. do {
  958. try realm.safeWrite {
  959. let result = realm.objects(tableLocalFile.self).filter("ocId == %@", ocId).first
  960. result?.offline = offline
  961. }
  962. } catch let error {
  963. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  964. }
  965. }
  966. // MARK: -
  967. // MARK: Table Photo Library
  968. @discardableResult
  969. @objc func addPhotoLibrary(_ assets: [PHAsset], account: String) -> Bool {
  970. let realm = try! Realm()
  971. do {
  972. try realm.safeWrite {
  973. var creationDateString = ""
  974. for asset in assets {
  975. let addObject = tablePhotoLibrary()
  976. addObject.account = account
  977. addObject.assetLocalIdentifier = asset.localIdentifier
  978. addObject.mediaType = asset.mediaType.rawValue
  979. if let creationDate = asset.creationDate {
  980. addObject.creationDate = creationDate as NSDate
  981. creationDateString = String(describing: creationDate)
  982. } else {
  983. creationDateString = ""
  984. }
  985. if let modificationDate = asset.modificationDate {
  986. addObject.modificationDate = modificationDate as NSDate
  987. }
  988. addObject.idAsset = "\(account)\(asset.localIdentifier)\(creationDateString)"
  989. realm.add(addObject, update: .all)
  990. }
  991. }
  992. } catch let error {
  993. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  994. return false
  995. }
  996. return true
  997. }
  998. @objc func getPhotoLibraryIdAsset(image: Bool, video: Bool, account: String) -> [String]? {
  999. let realm = try! Realm()
  1000. var predicate = NSPredicate()
  1001. if image && video {
  1002. predicate = NSPredicate(format: "account == %@ AND (mediaType == %d OR mediaType == %d)", account, PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
  1003. } else if image {
  1004. predicate = NSPredicate(format: "account == %@ AND mediaType == %d", account, PHAssetMediaType.image.rawValue)
  1005. } else if video {
  1006. predicate = NSPredicate(format: "account == %@ AND mediaType == %d", account, PHAssetMediaType.video.rawValue)
  1007. }
  1008. let results = realm.objects(tablePhotoLibrary.self).filter(predicate)
  1009. let idsAsset = results.map { $0.idAsset }
  1010. return Array(idsAsset)
  1011. }
  1012. // MARK: -
  1013. // MARK: Table Share
  1014. @objc func addShare(urlBase: String, account: String, shares: [NCCommunicationShare]) {
  1015. let realm = try! Realm()
  1016. realm.beginWrite()
  1017. for share in shares {
  1018. let addObject = tableShare()
  1019. let fullPath = NCUtilityFileSystem.shared.getHomeServer(account: account) + share.path
  1020. let serverUrl = NCUtilityFileSystem.shared.deletingLastPathComponent(account: account, serverUrl: fullPath)
  1021. let fileName = NSString(string: fullPath).lastPathComponent
  1022. addObject.account = account
  1023. addObject.fileName = fileName
  1024. addObject.serverUrl = serverUrl
  1025. addObject.canEdit = share.canEdit
  1026. addObject.canDelete = share.canDelete
  1027. addObject.date = share.date
  1028. addObject.displaynameFileOwner = share.displaynameFileOwner
  1029. addObject.displaynameOwner = share.displaynameOwner
  1030. addObject.expirationDate = share.expirationDate
  1031. addObject.fileParent = share.fileParent
  1032. addObject.fileSource = share.fileSource
  1033. addObject.fileTarget = share.fileTarget
  1034. addObject.hideDownload = share.hideDownload
  1035. addObject.idShare = share.idShare
  1036. addObject.itemSource = share.itemSource
  1037. addObject.itemType = share.itemType
  1038. addObject.label = share.label
  1039. addObject.mailSend = share.mailSend
  1040. addObject.mimeType = share.mimeType
  1041. addObject.note = share.note
  1042. addObject.parent = share.parent
  1043. addObject.password = share.password
  1044. addObject.path = share.path
  1045. addObject.permissions = share.permissions
  1046. addObject.sendPasswordByTalk = share.sendPasswordByTalk
  1047. addObject.shareType = share.shareType
  1048. addObject.shareWith = share.shareWith
  1049. addObject.shareWithDisplayname = share.shareWithDisplayname
  1050. addObject.storage = share.storage
  1051. addObject.storageId = share.storageId
  1052. addObject.token = share.token
  1053. addObject.uidOwner = share.uidOwner
  1054. addObject.uidFileOwner = share.uidFileOwner
  1055. addObject.url = share.url
  1056. addObject.userClearAt = share.userClearAt
  1057. addObject.userIcon = share.userIcon
  1058. addObject.userMessage = share.userMessage
  1059. addObject.userStatus = share.userStatus
  1060. realm.add(addObject, update: .all)
  1061. }
  1062. do {
  1063. try realm.commitWrite()
  1064. } catch let error {
  1065. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1066. }
  1067. }
  1068. @objc func getTableShares(account: String) -> [tableShare] {
  1069. let realm = try! Realm()
  1070. let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
  1071. let results = realm.objects(tableShare.self).filter("account == %@", account).sorted(by: sortProperties)
  1072. return Array(results.map { tableShare.init(value: $0) })
  1073. }
  1074. func getTableShares(metadata: tableMetadata) -> (firstShareLink: tableShare?, share: [tableShare]?) {
  1075. let realm = try! Realm()
  1076. let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
  1077. let firstShareLink = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@ AND shareType == 3", metadata.account, metadata.serverUrl, metadata.fileName).first
  1078. if firstShareLink == nil {
  1079. let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName).sorted(by: sortProperties)
  1080. return(firstShareLink: firstShareLink, share: Array(results.map { tableShare.init(value: $0) }))
  1081. } else {
  1082. let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@ AND idShare != %d", metadata.account, metadata.serverUrl, metadata.fileName, firstShareLink!.idShare).sorted(by: sortProperties)
  1083. return(firstShareLink: firstShareLink, share: Array(results.map { tableShare.init(value: $0) }))
  1084. }
  1085. }
  1086. func getTableShare(account: String, idShare: Int) -> tableShare? {
  1087. let realm = try! Realm()
  1088. guard let result = realm.objects(tableShare.self).filter("account = %@ AND idShare = %d", account, idShare).first else {
  1089. return nil
  1090. }
  1091. return tableShare.init(value: result)
  1092. }
  1093. @objc func getTableShares(account: String, serverUrl: String) -> [tableShare] {
  1094. let realm = try! Realm()
  1095. let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
  1096. let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).sorted(by: sortProperties)
  1097. return Array(results.map { tableShare.init(value: $0) })
  1098. }
  1099. @objc func getTableShares(account: String, serverUrl: String, fileName: String) -> [tableShare] {
  1100. let realm = try! Realm()
  1101. let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
  1102. let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).sorted(by: sortProperties)
  1103. return Array(results.map { tableShare.init(value: $0) })
  1104. }
  1105. @objc func deleteTableShare(account: String, idShare: Int) {
  1106. let realm = try! Realm()
  1107. realm.beginWrite()
  1108. let result = realm.objects(tableShare.self).filter("account == %@ AND idShare == %d", account, idShare)
  1109. realm.delete(result)
  1110. do {
  1111. try realm.commitWrite()
  1112. } catch let error {
  1113. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1114. }
  1115. }
  1116. @objc func deleteTableShare(account: String) {
  1117. let realm = try! Realm()
  1118. realm.beginWrite()
  1119. let result = realm.objects(tableShare.self).filter("account == %@", account)
  1120. realm.delete(result)
  1121. do {
  1122. try realm.commitWrite()
  1123. } catch let error {
  1124. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1125. }
  1126. }
  1127. // MARK: -
  1128. // MARK: Table Tag
  1129. @objc func addTag(_ ocId: String, tagIOS: Data?, account: String) {
  1130. let realm = try! Realm()
  1131. do {
  1132. try realm.safeWrite {
  1133. // Add new
  1134. let addObject = tableTag()
  1135. addObject.account = account
  1136. addObject.ocId = ocId
  1137. addObject.tagIOS = tagIOS
  1138. realm.add(addObject, update: .all)
  1139. }
  1140. } catch let error {
  1141. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1142. }
  1143. }
  1144. @objc func deleteTag(_ ocId: String) {
  1145. let realm = try! Realm()
  1146. realm.beginWrite()
  1147. let result = realm.objects(tableTag.self).filter("ocId == %@", ocId)
  1148. realm.delete(result)
  1149. do {
  1150. try realm.commitWrite()
  1151. } catch let error {
  1152. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1153. }
  1154. }
  1155. @objc func getTags(predicate: NSPredicate) -> [tableTag] {
  1156. let realm = try! Realm()
  1157. let results = realm.objects(tableTag.self).filter(predicate)
  1158. return Array(results.map { tableTag.init(value: $0) })
  1159. }
  1160. @objc func getTag(predicate: NSPredicate) -> tableTag? {
  1161. let realm = try! Realm()
  1162. guard let result = realm.objects(tableTag.self).filter(predicate).first else {
  1163. return nil
  1164. }
  1165. return tableTag.init(value: result)
  1166. }
  1167. // MARK: -
  1168. // MARK: Table Trash
  1169. @objc func addTrash(account: String, items: [NCCommunicationTrash]) {
  1170. let realm = try! Realm()
  1171. do {
  1172. try realm.safeWrite {
  1173. for trash in items {
  1174. let object = tableTrash()
  1175. object.account = account
  1176. object.contentType = trash.contentType
  1177. object.date = trash.date
  1178. object.directory = trash.directory
  1179. object.fileId = trash.fileId
  1180. object.fileName = trash.fileName
  1181. object.filePath = trash.filePath
  1182. object.hasPreview = trash.hasPreview
  1183. object.iconName = trash.iconName
  1184. object.size = trash.size
  1185. object.trashbinDeletionTime = trash.trashbinDeletionTime
  1186. object.trashbinFileName = trash.trashbinFileName
  1187. object.trashbinOriginalLocation = trash.trashbinOriginalLocation
  1188. object.classFile = trash.classFile
  1189. realm.add(object, update: .all)
  1190. }
  1191. }
  1192. } catch let error {
  1193. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1194. }
  1195. }
  1196. @objc func deleteTrash(filePath: String?, account: String) {
  1197. let realm = try! Realm()
  1198. var predicate = NSPredicate()
  1199. do {
  1200. try realm.safeWrite {
  1201. if filePath == nil {
  1202. predicate = NSPredicate(format: "account == %@", account)
  1203. } else {
  1204. predicate = NSPredicate(format: "account == %@ AND filePath == %@", account, filePath!)
  1205. }
  1206. let result = realm.objects(tableTrash.self).filter(predicate)
  1207. realm.delete(result)
  1208. }
  1209. } catch let error {
  1210. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1211. }
  1212. }
  1213. @objc func deleteTrash(fileId: String?, account: String) {
  1214. let realm = try! Realm()
  1215. var predicate = NSPredicate()
  1216. do {
  1217. try realm.safeWrite {
  1218. if fileId == nil {
  1219. predicate = NSPredicate(format: "account == %@", account)
  1220. } else {
  1221. predicate = NSPredicate(format: "account == %@ AND fileId == %@", account, fileId!)
  1222. }
  1223. let result = realm.objects(tableTrash.self).filter(predicate)
  1224. realm.delete(result)
  1225. }
  1226. } catch let error {
  1227. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1228. }
  1229. }
  1230. func getTrash(filePath: String, sort: String?, ascending: Bool?, account: String) -> [tableTrash]? {
  1231. let realm = try! Realm()
  1232. let sort = sort ?? "date"
  1233. let ascending = ascending ?? false
  1234. let results = realm.objects(tableTrash.self).filter("account == %@ AND filePath == %@", account, filePath).sorted(byKeyPath: sort, ascending: ascending)
  1235. return Array(results.map { tableTrash.init(value: $0) })
  1236. }
  1237. @objc func getTrashItem(fileId: String, account: String) -> tableTrash? {
  1238. let realm = try! Realm()
  1239. guard let result = realm.objects(tableTrash.self).filter("account == %@ AND fileId == %@", account, fileId).first else {
  1240. return nil
  1241. }
  1242. return tableTrash.init(value: result)
  1243. }
  1244. // MARK: -
  1245. // MARK: Table UserStatus
  1246. @objc func addUserStatus(_ userStatuses: [NCCommunicationUserStatus], account: String, predefined: Bool) {
  1247. let realm = try! Realm()
  1248. do {
  1249. try realm.safeWrite {
  1250. let results = realm.objects(tableUserStatus.self).filter("account == %@ AND predefined == %@", account, predefined)
  1251. realm.delete(results)
  1252. for userStatus in userStatuses {
  1253. let object = tableUserStatus()
  1254. object.account = account
  1255. object.clearAt = userStatus.clearAt
  1256. object.clearAtTime = userStatus.clearAtTime
  1257. object.clearAtType = userStatus.clearAtType
  1258. object.icon = userStatus.icon
  1259. object.id = userStatus.id
  1260. object.message = userStatus.message
  1261. object.predefined = userStatus.predefined
  1262. object.status = userStatus.status
  1263. object.userId = userStatus.userId
  1264. realm.add(object)
  1265. }
  1266. }
  1267. } catch let error {
  1268. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1269. }
  1270. }
  1271. // MARK: -
  1272. // MARK: Table Video
  1273. func addVideoTime(metadata: tableMetadata, time: CMTime?, durationTime: CMTime?) {
  1274. if metadata.livePhoto { return }
  1275. let realm = try! Realm()
  1276. do {
  1277. try realm.safeWrite {
  1278. if let result = realm.objects(tableVideo.self).filter("account == %@ AND ocId == %@", metadata.account, metadata.ocId).first {
  1279. if let durationTime = durationTime {
  1280. result.duration = durationTime.convertScale(1000, method: .default).value
  1281. }
  1282. if let time = time {
  1283. result.time = time.convertScale(1000, method: .default).value
  1284. }
  1285. realm.add(result, update: .all)
  1286. } else {
  1287. let addObject = tableVideo()
  1288. addObject.account = metadata.account
  1289. if let durationTime = durationTime {
  1290. addObject.duration = durationTime.convertScale(1000, method: .default).value
  1291. }
  1292. addObject.ocId = metadata.ocId
  1293. if let time = time {
  1294. addObject.time = time.convertScale(1000, method: .default).value
  1295. }
  1296. realm.add(addObject, update: .all)
  1297. }
  1298. }
  1299. } catch let error {
  1300. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1301. }
  1302. }
  1303. func addVideoCodec(metadata: tableMetadata, codecNameVideo: String?, codecNameAudio: String?, codecAudioChannelLayout: String?, codecAudioLanguage: String?, codecSubtitleLanguage: String?, codecMaxCompatibility: Bool, codecQuality: String?) {
  1304. let realm = try! Realm()
  1305. do {
  1306. try realm.safeWrite {
  1307. if let result = realm.objects(tableVideo.self).filter("account == %@ AND ocId == %@", metadata.account, metadata.ocId).first {
  1308. if let codecNameVideo = codecNameVideo { result.codecNameVideo = codecNameVideo }
  1309. if let codecNameAudio = codecNameAudio { result.codecNameAudio = codecNameAudio }
  1310. if let codecAudioChannelLayout = codecAudioChannelLayout { result.codecAudioChannelLayout = codecAudioChannelLayout }
  1311. if let codecAudioLanguage = codecAudioLanguage { result.codecAudioLanguage = codecAudioLanguage }
  1312. if let codecSubtitleLanguage = codecSubtitleLanguage { result.codecSubtitleLanguage = codecSubtitleLanguage }
  1313. result.codecMaxCompatibility = codecMaxCompatibility
  1314. if let codecQuality = codecQuality { result.codecQuality = codecQuality }
  1315. realm.add(result, update: .all)
  1316. } else {
  1317. let addObject = tableVideo()
  1318. addObject.account = metadata.account
  1319. addObject.ocId = metadata.ocId
  1320. addObject.codecNameVideo = codecNameVideo
  1321. addObject.codecNameAudio = codecNameAudio
  1322. addObject.codecAudioChannelLayout = codecAudioChannelLayout
  1323. addObject.codecAudioLanguage = codecAudioLanguage
  1324. addObject.codecSubtitleLanguage = codecSubtitleLanguage
  1325. addObject.codecMaxCompatibility = codecMaxCompatibility
  1326. addObject.codecQuality = codecQuality
  1327. realm.add(addObject, update: .all)
  1328. }
  1329. }
  1330. } catch let error {
  1331. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1332. }
  1333. }
  1334. func getVideo(metadata: tableMetadata?) -> tableVideo? {
  1335. guard let metadata = metadata else { return nil }
  1336. let realm = try! Realm()
  1337. guard let result = realm.objects(tableVideo.self).filter("account == %@ AND ocId == %@", metadata.account, metadata.ocId).first else {
  1338. return nil
  1339. }
  1340. return tableVideo.init(value: result)
  1341. }
  1342. func getVideoDurationTime(metadata: tableMetadata?) -> CMTime? {
  1343. guard let metadata = metadata else { return nil }
  1344. if metadata.livePhoto { return nil }
  1345. let realm = try! Realm()
  1346. guard let result = realm.objects(tableVideo.self).filter("account == %@ AND ocId == %@", metadata.account, metadata.ocId).first else {
  1347. return nil
  1348. }
  1349. if result.duration == 0 { return nil }
  1350. let duration = CMTimeMake(value: result.duration, timescale: 1000)
  1351. return duration
  1352. }
  1353. func getVideoTime(metadata: tableMetadata) -> CMTime? {
  1354. if metadata.livePhoto { return nil }
  1355. let realm = try! Realm()
  1356. guard let result = realm.objects(tableVideo.self).filter("account == %@ AND ocId == %@", metadata.account, metadata.ocId).first else {
  1357. return nil
  1358. }
  1359. if result.time == 0 { return nil }
  1360. let time = CMTimeMake(value: result.time, timescale: 1000)
  1361. return time
  1362. }
  1363. func deleteVideo(metadata: tableMetadata) {
  1364. let realm = try! Realm()
  1365. do {
  1366. try realm.safeWrite {
  1367. let result = realm.objects(tableVideo.self).filter("account == %@ AND ocId == %@", metadata.account, metadata.ocId)
  1368. realm.delete(result)
  1369. }
  1370. } catch let error {
  1371. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1372. }
  1373. }
  1374. }
  1375. // MARK: -
  1376. extension Realm {
  1377. public func safeWrite(_ block: (() throws -> Void)) throws {
  1378. if isInWriteTransaction {
  1379. try block()
  1380. } else {
  1381. try write(block)
  1382. }
  1383. }
  1384. }