NCManageDatabase+Metadata.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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 NCCommunication
  26. extension NCManageDatabase {
  27. @objc func copyObject(metadata: tableMetadata) -> tableMetadata {
  28. return tableMetadata.init(value: metadata)
  29. }
  30. @objc func convertNCFileToMetadata(_ file: NCCommunicationFile, isEncrypted: Bool, account: String) -> tableMetadata {
  31. let metadata = tableMetadata()
  32. metadata.account = account
  33. metadata.checksums = file.checksums
  34. metadata.commentsUnread = file.commentsUnread
  35. metadata.contentType = file.contentType
  36. if let date = file.creationDate {
  37. metadata.creationDate = date
  38. } else {
  39. metadata.creationDate = file.date
  40. }
  41. metadata.dataFingerprint = file.dataFingerprint
  42. metadata.date = file.date
  43. metadata.directory = file.directory
  44. metadata.downloadURL = file.downloadURL
  45. metadata.e2eEncrypted = file.e2eEncrypted
  46. metadata.etag = file.etag
  47. metadata.ext = file.ext
  48. metadata.favorite = file.favorite
  49. metadata.fileId = file.fileId
  50. metadata.fileName = file.fileName
  51. metadata.fileNameView = file.fileName
  52. metadata.fileNameWithoutExt = file.fileNameWithoutExt
  53. metadata.hasPreview = file.hasPreview
  54. metadata.iconName = file.iconName
  55. metadata.livePhoto = file.livePhoto
  56. metadata.mountType = file.mountType
  57. metadata.note = file.note
  58. metadata.ocId = file.ocId
  59. metadata.ownerId = file.ownerId
  60. metadata.ownerDisplayName = file.ownerDisplayName
  61. metadata.lock = file.lock
  62. metadata.lockOwner = file.lockOwner
  63. metadata.lockOwnerEditor = file.lockOwnerEditor
  64. metadata.lockOwnerType = file.lockOwnerType
  65. metadata.lockOwnerDisplayName = file.lockOwnerDisplayName
  66. metadata.lockTime = file.lockTime
  67. metadata.lockTimeOut = file.lockTimeOut
  68. metadata.path = file.path
  69. metadata.permissions = file.permissions
  70. metadata.quotaUsedBytes = file.quotaUsedBytes
  71. metadata.quotaAvailableBytes = file.quotaAvailableBytes
  72. metadata.richWorkspace = file.richWorkspace
  73. metadata.resourceType = file.resourceType
  74. metadata.serverUrl = file.serverUrl
  75. metadata.sharePermissionsCollaborationServices = file.sharePermissionsCollaborationServices
  76. for element in file.sharePermissionsCloudMesh {
  77. metadata.sharePermissionsCloudMesh.append(element)
  78. }
  79. for element in file.shareType {
  80. metadata.shareType.append(element)
  81. }
  82. metadata.size = file.size
  83. metadata.classFile = file.classFile
  84. if let date = file.uploadDate {
  85. metadata.uploadDate = date
  86. } else {
  87. metadata.uploadDate = file.date
  88. }
  89. metadata.urlBase = file.urlBase
  90. metadata.user = file.user
  91. metadata.userId = file.userId
  92. // E2EE find the fileName for fileNameView
  93. if isEncrypted || metadata.e2eEncrypted {
  94. if let tableE2eEncryption = NCManageDatabase.shared.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", account, file.serverUrl, file.fileName)) {
  95. metadata.fileNameView = tableE2eEncryption.fileName
  96. let results = NCCommunicationCommon.shared.getInternalType(fileName: metadata.fileNameView, mimeType: file.contentType, directory: file.directory)
  97. metadata.contentType = results.mimeType
  98. metadata.iconName = results.iconName
  99. metadata.classFile = results.classFile
  100. }
  101. }
  102. // Live Photo "DETECT"
  103. if !metadata.directory && !metadata.livePhoto && (metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue || metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue) {
  104. var classFile = metadata.classFile
  105. if classFile == NCCommunicationCommon.typeClassFile.image.rawValue {
  106. classFile = NCCommunicationCommon.typeClassFile.video.rawValue
  107. } else {
  108. classFile = NCCommunicationCommon.typeClassFile.image.rawValue
  109. }
  110. if getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameWithoutExt == %@ AND ocId != %@ AND classFile == %@", metadata.account, metadata.serverUrl, metadata.fileNameWithoutExt, metadata.ocId, classFile)) != nil {
  111. metadata.livePhoto = true
  112. }
  113. }
  114. return metadata
  115. }
  116. @objc func convertNCCommunicationFilesToMetadatas(_ files: [NCCommunicationFile], useMetadataFolder: Bool, account: String, completion: @escaping (_ metadataFolder: tableMetadata, _ metadatasFolder: [tableMetadata], _ metadatas: [tableMetadata]) -> Void) {
  117. var counter: Int = 0
  118. var isEncrypted: Bool = false
  119. var listServerUrl: [String: Bool] = [:]
  120. var metadataFolder = tableMetadata()
  121. var metadataFolders: [tableMetadata] = []
  122. var metadatas: [tableMetadata] = []
  123. for file in files {
  124. if let key = listServerUrl[file.serverUrl] {
  125. isEncrypted = key
  126. } else {
  127. isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted: file.e2eEncrypted, account: account, urlBase: file.urlBase)
  128. listServerUrl[file.serverUrl] = isEncrypted
  129. }
  130. let metadata = convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
  131. if counter == 0 && useMetadataFolder {
  132. metadataFolder = tableMetadata.init(value: metadata)
  133. } else {
  134. metadatas.append(metadata)
  135. if metadata.directory {
  136. metadataFolders.append(metadata)
  137. }
  138. }
  139. counter += 1
  140. }
  141. completion(metadataFolder, metadataFolders, metadatas)
  142. }
  143. @objc func createMetadata(account: String, user: String, userId: String, fileName: String, fileNameView: String, ocId: String, serverUrl: String, urlBase: String, url: String, contentType: String, livePhoto: Bool) -> tableMetadata {
  144. let metadata = tableMetadata()
  145. let resultInternalType = NCCommunicationCommon.shared.getInternalType(fileName: fileName, mimeType: contentType, directory: false)
  146. let fileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
  147. metadata.account = account
  148. metadata.chunk = false
  149. metadata.contentType = resultInternalType.mimeType
  150. metadata.creationDate = Date() as NSDate
  151. metadata.date = Date() as NSDate
  152. metadata.hasPreview = true
  153. metadata.iconName = resultInternalType.iconName
  154. metadata.etag = ocId
  155. metadata.ext = (fileName as NSString).pathExtension.lowercased()
  156. metadata.fileName = fileName
  157. metadata.fileNameView = fileName
  158. metadata.fileNameWithoutExt = (fileName as NSString).deletingPathExtension
  159. metadata.livePhoto = livePhoto
  160. metadata.ocId = ocId
  161. metadata.permissions = "RGDNVW"
  162. metadata.serverUrl = serverUrl
  163. metadata.classFile = resultInternalType.classFile
  164. metadata.uploadDate = Date() as NSDate
  165. metadata.url = url
  166. metadata.urlBase = urlBase
  167. metadata.user = user
  168. metadata.userId = userId
  169. if !metadata.urlBase.isEmpty, metadata.serverUrl.hasPrefix(metadata.urlBase) {
  170. metadata.path = String(metadata.serverUrl.dropFirst(metadata.urlBase.count)) + "/"
  171. }
  172. return metadata
  173. }
  174. @objc func addMetadata(_ metadata: tableMetadata) {
  175. let realm = try! Realm()
  176. do {
  177. try realm.safeWrite {
  178. realm.add(metadata, update: .all)
  179. }
  180. } catch let error {
  181. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  182. }
  183. }
  184. @objc func addMetadatas(_ metadatas: [tableMetadata]) {
  185. let realm = try! Realm()
  186. do {
  187. try realm.safeWrite {
  188. for metadata in metadatas {
  189. realm.add(metadata, update: .all)
  190. }
  191. }
  192. } catch let error {
  193. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  194. }
  195. }
  196. @objc func deleteMetadata(predicate: NSPredicate) {
  197. let realm = try! Realm()
  198. do {
  199. try realm.safeWrite {
  200. let results = realm.objects(tableMetadata.self).filter(predicate)
  201. realm.delete(results)
  202. }
  203. } catch let error {
  204. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  205. }
  206. }
  207. @objc func moveMetadata(ocId: String, serverUrlTo: String) {
  208. let realm = try! Realm()
  209. do {
  210. try realm.safeWrite {
  211. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  212. result.serverUrl = serverUrlTo
  213. }
  214. }
  215. } catch let error {
  216. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  217. }
  218. }
  219. @objc func addMetadataServerUrl(ocId: String, serverUrl: String) {
  220. let realm = try! Realm()
  221. do {
  222. try realm.safeWrite {
  223. let results = realm.objects(tableMetadata.self).filter("ocId == %@", ocId)
  224. for result in results {
  225. result.serverUrl = serverUrl
  226. }
  227. }
  228. } catch let error {
  229. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  230. }
  231. }
  232. @objc func renameMetadata(fileNameTo: String, ocId: String) {
  233. let realm = try! Realm()
  234. do {
  235. try realm.safeWrite {
  236. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  237. let resultsType = NCCommunicationCommon.shared.getInternalType(fileName: fileNameTo, mimeType: "", directory: result.directory)
  238. result.fileName = fileNameTo
  239. result.fileNameView = fileNameTo
  240. if result.directory {
  241. result.fileNameWithoutExt = fileNameTo
  242. result.ext = ""
  243. } else {
  244. result.fileNameWithoutExt = (fileNameTo as NSString).deletingPathExtension
  245. result.ext = resultsType.ext
  246. }
  247. result.iconName = resultsType.iconName
  248. result.contentType = resultsType.mimeType
  249. result.classFile = resultsType.classFile
  250. }
  251. }
  252. } catch let error {
  253. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  254. }
  255. }
  256. @discardableResult
  257. func updateMetadatas(_ metadatas: [tableMetadata], metadatasResult: [tableMetadata], addCompareLivePhoto: Bool = true, addExistsInLocal: Bool = false, addCompareEtagLocal: Bool = false, addDirectorySynchronized: Bool = false) -> (metadatasUpdate: [tableMetadata], metadatasLocalUpdate: [tableMetadata], metadatasDelete: [tableMetadata]) {
  258. let realm = try! Realm()
  259. var ocIdsUdate: [String] = []
  260. var ocIdsLocalUdate: [String] = []
  261. var metadatasDelete: [tableMetadata] = []
  262. var metadatasUpdate: [tableMetadata] = []
  263. var metadatasLocalUpdate: [tableMetadata] = []
  264. realm.refresh()
  265. do {
  266. try realm.safeWrite {
  267. // DELETE
  268. for metadataResult in metadatasResult {
  269. if metadatas.firstIndex(where: { $0.ocId == metadataResult.ocId }) == nil {
  270. if let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "ocId == %@", metadataResult.ocId)).first {
  271. metadatasDelete.append(tableMetadata.init(value: result))
  272. realm.delete(result)
  273. }
  274. }
  275. }
  276. // UPDATE/NEW
  277. for metadata in metadatas {
  278. if let result = metadatasResult.first(where: { $0.ocId == metadata.ocId }) {
  279. // update
  280. // Workaround: check lock bc no etag changes if lock runs out in directory
  281. // https://github.com/nextcloud/server/issues/8477
  282. if result.status == NCGlobal.shared.metadataStatusNormal && (result.etag != metadata.etag || result.fileNameView != metadata.fileNameView || result.date != metadata.date || result.permissions != metadata.permissions || result.hasPreview != metadata.hasPreview || result.note != metadata.note || result.lock != metadata.lock) {
  283. ocIdsUdate.append(metadata.ocId)
  284. realm.add(tableMetadata.init(value: metadata), update: .all)
  285. } else if result.status == NCGlobal.shared.metadataStatusNormal && addCompareLivePhoto && result.livePhoto != metadata.livePhoto {
  286. ocIdsUdate.append(metadata.ocId)
  287. realm.add(tableMetadata.init(value: metadata), update: .all)
  288. }
  289. } else {
  290. // new
  291. ocIdsUdate.append(metadata.ocId)
  292. realm.add(tableMetadata.init(value: metadata), update: .all)
  293. }
  294. if metadata.directory && !ocIdsUdate.contains(metadata.ocId) {
  295. let table = realm.objects(tableDirectory.self).filter(NSPredicate(format: "ocId == %@", metadata.ocId)).first
  296. if table?.etag != metadata.etag {
  297. ocIdsUdate.append(metadata.ocId)
  298. }
  299. }
  300. // Local
  301. if !metadata.directory && (addExistsInLocal || addCompareEtagLocal) {
  302. let localFile = realm.objects(tableLocalFile.self).filter(NSPredicate(format: "ocId == %@", metadata.ocId)).first
  303. if addCompareEtagLocal && localFile != nil && localFile?.etag != metadata.etag {
  304. ocIdsLocalUdate.append(metadata.ocId)
  305. }
  306. if addExistsInLocal && (localFile == nil || localFile?.etag != metadata.etag) && !ocIdsLocalUdate.contains(metadata.ocId) {
  307. ocIdsLocalUdate.append(metadata.ocId)
  308. }
  309. }
  310. }
  311. }
  312. } catch let error {
  313. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  314. }
  315. for ocId in ocIdsUdate {
  316. if let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "ocId == %@", ocId)).first {
  317. metadatasUpdate.append(tableMetadata.init(value: result))
  318. }
  319. }
  320. for ocId in ocIdsLocalUdate {
  321. if let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "ocId == %@", ocId)).first {
  322. metadatasLocalUpdate.append(tableMetadata.init(value: result))
  323. }
  324. }
  325. return (metadatasUpdate, metadatasLocalUpdate, metadatasDelete)
  326. }
  327. func setMetadataSession(ocId: String, session: String? = nil, sessionError: String? = nil, sessionSelector: String? = nil, sessionTaskIdentifier: Int? = nil, status: Int? = nil, etag: String? = nil) {
  328. let realm = try! Realm()
  329. realm.refresh()
  330. do {
  331. try realm.safeWrite {
  332. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  333. if let session = session {
  334. result?.session = session
  335. }
  336. if let sessionError = sessionError {
  337. result?.sessionError = sessionError
  338. }
  339. if let sessionSelector = sessionSelector {
  340. result?.sessionSelector = sessionSelector
  341. }
  342. if let sessionTaskIdentifier = sessionTaskIdentifier {
  343. result?.sessionTaskIdentifier = sessionTaskIdentifier
  344. }
  345. if let status = status {
  346. result?.status = status
  347. }
  348. if let etag = etag {
  349. result?.etag = etag
  350. }
  351. }
  352. } catch let error {
  353. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  354. }
  355. }
  356. @discardableResult
  357. func setMetadataStatus(ocId: String, status: Int) -> tableMetadata? {
  358. let realm = try! Realm()
  359. var result: tableMetadata?
  360. do {
  361. try realm.safeWrite {
  362. result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  363. result?.status = status
  364. }
  365. } catch let error {
  366. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  367. }
  368. if let result = result {
  369. return tableMetadata.init(value: result)
  370. } else {
  371. return nil
  372. }
  373. }
  374. func setMetadataEtagResource(ocId: String, etagResource: String?) {
  375. let realm = try! Realm()
  376. var result: tableMetadata?
  377. guard let etagResource = etagResource else { return }
  378. do {
  379. try realm.safeWrite {
  380. result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  381. result?.etagResource = etagResource
  382. }
  383. } catch let error {
  384. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  385. }
  386. }
  387. @objc func setMetadataFavorite(ocId: String, favorite: Bool) {
  388. let realm = try! Realm()
  389. do {
  390. try realm.safeWrite {
  391. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  392. result?.favorite = favorite
  393. }
  394. } catch let error {
  395. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  396. }
  397. }
  398. @objc func updateMetadatasFavorite(account: String, metadatas: [tableMetadata]) {
  399. let realm = try! Realm()
  400. do {
  401. try realm.safeWrite {
  402. let results = realm.objects(tableMetadata.self).filter("account == %@ AND favorite == true", account)
  403. for result in results {
  404. result.favorite = false
  405. }
  406. for metadata in metadatas {
  407. realm.add(metadata, update: .all)
  408. }
  409. }
  410. } catch let error {
  411. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  412. }
  413. }
  414. @objc func setMetadataEncrypted(ocId: String, encrypted: Bool) {
  415. let realm = try! Realm()
  416. do {
  417. try realm.safeWrite {
  418. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  419. result?.e2eEncrypted = encrypted
  420. }
  421. } catch let error {
  422. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  423. }
  424. }
  425. @objc func setMetadataFileNameView(serverUrl: String, fileName: String, newFileNameView: String, account: String) {
  426. let realm = try! Realm()
  427. do {
  428. try realm.safeWrite {
  429. let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first
  430. result?.fileNameView = newFileNameView
  431. }
  432. } catch let error {
  433. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  434. }
  435. }
  436. @objc func getMetadata(predicate: NSPredicate) -> tableMetadata? {
  437. let realm = try! Realm()
  438. realm.refresh()
  439. guard let result = realm.objects(tableMetadata.self).filter(predicate).first else {
  440. return nil
  441. }
  442. return tableMetadata.init(value: result)
  443. }
  444. @objc func getMetadata(predicate: NSPredicate, sorted: String, ascending: Bool) -> tableMetadata? {
  445. let realm = try! Realm()
  446. realm.refresh()
  447. guard let result = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending).first else {
  448. return nil
  449. }
  450. return tableMetadata.init(value: result)
  451. }
  452. @objc func getMetadatasViewer(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableMetadata]? {
  453. let realm = try! Realm()
  454. realm.refresh()
  455. let results: Results<tableMetadata>
  456. var finals: [tableMetadata] = []
  457. if (tableMetadata().objectSchema.properties.contains { $0.name == sorted }) {
  458. results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  459. } else {
  460. results = realm.objects(tableMetadata.self).filter(predicate)
  461. }
  462. // For Live Photo
  463. var fileNameImages: [String] = []
  464. let filtered = results.filter { $0.classFile.contains(NCCommunicationCommon.typeClassFile.image.rawValue) }
  465. filtered.forEach { print($0)
  466. let fileName = ($0.fileNameView as NSString).deletingPathExtension
  467. fileNameImages.append(fileName)
  468. }
  469. for result in results {
  470. let ext = (result.fileNameView as NSString).pathExtension.uppercased()
  471. let fileName = (result.fileNameView as NSString).deletingPathExtension
  472. if !(ext == "MOV" && fileNameImages.contains(fileName)) {
  473. finals.append(result)
  474. }
  475. }
  476. if finals.count > 0 {
  477. return Array(finals.map { tableMetadata.init(value: $0) })
  478. } else {
  479. return nil
  480. }
  481. }
  482. @objc func getMetadatas(predicate: NSPredicate) -> [tableMetadata] {
  483. let realm = try! Realm()
  484. realm.refresh()
  485. let results = realm.objects(tableMetadata.self).filter(predicate)
  486. return Array(results.map { tableMetadata.init(value: $0) })
  487. }
  488. @objc func getAdvancedMetadatas(predicate: NSPredicate, page: Int = 0, limit: Int = 0, sorted: String, ascending: Bool) -> [tableMetadata] {
  489. let realm = try! Realm()
  490. realm.refresh()
  491. var metadatas: [tableMetadata] = []
  492. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  493. if results.count > 0 {
  494. if page == 0 || limit == 0 {
  495. return Array(results.map { tableMetadata.init(value: $0) })
  496. } else {
  497. let nFrom = (page - 1) * limit
  498. let nTo = nFrom + (limit - 1)
  499. for n in nFrom...nTo {
  500. if n == results.count {
  501. break
  502. }
  503. metadatas.append(tableMetadata.init(value: results[n]))
  504. }
  505. }
  506. }
  507. return metadatas
  508. }
  509. @objc func getMetadataAtIndex(predicate: NSPredicate, sorted: String, ascending: Bool, index: Int) -> tableMetadata? {
  510. let realm = try! Realm()
  511. realm.refresh()
  512. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  513. if results.count > 0 && results.count > index {
  514. return tableMetadata.init(value: results[index])
  515. } else {
  516. return nil
  517. }
  518. }
  519. @objc func getMetadataFromOcId(_ ocId: String?) -> tableMetadata? {
  520. let realm = try! Realm()
  521. realm.refresh()
  522. guard let ocId = ocId else { return nil }
  523. guard let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first else { return nil }
  524. return tableMetadata.init(value: result)
  525. }
  526. @objc func getMetadataFolder(account: String, urlBase: String, serverUrl: String) -> tableMetadata? {
  527. let realm = try! Realm()
  528. realm.refresh()
  529. var serverUrl = serverUrl
  530. var fileName = ""
  531. let serverUrlHome = NCUtilityFileSystem.shared.getHomeServer(account: account)
  532. if serverUrlHome == serverUrl {
  533. fileName = "."
  534. serverUrl = ".."
  535. } else {
  536. fileName = (serverUrl as NSString).lastPathComponent
  537. serverUrl = NCUtilityFileSystem.shared.deletingLastPathComponent(account: account, serverUrl: serverUrl)
  538. }
  539. guard let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first else { return nil }
  540. return tableMetadata.init(value: result)
  541. }
  542. @objc func getTableMetadatasDirectoryFavoriteIdentifierRank(account: String) -> [String: NSNumber] {
  543. var listIdentifierRank: [String: NSNumber] = [:]
  544. let realm = try! Realm()
  545. var counter = 10 as Int64
  546. let results = realm.objects(tableMetadata.self).filter("account == %@ AND directory == true AND favorite == true", account).sorted(byKeyPath: "fileNameView", ascending: true)
  547. for result in results {
  548. counter += 1
  549. listIdentifierRank[result.ocId] = NSNumber(value: Int64(counter))
  550. }
  551. return listIdentifierRank
  552. }
  553. @objc func clearMetadatasUpload(account: String) {
  554. let realm = try! Realm()
  555. realm.refresh()
  556. do {
  557. try realm.safeWrite {
  558. let results = realm.objects(tableMetadata.self).filter("account == %@ AND (status == %d OR status == %@)", account, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusUploadError)
  559. realm.delete(results)
  560. }
  561. } catch let error {
  562. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  563. }
  564. }
  565. @objc func readMarkerMetadata(account: String, fileId: String) {
  566. let realm = try! Realm()
  567. do {
  568. try realm.safeWrite {
  569. let results = realm.objects(tableMetadata.self).filter("account == %@ AND fileId == %@", account, fileId)
  570. for result in results {
  571. result.commentsUnread = false
  572. }
  573. }
  574. } catch let error {
  575. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  576. }
  577. }
  578. @objc func getAssetLocalIdentifiersUploaded(account: String, sessionSelector: String) -> [String] {
  579. let realm = try! Realm()
  580. realm.refresh()
  581. var assetLocalIdentifiers: [String] = []
  582. let results = realm.objects(tableMetadata.self).filter("account == %@ AND assetLocalIdentifier != '' AND deleteAssetLocalIdentifier == true AND sessionSelector == %@", account, sessionSelector)
  583. for result in results {
  584. assetLocalIdentifiers.append(result.assetLocalIdentifier)
  585. }
  586. return assetLocalIdentifiers
  587. }
  588. @objc func clearAssetLocalIdentifiers(_ assetLocalIdentifiers: [String], account: String) {
  589. let realm = try! Realm()
  590. do {
  591. try realm.safeWrite {
  592. let results = realm.objects(tableMetadata.self).filter("account == %@ AND assetLocalIdentifier IN %@", account, assetLocalIdentifiers)
  593. for result in results {
  594. result.assetLocalIdentifier = ""
  595. result.deleteAssetLocalIdentifier = false
  596. }
  597. }
  598. } catch let error {
  599. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  600. }
  601. }
  602. @objc func getMetadataLivePhoto(metadata: tableMetadata) -> tableMetadata? {
  603. let realm = try! Realm()
  604. var classFile = metadata.classFile
  605. realm.refresh()
  606. if !metadata.livePhoto || !CCUtility.getLivePhoto() {
  607. return nil
  608. }
  609. if classFile == NCCommunicationCommon.typeClassFile.image.rawValue {
  610. classFile = NCCommunicationCommon.typeClassFile.video.rawValue
  611. } else {
  612. classFile = NCCommunicationCommon.typeClassFile.image.rawValue
  613. }
  614. guard let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameWithoutExt == %@ AND ocId != %@ AND classFile == %@", metadata.account, metadata.serverUrl, metadata.fileNameWithoutExt, metadata.ocId, classFile)).first else {
  615. return nil
  616. }
  617. return tableMetadata.init(value: result)
  618. }
  619. func getMetadatasMedia(predicate: NSPredicate, sort: String, ascending: Bool = false) -> [tableMetadata] {
  620. let realm = try! Realm()
  621. realm.refresh()
  622. let sortProperties = [SortDescriptor(keyPath: sort, ascending: ascending), SortDescriptor(keyPath: "fileNameView", ascending: false)]
  623. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(by: sortProperties)
  624. return Array(results.map { tableMetadata.init(value: $0) })
  625. }
  626. func isMetadataShareOrMounted(metadata: tableMetadata, metadataFolder: tableMetadata?) -> Bool {
  627. var isShare = false
  628. var isMounted = false
  629. if metadataFolder != nil {
  630. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionShared)
  631. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !metadataFolder!.permissions.contains(NCGlobal.shared.permissionMounted)
  632. } else if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  633. isShare = metadata.permissions.contains(NCGlobal.shared.permissionShared) && !directory.permissions.contains(NCGlobal.shared.permissionShared)
  634. isMounted = metadata.permissions.contains(NCGlobal.shared.permissionMounted) && !directory.permissions.contains(NCGlobal.shared.permissionMounted)
  635. }
  636. if isShare || isMounted {
  637. return true
  638. } else {
  639. return false
  640. }
  641. }
  642. func isDownloadMetadata(_ metadata: tableMetadata, download: Bool) -> Bool {
  643. let localFile = getTableLocalFile(predicate: NSPredicate(format: "ocId == %@", metadata.ocId))
  644. let fileSize = CCUtility.fileProviderStorageSize(metadata.ocId, fileNameView: metadata.fileNameView)
  645. if (localFile != nil || download) && (localFile?.etag != metadata.etag || fileSize == 0) {
  646. return true
  647. }
  648. return false
  649. }
  650. func getMetadataConflict(account: String, serverUrl: String, fileName: String) -> tableMetadata? {
  651. // verify exists conflict
  652. let fileNameExtension = (fileName as NSString).pathExtension.lowercased()
  653. let fileNameWithoutExtension = (fileName as NSString).deletingPathExtension
  654. var fileNameConflict = fileName
  655. if fileNameExtension == "heic" && CCUtility.getFormatCompatibility() {
  656. fileNameConflict = fileNameWithoutExtension + ".jpg"
  657. }
  658. return getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account, serverUrl, fileNameConflict))
  659. }
  660. func getSubtitles(account: String, serverUrl: String, fileName: String) -> (all:[tableMetadata], existing:[tableMetadata]) {
  661. let realm = try! Realm()
  662. let nameOnly = (fileName as NSString).deletingPathExtension + "."
  663. var metadatas: [tableMetadata] = []
  664. let results = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName BEGINSWITH[c] %@ AND fileName ENDSWITH[c] '.srt'", account, serverUrl, nameOnly)
  665. for result in results {
  666. if CCUtility.fileProviderStorageExists(result) {
  667. metadatas.append(result)
  668. }
  669. }
  670. return(Array(results.map { tableMetadata.init(value: $0) }), Array(metadatas.map { tableMetadata.init(value: $0) }))
  671. }
  672. }