NCManageDatabase+Metadata.swift 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. //
  2. // NCManageDatabase+Metadata.swift
  3. // Nextcloud
  4. //
  5. // Created by Henrik Storch on 30.11.21.
  6. // Copyright © 2021 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. import RealmSwift
  25. import NextcloudKit
  26. class tableMetadata: Object, NCUserBaseUrl {
  27. override func isEqual(_ object: Any?) -> Bool {
  28. if let object = object as? tableMetadata,
  29. self.account == object.account,
  30. self.etag == object.etag,
  31. self.fileId == object.fileId,
  32. self.path == object.path,
  33. self.fileName == object.fileName,
  34. self.fileNameView == object.fileNameView,
  35. self.date == object.date,
  36. self.permissions == object.permissions,
  37. self.hasPreview == object.hasPreview,
  38. self.note == object.note,
  39. self.lock == object.lock,
  40. self.favorite == object.favorite,
  41. self.livePhotoFile == object.livePhotoFile,
  42. self.sharePermissionsCollaborationServices == object.sharePermissionsCollaborationServices,
  43. Array(self.tags).elementsEqual(Array(object.tags)),
  44. Array(self.shareType).elementsEqual(Array(object.shareType)),
  45. Array(self.sharePermissionsCloudMesh).elementsEqual(Array(object.sharePermissionsCloudMesh)) {
  46. return true
  47. } else {
  48. return false
  49. }
  50. }
  51. @objc dynamic var account = ""
  52. @objc dynamic var assetLocalIdentifier = ""
  53. @objc dynamic var checksums = ""
  54. @objc dynamic var chunk: Int = 0
  55. @objc dynamic var classFile = ""
  56. @objc dynamic var commentsUnread: Bool = false
  57. @objc dynamic var contentType = ""
  58. @objc dynamic var creationDate = NSDate()
  59. @objc dynamic var dataFingerprint = ""
  60. @objc dynamic var date = NSDate()
  61. @objc dynamic var directory: Bool = false
  62. @objc dynamic var deleteAssetLocalIdentifier: Bool = false
  63. @objc dynamic var downloadURL = ""
  64. @objc dynamic var e2eEncrypted: Bool = false
  65. @objc dynamic var edited: Bool = false
  66. @objc dynamic var etag = ""
  67. @objc dynamic var etagResource = ""
  68. @objc dynamic var favorite: Bool = false
  69. @objc dynamic var fileId = ""
  70. @objc dynamic var fileName = ""
  71. @objc dynamic var fileNameView = ""
  72. @objc dynamic var hasPreview: Bool = false
  73. @objc dynamic var hidden: Bool = false
  74. @objc dynamic var iconName = ""
  75. @objc dynamic var iconUrl = ""
  76. @objc dynamic var isFlaggedAsLivePhotoByServer: Bool = false // Indicating if the file is sent as a live photo from the server, or if we should detect it as such and convert it client-side
  77. @objc dynamic var isExtractFile: Bool = false
  78. @objc dynamic var livePhotoFile = "" // If this is not empty, the media is a live photo. New media gets this straight from server, but old media needs to be detected as live photo (look isFlaggedAsLivePhotoByServer)
  79. @objc dynamic var mountType = ""
  80. @objc dynamic var name = "" // for unifiedSearch is the provider.id
  81. @objc dynamic var note = ""
  82. @objc dynamic var ocId = ""
  83. @objc dynamic var ownerId = ""
  84. @objc dynamic var ownerDisplayName = ""
  85. @objc public var lock = false
  86. @objc public var lockOwner = ""
  87. @objc public var lockOwnerEditor = ""
  88. @objc public var lockOwnerType = 0
  89. @objc public var lockOwnerDisplayName = ""
  90. @objc public var lockTime: Date?
  91. @objc public var lockTimeOut: Date?
  92. @objc dynamic var path = ""
  93. @objc dynamic var permissions = ""
  94. @objc dynamic var quotaUsedBytes: Int64 = 0
  95. @objc dynamic var quotaAvailableBytes: Int64 = 0
  96. @objc dynamic var resourceType = ""
  97. @objc dynamic var richWorkspace: String?
  98. @objc dynamic var serverUrl = ""
  99. @objc dynamic var session = ""
  100. @objc dynamic var sessionError = ""
  101. @objc dynamic var sessionSelector = ""
  102. @objc dynamic var sessionTaskIdentifier: Int = 0
  103. @objc dynamic var sharePermissionsCollaborationServices: Int = 0
  104. let sharePermissionsCloudMesh = List<String>()
  105. let shareType = List<Int>()
  106. @objc dynamic var size: Int64 = 0
  107. @objc dynamic var status: Int = 0
  108. @objc dynamic var subline: String?
  109. let tags = List<String>()
  110. @objc dynamic var trashbinFileName = ""
  111. @objc dynamic var trashbinOriginalLocation = ""
  112. @objc dynamic var trashbinDeletionTime = NSDate()
  113. @objc dynamic var uploadDate = NSDate()
  114. @objc dynamic var url = ""
  115. @objc dynamic var urlBase = ""
  116. @objc dynamic var user = ""
  117. @objc dynamic var userId = ""
  118. @objc dynamic var latitude: Double = 0
  119. @objc dynamic var longitude: Double = 0
  120. @objc dynamic var height: Int = 0
  121. @objc dynamic var width: Int = 0
  122. @objc dynamic var errorCode: Int = 0
  123. override static func primaryKey() -> String {
  124. return "ocId"
  125. }
  126. }
  127. extension tableMetadata {
  128. var fileExtension: String {
  129. (fileNameView as NSString).pathExtension
  130. }
  131. var fileNoExtension: String {
  132. (fileNameView as NSString).deletingPathExtension
  133. }
  134. var isRenameable: Bool {
  135. if lock {
  136. return false
  137. }
  138. if !isDirectoryE2EE && e2eEncrypted {
  139. return false
  140. }
  141. return true
  142. }
  143. var isPrintable: Bool {
  144. if isDocumentViewableOnly {
  145. return false
  146. }
  147. if ["application/pdf", "com.adobe.pdf"].contains(contentType) || contentType.hasPrefix("text/") || classFile == NKCommon.TypeClassFile.image.rawValue {
  148. return true
  149. }
  150. return false
  151. }
  152. var isSavebleInCameraRoll: Bool {
  153. return (classFile == NKCommon.TypeClassFile.image.rawValue && contentType != "image/svg+xml") || classFile == NKCommon.TypeClassFile.video.rawValue
  154. }
  155. var isDocumentViewableOnly: Bool {
  156. sharePermissionsCollaborationServices == NCGlobal.shared.permissionReadShare && classFile == NKCommon.TypeClassFile.document.rawValue
  157. }
  158. var isAudioOrVideo: Bool {
  159. return classFile == NKCommon.TypeClassFile.audio.rawValue || classFile == NKCommon.TypeClassFile.video.rawValue
  160. }
  161. var isVideo: Bool {
  162. return classFile == NKCommon.TypeClassFile.video.rawValue
  163. }
  164. var isAudio: Bool {
  165. return classFile == NKCommon.TypeClassFile.audio.rawValue
  166. }
  167. var isImage: Bool {
  168. return classFile == NKCommon.TypeClassFile.image.rawValue
  169. }
  170. var isSavebleAsImage: Bool {
  171. classFile == NKCommon.TypeClassFile.image.rawValue && contentType != "image/svg+xml"
  172. }
  173. var isCopyableInPasteboard: Bool {
  174. !isDocumentViewableOnly && !directory
  175. }
  176. var isCopyableMovable: Bool {
  177. !isDocumentViewableOnly && !isDirectoryE2EE && !e2eEncrypted
  178. }
  179. var isModifiableWithQuickLook: Bool {
  180. if directory || isDocumentViewableOnly || isDirectoryE2EE {
  181. return false
  182. }
  183. return contentType == "com.adobe.pdf" || contentType == "application/pdf" || classFile == NKCommon.TypeClassFile.image.rawValue
  184. }
  185. var isDeletable: Bool {
  186. if !isDirectoryE2EE && e2eEncrypted {
  187. return false
  188. }
  189. return true
  190. }
  191. var isSettableOnOffline: Bool {
  192. return session.isEmpty && !isDocumentViewableOnly
  193. }
  194. var canOpenIn: Bool {
  195. return session.isEmpty && !isDocumentViewableOnly && !directory && !NCBrandOptions.shared.disable_openin_file
  196. }
  197. var isDirectoySettableE2EE: Bool {
  198. return directory && size == 0 && !e2eEncrypted && NCKeychain().isEndToEndEnabled(account: account)
  199. }
  200. var isDirectoryUnsettableE2EE: Bool {
  201. return !isDirectoryE2EE && directory && size == 0 && e2eEncrypted && NCKeychain().isEndToEndEnabled(account: account)
  202. }
  203. var canOpenExternalEditor: Bool {
  204. if isDocumentViewableOnly {
  205. return false
  206. }
  207. let utility = NCUtility()
  208. let editors = utility.isDirectEditing(account: account, contentType: contentType)
  209. let isRichDocument = utility.isRichDocument(self)
  210. return classFile == NKCommon.TypeClassFile.document.rawValue && editors.contains(NCGlobal.shared.editorText) && ((editors.contains(NCGlobal.shared.editorOnlyoffice) || isRichDocument))
  211. }
  212. var isWaitingTransfer: Bool {
  213. status == NCGlobal.shared.metadataStatusWaitDownload || status == NCGlobal.shared.metadataStatusWaitUpload || status == NCGlobal.shared.metadataStatusUploadError
  214. }
  215. var isInTransfer: Bool {
  216. status == NCGlobal.shared.metadataStatusDownloading || status == NCGlobal.shared.metadataStatusUploading
  217. }
  218. var isTransferInForeground: Bool {
  219. (status > 0 && (chunk > 0 || e2eEncrypted))
  220. }
  221. var isDownload: Bool {
  222. status == NCGlobal.shared.metadataStatusDownloading
  223. }
  224. var isUpload: Bool {
  225. status == NCGlobal.shared.metadataStatusUploading
  226. }
  227. @objc var isDirectoryE2EE: Bool {
  228. NCUtilityFileSystem().isDirectoryE2EE(account: account, urlBase: urlBase, userId: userId, serverUrl: serverUrl)
  229. }
  230. var isDirectoryE2EETop: Bool {
  231. NCUtilityFileSystem().isDirectoryE2EETop(account: account, serverUrl: serverUrl)
  232. }
  233. var isLivePhoto: Bool {
  234. !livePhotoFile.isEmpty
  235. }
  236. var isNotFlaggedAsLivePhotoByServer: Bool {
  237. !isFlaggedAsLivePhotoByServer
  238. }
  239. var isSynchronizable: Bool {
  240. let localFile = NCManageDatabase.shared.getResultsTableLocalFile(predicate: NSPredicate(format: "ocId == %@", ocId))?.first
  241. if localFile?.etag != etag || NCUtilityFileSystem().fileProviderStorageSize(ocId, fileNameView: fileNameView) == 0 {
  242. return true
  243. }
  244. return false
  245. }
  246. /// Returns false if the user is lokced out of the file. I.e. The file is locked but by somone else
  247. func canUnlock(as user: String) -> Bool {
  248. return !lock || (lockOwner == user && lockOwnerType == 0)
  249. }
  250. // Return if is sharable
  251. func isSharable() -> Bool {
  252. if !NCGlobal.shared.capabilityFileSharingApiEnabled || (NCGlobal.shared.capabilityE2EEEnabled && isDirectoryE2EE) {
  253. return false
  254. }
  255. return true
  256. }
  257. }
  258. extension NCManageDatabase {
  259. func convertFileToMetadata(_ file: NKFile, isDirectoryE2EE: Bool) -> tableMetadata {
  260. let metadata = tableMetadata()
  261. metadata.account = file.account
  262. metadata.checksums = file.checksums
  263. metadata.commentsUnread = file.commentsUnread
  264. metadata.contentType = file.contentType
  265. if let date = file.creationDate {
  266. metadata.creationDate = date
  267. } else {
  268. metadata.creationDate = file.date
  269. }
  270. metadata.dataFingerprint = file.dataFingerprint
  271. metadata.date = file.date
  272. metadata.directory = file.directory
  273. metadata.downloadURL = file.downloadURL
  274. metadata.e2eEncrypted = file.e2eEncrypted
  275. metadata.etag = file.etag
  276. metadata.favorite = file.favorite
  277. metadata.fileId = file.fileId
  278. metadata.fileName = file.fileName
  279. metadata.fileNameView = file.fileName
  280. metadata.hasPreview = file.hasPreview
  281. metadata.hidden = file.hidden
  282. metadata.iconName = file.iconName
  283. metadata.mountType = file.mountType
  284. metadata.name = file.name
  285. metadata.note = file.note
  286. metadata.ocId = file.ocId
  287. metadata.ownerId = file.ownerId
  288. metadata.ownerDisplayName = file.ownerDisplayName
  289. metadata.lock = file.lock
  290. metadata.lockOwner = file.lockOwner
  291. metadata.lockOwnerEditor = file.lockOwnerEditor
  292. metadata.lockOwnerType = file.lockOwnerType
  293. metadata.lockOwnerDisplayName = file.lockOwnerDisplayName
  294. metadata.lockTime = file.lockTime
  295. metadata.lockTimeOut = file.lockTimeOut
  296. metadata.path = file.path
  297. metadata.permissions = file.permissions
  298. metadata.quotaUsedBytes = file.quotaUsedBytes
  299. metadata.quotaAvailableBytes = file.quotaAvailableBytes
  300. metadata.richWorkspace = file.richWorkspace
  301. metadata.resourceType = file.resourceType
  302. metadata.serverUrl = file.serverUrl
  303. metadata.sharePermissionsCollaborationServices = file.sharePermissionsCollaborationServices
  304. for element in file.sharePermissionsCloudMesh {
  305. metadata.sharePermissionsCloudMesh.append(element)
  306. }
  307. for element in file.shareType {
  308. metadata.shareType.append(element)
  309. }
  310. for element in file.tags {
  311. metadata.tags.append(element)
  312. }
  313. metadata.size = file.size
  314. metadata.classFile = file.classFile
  315. // iOS 12.0,* don't detect UTI text/markdown, text/x-markdown
  316. if (metadata.contentType == "text/markdown" || metadata.contentType == "text/x-markdown") && metadata.classFile == NKCommon.TypeClassFile.unknow.rawValue {
  317. metadata.classFile = NKCommon.TypeClassFile.document.rawValue
  318. }
  319. if let date = file.uploadDate {
  320. metadata.uploadDate = date
  321. } else {
  322. metadata.uploadDate = file.date
  323. }
  324. metadata.urlBase = file.urlBase
  325. metadata.user = file.user
  326. metadata.userId = file.userId
  327. metadata.latitude = file.latitude
  328. metadata.longitude = file.longitude
  329. metadata.height = file.height
  330. metadata.width = file.width
  331. metadata.livePhotoFile = file.livePhotoFile
  332. metadata.isFlaggedAsLivePhotoByServer = file.isFlaggedAsLivePhotoByServer
  333. // E2EE find the fileName for fileNameView
  334. if isDirectoryE2EE || file.e2eEncrypted {
  335. if let tableE2eEncryption = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", file.account, file.serverUrl, file.fileName)) {
  336. metadata.fileNameView = tableE2eEncryption.fileName
  337. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: metadata.fileNameView, mimeType: file.contentType, directory: file.directory)
  338. metadata.contentType = results.mimeType
  339. metadata.iconName = results.iconName
  340. metadata.classFile = results.classFile
  341. }
  342. }
  343. return metadata
  344. }
  345. func convertFilesToMetadatas(_ files: [NKFile], useMetadataFolder: Bool, completion: @escaping (_ metadataFolder: tableMetadata, _ metadatasFolder: [tableMetadata], _ metadatas: [tableMetadata]) -> Void) {
  346. var counter: Int = 0
  347. var isDirectoryE2EE: Bool = false
  348. let listServerUrl = ThreadSafeDictionary<String, Bool>()
  349. var metadataFolder = tableMetadata()
  350. var metadataFolders: [tableMetadata] = []
  351. var metadatas: [tableMetadata] = []
  352. for file in files {
  353. if let key = listServerUrl[file.serverUrl] {
  354. isDirectoryE2EE = key
  355. } else {
  356. isDirectoryE2EE = NCUtilityFileSystem().isDirectoryE2EE(file: file)
  357. listServerUrl[file.serverUrl] = isDirectoryE2EE
  358. }
  359. let metadata = convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE)
  360. if counter == 0 && useMetadataFolder {
  361. metadataFolder = tableMetadata.init(value: metadata)
  362. } else {
  363. metadatas.append(metadata)
  364. if metadata.directory {
  365. metadataFolders.append(metadata)
  366. }
  367. }
  368. counter += 1
  369. }
  370. completion(metadataFolder, metadataFolders, metadatas)
  371. }
  372. func convertFilesToMetadatas(_ files: [NKFile], useMetadataFolder: Bool) async -> (metadataFolder: tableMetadata, metadatasFolder: [tableMetadata], metadatas: [tableMetadata]) {
  373. await withUnsafeContinuation({ continuation in
  374. convertFilesToMetadatas(files, useMetadataFolder: useMetadataFolder) { metadataFolder, metadatasFolder, metadatas in
  375. continuation.resume(returning: (metadataFolder, metadatasFolder, metadatas))
  376. }
  377. })
  378. }
  379. func createMetadata(account: String, user: String, userId: String, fileName: String, fileNameView: String, ocId: String, serverUrl: String, urlBase: String, url: String, contentType: String, isUrl: Bool = false, name: String = NCGlobal.shared.appName, subline: String? = nil, iconName: String? = nil, iconUrl: String? = nil) -> tableMetadata {
  380. let metadata = tableMetadata()
  381. if isUrl {
  382. metadata.contentType = "text/uri-list"
  383. if let iconName = iconName {
  384. metadata.iconName = iconName
  385. } else {
  386. metadata.iconName = NKCommon.TypeClassFile.url.rawValue
  387. }
  388. metadata.classFile = NKCommon.TypeClassFile.url.rawValue
  389. } else {
  390. let (mimeType, classFile, iconName, _, _, _) = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: fileName, mimeType: contentType, directory: false)
  391. metadata.contentType = mimeType
  392. metadata.iconName = iconName
  393. metadata.classFile = classFile
  394. // iOS 12.0,* don't detect UTI text/markdown, text/x-markdown
  395. if classFile == NKCommon.TypeClassFile.unknow.rawValue && (mimeType == "text/x-markdown" || mimeType == "text/markdown") {
  396. metadata.iconName = NKCommon.TypeIconFile.txt.rawValue
  397. metadata.classFile = NKCommon.TypeClassFile.document.rawValue
  398. }
  399. }
  400. if let iconUrl = iconUrl {
  401. metadata.iconUrl = iconUrl
  402. }
  403. let fileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
  404. metadata.account = account
  405. metadata.creationDate = Date() as NSDate
  406. metadata.date = Date() as NSDate
  407. metadata.hasPreview = true
  408. metadata.etag = ocId
  409. metadata.fileName = fileName
  410. metadata.fileNameView = fileName
  411. metadata.name = name
  412. metadata.ocId = ocId
  413. metadata.permissions = "RGDNVW"
  414. metadata.serverUrl = serverUrl
  415. metadata.subline = subline
  416. metadata.uploadDate = Date() as NSDate
  417. metadata.url = url
  418. metadata.urlBase = urlBase
  419. metadata.user = user
  420. metadata.userId = userId
  421. if !metadata.urlBase.isEmpty, metadata.serverUrl.hasPrefix(metadata.urlBase) {
  422. metadata.path = String(metadata.serverUrl.dropFirst(metadata.urlBase.count)) + "/"
  423. }
  424. return metadata
  425. }
  426. @discardableResult
  427. func addMetadata(_ metadata: tableMetadata) -> tableMetadata? {
  428. let result = tableMetadata.init(value: metadata)
  429. do {
  430. let realm = try Realm()
  431. try realm.write {
  432. realm.add(result, update: .all)
  433. }
  434. } catch let error {
  435. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  436. return nil
  437. }
  438. return tableMetadata.init(value: result)
  439. }
  440. func addMetadatas(_ metadatas: [tableMetadata]) {
  441. do {
  442. let realm = try Realm()
  443. try realm.write {
  444. realm.add(metadatas, update: .all)
  445. }
  446. } catch let error {
  447. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  448. }
  449. }
  450. func deleteMetadata(predicate: NSPredicate) {
  451. do {
  452. let realm = try Realm()
  453. try realm.write {
  454. let results = realm.objects(tableMetadata.self).filter(predicate)
  455. realm.delete(results)
  456. }
  457. } catch let error {
  458. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  459. }
  460. }
  461. func deleteMetadata(results: Results<tableMetadata>) {
  462. do {
  463. let realm = try Realm()
  464. try realm.write {
  465. realm.delete(results)
  466. }
  467. } catch let error {
  468. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  469. }
  470. }
  471. func moveMetadata(ocId: String, serverUrlTo: String) {
  472. do {
  473. let realm = try Realm()
  474. try realm.write {
  475. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  476. result.serverUrl = serverUrlTo
  477. }
  478. }
  479. } catch let error {
  480. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  481. }
  482. }
  483. func renameMetadata(fileNameTo: String, ocId: String) {
  484. do {
  485. let realm = try Realm()
  486. try realm.write {
  487. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  488. let resultsType = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: fileNameTo, mimeType: "", directory: result.directory)
  489. result.fileName = fileNameTo
  490. result.fileNameView = fileNameTo
  491. result.iconName = resultsType.iconName
  492. result.contentType = resultsType.mimeType
  493. result.classFile = resultsType.classFile
  494. }
  495. }
  496. } catch let error {
  497. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  498. }
  499. }
  500. func setMetadataSession(ocId: String,
  501. newFileName: String? = nil,
  502. session: String? = nil,
  503. sessionError: String? = nil,
  504. selector: String? = nil,
  505. status: Int? = nil,
  506. etag: String? = nil,
  507. errorCode: Int? = nil) {
  508. do {
  509. let realm = try Realm()
  510. try realm.write {
  511. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  512. if let newFileName = newFileName {
  513. result.fileName = newFileName
  514. result.fileNameView = newFileName
  515. }
  516. if let session {
  517. result.session = session
  518. }
  519. if let sessionError {
  520. result.sessionError = sessionError
  521. }
  522. if let selector {
  523. result.sessionSelector = selector
  524. }
  525. if let status {
  526. result.status = status
  527. }
  528. if let etag {
  529. result.etag = etag
  530. }
  531. if let errorCode {
  532. result.errorCode = errorCode
  533. }
  534. }
  535. }
  536. } catch let error {
  537. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  538. }
  539. }
  540. func setMetadataSession(ocId: String,
  541. status: Int? = nil,
  542. taskIdentifier: Int? = nil) {
  543. do {
  544. let realm = try Realm()
  545. try realm.write {
  546. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  547. if let status {
  548. result.status = status
  549. }
  550. if let taskIdentifier {
  551. result.sessionTaskIdentifier = taskIdentifier
  552. }
  553. }
  554. }
  555. } catch let error {
  556. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  557. }
  558. }
  559. func setMetadataSessionInWaitDownload(ocId: String, selector: String) -> tableMetadata? {
  560. var metadata: tableMetadata?
  561. do {
  562. let realm = try Realm()
  563. try realm.write {
  564. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  565. result.session = NextcloudKit.shared.nkCommonInstance.sessionIdentifierDownload
  566. result.sessionError = ""
  567. result.sessionSelector = selector
  568. result.status = NCGlobal.shared.metadataStatusWaitDownload
  569. metadata = tableMetadata(value: result)
  570. }
  571. }
  572. } catch let error {
  573. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  574. }
  575. return metadata
  576. }
  577. @discardableResult
  578. func setMetadataStatus(ocId: String, status: Int) -> tableMetadata? {
  579. var result: tableMetadata?
  580. do {
  581. let realm = try Realm()
  582. try realm.write {
  583. result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  584. result?.status = status
  585. }
  586. } catch let error {
  587. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  588. }
  589. if let result = result {
  590. return tableMetadata.init(value: result)
  591. } else {
  592. return nil
  593. }
  594. }
  595. func setMetadataEtagResource(ocId: String, etagResource: String?) {
  596. guard let etagResource = etagResource else { return }
  597. do {
  598. let realm = try Realm()
  599. try realm.write {
  600. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  601. result?.etagResource = etagResource
  602. }
  603. } catch let error {
  604. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  605. }
  606. }
  607. func setMetadataFavorite(ocId: String, favorite: Bool) {
  608. do {
  609. let realm = try Realm()
  610. try realm.write {
  611. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  612. result?.favorite = favorite
  613. }
  614. } catch let error {
  615. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  616. }
  617. }
  618. func setMetadataLivePhotoByServer(account: String, ocId: String, livePhotoFile: String) {
  619. do {
  620. let realm = try Realm()
  621. try realm.write {
  622. if let result = realm.objects(tableMetadata.self).filter("account == %@ AND ocId == %@", account, ocId).first {
  623. result.isFlaggedAsLivePhotoByServer = true
  624. result.livePhotoFile = livePhotoFile
  625. }
  626. }
  627. } catch let error {
  628. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  629. }
  630. }
  631. func updateMetadatasFavorite(account: String, metadatas: [tableMetadata]) {
  632. do {
  633. let realm = try Realm()
  634. try realm.write {
  635. let results = realm.objects(tableMetadata.self).filter("account == %@ AND favorite == true", account)
  636. for result in results {
  637. result.favorite = false
  638. }
  639. for metadata in metadatas {
  640. realm.add(metadata, update: .all)
  641. }
  642. }
  643. } catch let error {
  644. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  645. }
  646. }
  647. func setMetadataEncrypted(ocId: String, encrypted: Bool) {
  648. do {
  649. let realm = try Realm()
  650. try realm.write {
  651. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  652. result?.e2eEncrypted = encrypted
  653. }
  654. } catch let error {
  655. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  656. }
  657. }
  658. func setMetadataFileNameView(serverUrl: String, fileName: String, newFileNameView: String, account: String) {
  659. do {
  660. let realm = try Realm()
  661. try realm.write {
  662. let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first
  663. result?.fileNameView = newFileNameView
  664. }
  665. } catch let error {
  666. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  667. }
  668. }
  669. func getMetadata(predicate: NSPredicate) -> tableMetadata? {
  670. do {
  671. let realm = try Realm()
  672. realm.refresh()
  673. guard let result = realm.objects(tableMetadata.self).filter(predicate).first else { return nil }
  674. return tableMetadata.init(value: result)
  675. } catch let error as NSError {
  676. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  677. }
  678. return nil
  679. }
  680. func getMetadata(predicate: NSPredicate, sorted: String, ascending: Bool) -> tableMetadata? {
  681. do {
  682. let realm = try Realm()
  683. realm.refresh()
  684. guard let result = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending).first else { return nil }
  685. return tableMetadata.init(value: result)
  686. } catch let error as NSError {
  687. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  688. }
  689. return nil
  690. }
  691. func getMetadatas(predicate: NSPredicate) -> [tableMetadata] {
  692. do {
  693. let realm = try Realm()
  694. realm.refresh()
  695. let results = realm.objects(tableMetadata.self).filter(predicate)
  696. return Array(results.map { tableMetadata.init(value: $0) })
  697. } catch let error as NSError {
  698. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  699. }
  700. return []
  701. }
  702. func getMetadatas(predicate: NSPredicate, sorted: String, ascending: Bool = false) -> [tableMetadata]? {
  703. do {
  704. let realm = try Realm()
  705. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  706. return Array(results.map { tableMetadata.init(value: $0) })
  707. } catch let error as NSError {
  708. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  709. }
  710. return nil
  711. }
  712. func getResultsMetadatas(predicate: NSPredicate, sorted: String? = nil, ascending: Bool = false) -> Results<tableMetadata>? {
  713. do {
  714. let realm = try Realm()
  715. if let sorted {
  716. return realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  717. } else {
  718. return realm.objects(tableMetadata.self).filter(predicate)
  719. }
  720. } catch let error as NSError {
  721. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  722. }
  723. return nil
  724. }
  725. func getResultsMetadatas(predicate: NSPredicate, sorted: [RealmSwift.SortDescriptor]) -> Results<tableMetadata>? {
  726. do {
  727. let realm = try Realm()
  728. return realm.objects(tableMetadata.self).filter(predicate).sorted(by: sorted)
  729. } catch let error as NSError {
  730. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  731. }
  732. return nil
  733. }
  734. func getResultMetadata(predicate: NSPredicate) -> tableMetadata? {
  735. do {
  736. let realm = try Realm()
  737. return realm.objects(tableMetadata.self).filter(predicate).first
  738. } catch let error as NSError {
  739. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  740. }
  741. return nil
  742. }
  743. func getAdvancedMetadatas(predicate: NSPredicate, page: Int = 0, limit: Int = 0, sorted: String, ascending: Bool) -> [tableMetadata] {
  744. var metadatas: [tableMetadata] = []
  745. do {
  746. let realm = try Realm()
  747. realm.refresh()
  748. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  749. if !results.isEmpty {
  750. if page == 0 || limit == 0 {
  751. return Array(results.map { tableMetadata.init(value: $0) })
  752. } else {
  753. let nFrom = (page - 1) * limit
  754. let nTo = nFrom + (limit - 1)
  755. for n in nFrom...nTo {
  756. if n == results.count {
  757. break
  758. }
  759. metadatas.append(tableMetadata.init(value: results[n]))
  760. }
  761. }
  762. }
  763. } catch let error as NSError {
  764. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  765. }
  766. return metadatas
  767. }
  768. func getMetadataAtIndex(predicate: NSPredicate, sorted: String, ascending: Bool, index: Int) -> tableMetadata? {
  769. do {
  770. let realm = try Realm()
  771. realm.refresh()
  772. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  773. if results.isEmpty {
  774. return nil
  775. } else {
  776. return tableMetadata.init(value: results[index])
  777. }
  778. } catch let error as NSError {
  779. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  780. }
  781. return nil
  782. }
  783. func getMetadataFromOcId(_ ocId: String?) -> tableMetadata? {
  784. guard let ocId else { return nil }
  785. do {
  786. let realm = try Realm()
  787. realm.refresh()
  788. guard let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first else { return nil }
  789. return tableMetadata.init(value: result)
  790. } catch let error as NSError {
  791. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  792. }
  793. return nil
  794. }
  795. func getTableMetadataFromOcId(_ ocId: String?) -> tableMetadata? {
  796. guard let ocId else { return nil }
  797. do {
  798. let realm = try Realm()
  799. realm.refresh()
  800. return realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  801. } catch let error as NSError {
  802. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  803. }
  804. return nil
  805. }
  806. func getMetadataFromFileId(_ fileId: String?) -> tableMetadata? {
  807. do {
  808. let realm = try Realm()
  809. realm.refresh()
  810. guard let fileId = fileId else { return nil }
  811. guard let result = realm.objects(tableMetadata.self).filter("fileId == %@", fileId).first else { return nil }
  812. return tableMetadata.init(value: result)
  813. } catch let error as NSError {
  814. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  815. }
  816. return nil
  817. }
  818. func getMetadataFolder(account: String, urlBase: String, userId: String, serverUrl: String) -> tableMetadata? {
  819. var serverUrl = serverUrl
  820. var fileName = ""
  821. let serverUrlHome = utilityFileSystem.getHomeServer(urlBase: urlBase, userId: userId)
  822. if serverUrlHome == serverUrl {
  823. fileName = "."
  824. serverUrl = ".."
  825. } else {
  826. fileName = (serverUrl as NSString).lastPathComponent
  827. if let path = utilityFileSystem.deleteLastPath(serverUrlPath: serverUrl) {
  828. serverUrl = path
  829. }
  830. }
  831. do {
  832. let realm = try Realm()
  833. realm.refresh()
  834. guard let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first else { return nil }
  835. return tableMetadata.init(value: result)
  836. } catch let error as NSError {
  837. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  838. }
  839. return nil
  840. }
  841. func getTableMetadatasDirectoryFavoriteIdentifierRank(account: String) -> [String: NSNumber] {
  842. var listIdentifierRank: [String: NSNumber] = [:]
  843. var counter = 10 as Int64
  844. do {
  845. let realm = try Realm()
  846. realm.refresh()
  847. let results = realm.objects(tableMetadata.self).filter("account == %@ AND directory == true AND favorite == true", account).sorted(byKeyPath: "fileNameView", ascending: true)
  848. for result in results {
  849. counter += 1
  850. listIdentifierRank[result.ocId] = NSNumber(value: Int64(counter))
  851. }
  852. } catch let error as NSError {
  853. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  854. }
  855. return listIdentifierRank
  856. }
  857. @objc func clearMetadatasUpload(account: String) {
  858. do {
  859. let realm = try Realm()
  860. try realm.write {
  861. let results = realm.objects(tableMetadata.self).filter("account == %@ AND (status == %d OR status == %@)", account, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusUploadError)
  862. realm.delete(results)
  863. }
  864. } catch let error {
  865. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  866. }
  867. }
  868. func readMarkerMetadata(account: String, fileId: String) {
  869. do {
  870. let realm = try Realm()
  871. try realm.write {
  872. let results = realm.objects(tableMetadata.self).filter("account == %@ AND fileId == %@", account, fileId)
  873. for result in results {
  874. result.commentsUnread = false
  875. }
  876. }
  877. } catch let error {
  878. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  879. }
  880. }
  881. func getAssetLocalIdentifiersUploaded(account: String) -> [String] {
  882. var assetLocalIdentifiers: [String] = []
  883. do {
  884. let realm = try Realm()
  885. let results = realm.objects(tableMetadata.self).filter("account == %@ AND assetLocalIdentifier != '' AND deleteAssetLocalIdentifier == true", account)
  886. for result in results {
  887. assetLocalIdentifiers.append(result.assetLocalIdentifier)
  888. }
  889. } catch let error as NSError {
  890. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  891. }
  892. return assetLocalIdentifiers
  893. }
  894. func clearAssetLocalIdentifiers(_ assetLocalIdentifiers: [String], account: String) {
  895. do {
  896. let realm = try Realm()
  897. try realm.write {
  898. let results = realm.objects(tableMetadata.self).filter("account == %@ AND assetLocalIdentifier IN %@", account, assetLocalIdentifiers)
  899. for result in results {
  900. result.assetLocalIdentifier = ""
  901. result.deleteAssetLocalIdentifier = false
  902. }
  903. }
  904. } catch let error {
  905. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  906. }
  907. }
  908. func getMetadataLivePhoto(metadata: tableMetadata) -> tableMetadata? {
  909. guard metadata.isLivePhoto else { return nil }
  910. do {
  911. let realm = try Realm()
  912. guard let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileId == %@", metadata.account, metadata.serverUrl, metadata.livePhotoFile)).first else { return nil }
  913. return tableMetadata.init(value: result)
  914. } catch let error as NSError {
  915. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  916. }
  917. return nil
  918. }
  919. func isMetadataShareOrMounted(metadata: tableMetadata, metadataFolder: tableMetadata?) -> Bool {
  920. var isShare = false
  921. var isMounted = false
  922. if metadataFolder != nil {
  923. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  924. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  925. } else if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  926. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !directory.permissions.contains(NCGlobal.shared.permissionShared)
  927. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !directory.permissions.contains(NCGlobal.shared.permissionMounted)
  928. }
  929. if isShare || isMounted {
  930. return true
  931. } else {
  932. return false
  933. }
  934. }
  935. func getMetadataConflict(account: String, serverUrl: String, fileNameView: String) -> tableMetadata? {
  936. // verify exists conflict
  937. let fileNameExtension = (fileNameView as NSString).pathExtension.lowercased()
  938. let fileNameNoExtension = (fileNameView as NSString).deletingPathExtension
  939. var fileNameConflict = fileNameView
  940. if fileNameExtension == "heic", NCKeychain().formatCompatibility {
  941. fileNameConflict = fileNameNoExtension + ".jpg"
  942. }
  943. return getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account, serverUrl, fileNameConflict))
  944. }
  945. func getNumMetadatasInUpload() -> Int {
  946. do {
  947. let realm = try Realm()
  948. realm.refresh()
  949. return realm.objects(tableMetadata.self).filter(NSPredicate(format: "status == %i", NCGlobal.shared.metadataStatusUploading)).count
  950. } catch let error as NSError {
  951. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  952. }
  953. return 0
  954. }
  955. func getMetadataFromDirectory(account: String, serverUrl: String) -> tableMetadata? {
  956. do {
  957. let realm = try Realm()
  958. realm.refresh()
  959. guard let directory = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else { return nil }
  960. guard let result = realm.objects(tableMetadata.self).filter("ocId == %@", directory.ocId).first else { return nil }
  961. return tableMetadata.init(value: result)
  962. } catch let error as NSError {
  963. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  964. }
  965. return nil
  966. }
  967. func getMetadatasFromGroupfolders(account: String, urlBase: String, userId: String) -> [tableMetadata] {
  968. var metadatas: [tableMetadata] = []
  969. let homeServerUrl = utilityFileSystem.getHomeServer(urlBase: urlBase, userId: userId)
  970. do {
  971. let realm = try Realm()
  972. realm.refresh()
  973. let groupfolders = realm.objects(TableGroupfolders.self).filter("account == %@", account)
  974. for groupfolder in groupfolders {
  975. let mountPoint = groupfolder.mountPoint.hasPrefix("/") ? groupfolder.mountPoint : "/" + groupfolder.mountPoint
  976. let serverUrlFileName = homeServerUrl + mountPoint
  977. if let directory = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrlFileName).first,
  978. let metadata = realm.objects(tableMetadata.self).filter("ocId == %@", directory.ocId).first {
  979. metadatas.append(tableMetadata(value: metadata))
  980. }
  981. }
  982. } catch let error as NSError {
  983. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  984. }
  985. return metadatas
  986. }
  987. func getMetadatasInError(account: String) -> Results<tableMetadata>? {
  988. do {
  989. let realm = try Realm()
  990. let results = realm.objects(tableMetadata.self).filter("account == %@ AND errorCodeCounter > 1", account)
  991. return results
  992. } catch let error as NSError {
  993. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  994. }
  995. return nil
  996. }
  997. @discardableResult
  998. func updateMetadatas(_ metadatas: [tableMetadata], predicate: NSPredicate) -> (metadatasChangedCount: Int, metadatasChanged: Bool) {
  999. var metadatasChangedCount: Int = 0
  1000. var metadatasChanged: Bool = false
  1001. do {
  1002. let realm = try Realm()
  1003. try realm.write {
  1004. let results = realm.objects(tableMetadata.self).filter(predicate)
  1005. metadatasChangedCount = metadatas.count - results.count
  1006. for metadata in metadatas {
  1007. if let result = results.first(where: { $0.ocId == metadata.ocId }),
  1008. metadata.isEqual(result) { } else {
  1009. metadatasChanged = true
  1010. break
  1011. }
  1012. }
  1013. if metadatasChangedCount != 0 || metadatasChanged {
  1014. realm.delete(results)
  1015. for metadata in metadatas {
  1016. realm.add(tableMetadata(value: metadata), update: .all)
  1017. }
  1018. }
  1019. }
  1020. } catch let error {
  1021. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  1022. }
  1023. return (metadatasChangedCount, metadatasChanged)
  1024. }
  1025. func replaceMetadata(_ metadatas: [tableMetadata], predicate: NSPredicate) {
  1026. do {
  1027. let realm = try Realm()
  1028. try realm.write {
  1029. let results = realm.objects(tableMetadata.self).filter(predicate)
  1030. realm.delete(results)
  1031. for metadata in metadatas {
  1032. if results.where({ $0.ocId == metadata.ocId }).isEmpty {
  1033. realm.add(tableMetadata(value: metadata), update: .modified)
  1034. } else {
  1035. continue
  1036. }
  1037. }
  1038. }
  1039. } catch let error {
  1040. NextcloudKit.shared.nkCommonInstance.writeLog("Could not write to database: \(error)")
  1041. }
  1042. }
  1043. func getMediaMetadatas(predicate: NSPredicate) -> ThreadSafeArray<tableMetadata>? {
  1044. do {
  1045. let realm = try Realm()
  1046. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  1047. return ThreadSafeArray(results.map { tableMetadata.init(value: $0) })
  1048. } catch let error as NSError {
  1049. NextcloudKit.shared.nkCommonInstance.writeLog("Could not access database: \(error)")
  1050. }
  1051. return nil
  1052. }
  1053. }