NCManageDatabase+Metadata.swift 45 KB

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