NCManageDatabase+Metadata.swift 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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 UIKit
  25. import RealmSwift
  26. import NextcloudKit
  27. class tableMetadata: Object {
  28. override func isEqual(_ object: Any?) -> Bool {
  29. if let object = object as? tableMetadata,
  30. self.account == object.account,
  31. self.etag == object.etag,
  32. self.fileId == object.fileId,
  33. self.path == object.path,
  34. self.fileName == object.fileName,
  35. self.fileNameView == object.fileNameView,
  36. self.date == object.date,
  37. self.datePhotosOriginal == object.datePhotosOriginal,
  38. self.permissions == object.permissions,
  39. self.hasPreview == object.hasPreview,
  40. self.note == object.note,
  41. self.lock == object.lock,
  42. self.favorite == object.favorite,
  43. self.livePhotoFile == object.livePhotoFile,
  44. self.sharePermissionsCollaborationServices == object.sharePermissionsCollaborationServices,
  45. self.height == object.height,
  46. self.width == object.width,
  47. self.latitude == object.latitude,
  48. self.longitude == object.longitude,
  49. self.altitude == object.altitude,
  50. self.status == object.status,
  51. Array(self.tags).elementsEqual(Array(object.tags)),
  52. Array(self.shareType).elementsEqual(Array(object.shareType)),
  53. Array(self.sharePermissionsCloudMesh).elementsEqual(Array(object.sharePermissionsCloudMesh)) {
  54. return true
  55. } else {
  56. return false
  57. }
  58. }
  59. @objc dynamic var account = ""
  60. @objc dynamic var assetLocalIdentifier = ""
  61. @objc dynamic var checksums = ""
  62. @objc dynamic var chunk: Int = 0
  63. @objc dynamic var classFile = ""
  64. @objc dynamic var commentsUnread: Bool = false
  65. @objc dynamic var contentType = ""
  66. @objc dynamic var creationDate = NSDate()
  67. @objc dynamic var dataFingerprint = ""
  68. @objc dynamic var date = NSDate()
  69. @objc dynamic var datePhotosOriginal = NSDate()
  70. @objc dynamic var directory: Bool = false
  71. @objc dynamic var downloadURL = ""
  72. @objc dynamic var e2eEncrypted: Bool = false
  73. @objc dynamic var edited: Bool = false
  74. @objc dynamic var etag = ""
  75. @objc dynamic var etagResource = ""
  76. let exifPhotos = List<NCKeyValue>()
  77. @objc dynamic var favorite: Bool = false
  78. @objc dynamic var fileId = ""
  79. @objc dynamic var fileName = ""
  80. @objc dynamic var fileNameView = ""
  81. @objc dynamic var hasPreview: Bool = false
  82. @objc dynamic var hidden: Bool = false
  83. @objc dynamic var iconName = ""
  84. @objc dynamic var iconUrl = ""
  85. @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
  86. @objc dynamic var isExtractFile: Bool = false
  87. @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)
  88. @objc dynamic var mountType = ""
  89. @objc dynamic var name = "" // for unifiedSearch is the provider.id
  90. @objc dynamic var note = ""
  91. @objc dynamic var ocId = ""
  92. @objc dynamic var ocIdTransfer = ""
  93. @objc dynamic var ownerId = ""
  94. @objc dynamic var ownerDisplayName = ""
  95. @objc public var lock = false
  96. @objc public var lockOwner = ""
  97. @objc public var lockOwnerEditor = ""
  98. @objc public var lockOwnerType = 0
  99. @objc public var lockOwnerDisplayName = ""
  100. @objc public var lockTime: Date?
  101. @objc public var lockTimeOut: Date?
  102. @objc dynamic var path = ""
  103. @objc dynamic var permissions = ""
  104. @objc dynamic var placePhotos: String?
  105. @objc dynamic var quotaUsedBytes: Int64 = 0
  106. @objc dynamic var quotaAvailableBytes: Int64 = 0
  107. @objc dynamic var resourceType = ""
  108. @objc dynamic var richWorkspace: String?
  109. @objc dynamic var sceneIdentifier: String?
  110. @objc dynamic var serverUrl = ""
  111. @objc dynamic var serveUrlFileName = ""
  112. @objc dynamic var serverUrlTo = ""
  113. @objc dynamic var session = ""
  114. @objc dynamic var sessionDate: Date?
  115. @objc dynamic var sessionError = ""
  116. @objc dynamic var sessionSelector = ""
  117. @objc dynamic var sessionTaskIdentifier: Int = 0
  118. @objc dynamic var sharePermissionsCollaborationServices: Int = 0
  119. let sharePermissionsCloudMesh = List<String>()
  120. let shareType = List<Int>()
  121. @objc dynamic var size: Int64 = 0
  122. @objc dynamic var status: Int = 0
  123. @objc dynamic var storeFlag: String?
  124. @objc dynamic var subline: String?
  125. let tags = List<String>()
  126. @objc dynamic var trashbinFileName = ""
  127. @objc dynamic var trashbinOriginalLocation = ""
  128. @objc dynamic var trashbinDeletionTime = NSDate()
  129. @objc dynamic var uploadDate = NSDate()
  130. @objc dynamic var url = ""
  131. @objc dynamic var urlBase = ""
  132. @objc dynamic var user = ""
  133. @objc dynamic var userId = ""
  134. @objc dynamic var latitude: Double = 0
  135. @objc dynamic var longitude: Double = 0
  136. @objc dynamic var altitude: Double = 0
  137. @objc dynamic var height: Int = 0
  138. @objc dynamic var width: Int = 0
  139. @objc dynamic var errorCode: Int = 0
  140. override static func primaryKey() -> String {
  141. return "ocId"
  142. }
  143. }
  144. extension tableMetadata {
  145. var fileExtension: String {
  146. (fileNameView as NSString).pathExtension
  147. }
  148. var fileNoExtension: String {
  149. (fileNameView as NSString).deletingPathExtension
  150. }
  151. var isRenameable: Bool {
  152. if lock {
  153. return false
  154. }
  155. if !isDirectoryE2EE && e2eEncrypted {
  156. return false
  157. }
  158. return true
  159. }
  160. var isPrintable: Bool {
  161. if isDocumentViewableOnly {
  162. return false
  163. }
  164. if ["application/pdf", "com.adobe.pdf"].contains(contentType) || contentType.hasPrefix("text/") || classFile == NKCommon.TypeClassFile.image.rawValue {
  165. return true
  166. }
  167. return false
  168. }
  169. var isSavebleInCameraRoll: Bool {
  170. return (classFile == NKCommon.TypeClassFile.image.rawValue && contentType != "image/svg+xml") || classFile == NKCommon.TypeClassFile.video.rawValue
  171. }
  172. var isDocumentViewableOnly: Bool {
  173. sharePermissionsCollaborationServices == NCPermissions().permissionReadShare && classFile == NKCommon.TypeClassFile.document.rawValue
  174. }
  175. var isAudioOrVideo: Bool {
  176. return classFile == NKCommon.TypeClassFile.audio.rawValue || classFile == NKCommon.TypeClassFile.video.rawValue
  177. }
  178. var isImageOrVideo: Bool {
  179. return classFile == NKCommon.TypeClassFile.image.rawValue || classFile == NKCommon.TypeClassFile.video.rawValue
  180. }
  181. var isVideo: Bool {
  182. return classFile == NKCommon.TypeClassFile.video.rawValue
  183. }
  184. var isAudio: Bool {
  185. return classFile == NKCommon.TypeClassFile.audio.rawValue
  186. }
  187. var isImage: Bool {
  188. return classFile == NKCommon.TypeClassFile.image.rawValue
  189. }
  190. var isSavebleAsImage: Bool {
  191. classFile == NKCommon.TypeClassFile.image.rawValue && contentType != "image/svg+xml"
  192. }
  193. var isCopyableInPasteboard: Bool {
  194. !isDocumentViewableOnly && !directory
  195. }
  196. var isCopyableMovable: Bool {
  197. !isDocumentViewableOnly && !isDirectoryE2EE && !e2eEncrypted
  198. }
  199. var isModifiableWithQuickLook: Bool {
  200. if directory || isDocumentViewableOnly || isDirectoryE2EE {
  201. return false
  202. }
  203. return isPDF || isImage
  204. }
  205. var isDeletable: Bool {
  206. if !isDirectoryE2EE && e2eEncrypted {
  207. return false
  208. }
  209. return true
  210. }
  211. var canSetAsAvailableOffline: Bool {
  212. return session.isEmpty && !isDirectoryE2EE && !e2eEncrypted
  213. }
  214. var canShare: Bool {
  215. return session.isEmpty && !isDocumentViewableOnly && !directory && !NCBrandOptions.shared.disable_openin_file
  216. }
  217. var canSetDirectoryAsE2EE: Bool {
  218. return directory && size == 0 && !e2eEncrypted && NCKeychain().isEndToEndEnabled(account: account)
  219. }
  220. var canUnsetDirectoryAsE2EE: Bool {
  221. return !isDirectoryE2EE && directory && size == 0 && e2eEncrypted && NCKeychain().isEndToEndEnabled(account: account)
  222. }
  223. var isDownload: Bool {
  224. status == NCGlobal.shared.metadataStatusWaitDownload || status == NCGlobal.shared.metadataStatusDownloading
  225. }
  226. var isUpload: Bool {
  227. status == NCGlobal.shared.metadataStatusWaitUpload || status == NCGlobal.shared.metadataStatusUploading
  228. }
  229. var isDirectory: Bool {
  230. directory
  231. }
  232. @objc var isDirectoryE2EE: Bool {
  233. let session = NCSession.Session(account: account, urlBase: urlBase, user: user, userId: userId)
  234. return NCUtilityFileSystem().isDirectoryE2EE(session: session, serverUrl: serverUrl)
  235. }
  236. var isDirectoryE2EETop: Bool {
  237. NCUtilityFileSystem().isDirectoryE2EETop(account: account, serverUrl: serverUrl)
  238. }
  239. var isLivePhoto: Bool {
  240. !livePhotoFile.isEmpty
  241. }
  242. var isNotFlaggedAsLivePhotoByServer: Bool {
  243. !isFlaggedAsLivePhotoByServer
  244. }
  245. var imageSize: CGSize {
  246. CGSize(width: width, height: height)
  247. }
  248. var hasPreviewBorder: Bool {
  249. !isImage && !isAudioOrVideo && hasPreview && NCUtilityFileSystem().fileProviderStorageImageExists(ocId, etag: etag, ext: NCGlobal.shared.previewExt1024)
  250. }
  251. var isAvailableEditorView: Bool {
  252. guard !isPDF,
  253. classFile == NKCommon.TypeClassFile.document.rawValue,
  254. NextcloudKit.shared.isNetworkReachable() else { return false }
  255. let utility = NCUtility()
  256. let directEditingEditors = utility.editorsDirectEditing(account: account, contentType: contentType)
  257. let richDocumentEditor = utility.isTypeFileRichDocument(self)
  258. if NCCapabilities.shared.getCapabilities(account: account).capabilityRichDocumentsEnabled && richDocumentEditor && directEditingEditors.isEmpty {
  259. // RichDocument: Collabora
  260. return true
  261. } else if directEditingEditors.contains(NCGlobal.shared.editorText) || directEditingEditors.contains(NCGlobal.shared.editorOnlyoffice) {
  262. // DirectEditing: Nextcloud Text - OnlyOffice
  263. return true
  264. }
  265. return false
  266. }
  267. var isAvailableRichDocumentEditorView: Bool {
  268. guard (classFile == NKCommon.TypeClassFile.document.rawValue),
  269. NCCapabilities.shared.getCapabilities(account: account).capabilityRichDocumentsEnabled,
  270. NextcloudKit.shared.isNetworkReachable() else { return false }
  271. if NCUtility().isTypeFileRichDocument(self) {
  272. return true
  273. }
  274. return false
  275. }
  276. var isAvailableDirectEditingEditorView: Bool {
  277. guard (classFile == NKCommon.TypeClassFile.document.rawValue) && NextcloudKit.shared.isNetworkReachable() else { return false }
  278. let editors = NCUtility().editorsDirectEditing(account: account, contentType: contentType)
  279. if editors.contains(NCGlobal.shared.editorText) || editors.contains(NCGlobal.shared.editorOnlyoffice) {
  280. return true
  281. }
  282. return false
  283. }
  284. var isPDF: Bool {
  285. return (contentType == "application/pdf" || contentType == "com.adobe.pdf")
  286. }
  287. /// Returns false if the user is lokced out of the file. I.e. The file is locked but by somone else
  288. func canUnlock(as user: String) -> Bool {
  289. return !lock || (lockOwner == user && lockOwnerType == 0)
  290. }
  291. // Return if is sharable
  292. func isSharable() -> Bool {
  293. if !NCCapabilities.shared.getCapabilities(account: account).capabilityFileSharingApiEnabled || (NCCapabilities.shared.getCapabilities(account: account).capabilityE2EEEnabled && isDirectoryE2EE) {
  294. return false
  295. }
  296. return true
  297. }
  298. }
  299. extension NCManageDatabase {
  300. func convertFileToMetadata(_ file: NKFile, isDirectoryE2EE: Bool) -> tableMetadata {
  301. let metadata = tableMetadata()
  302. metadata.account = file.account
  303. metadata.checksums = file.checksums
  304. metadata.commentsUnread = file.commentsUnread
  305. metadata.contentType = file.contentType
  306. if let date = file.creationDate {
  307. metadata.creationDate = date as NSDate
  308. } else {
  309. metadata.creationDate = file.date as NSDate
  310. }
  311. metadata.dataFingerprint = file.dataFingerprint
  312. metadata.date = file.date as NSDate
  313. if let datePhotosOriginal = file.datePhotosOriginal {
  314. metadata.datePhotosOriginal = datePhotosOriginal as NSDate
  315. } else {
  316. metadata.datePhotosOriginal = metadata.date
  317. }
  318. metadata.directory = file.directory
  319. metadata.downloadURL = file.downloadURL
  320. metadata.e2eEncrypted = file.e2eEncrypted
  321. metadata.etag = file.etag
  322. for dict in file.exifPhotos {
  323. for (key, value) in dict {
  324. let keyValue = NCKeyValue()
  325. keyValue.key = key
  326. keyValue.value = value
  327. metadata.exifPhotos.append(keyValue)
  328. }
  329. }
  330. metadata.favorite = file.favorite
  331. metadata.fileId = file.fileId
  332. metadata.fileName = file.fileName
  333. metadata.fileNameView = file.fileName
  334. metadata.hasPreview = file.hasPreview
  335. metadata.hidden = file.hidden
  336. metadata.iconName = file.iconName
  337. metadata.mountType = file.mountType
  338. metadata.name = file.name
  339. metadata.note = file.note
  340. metadata.ocId = file.ocId
  341. metadata.ocIdTransfer = file.ocId
  342. metadata.ownerId = file.ownerId
  343. metadata.ownerDisplayName = file.ownerDisplayName
  344. metadata.lock = file.lock
  345. metadata.lockOwner = file.lockOwner
  346. metadata.lockOwnerEditor = file.lockOwnerEditor
  347. metadata.lockOwnerType = file.lockOwnerType
  348. metadata.lockOwnerDisplayName = file.lockOwnerDisplayName
  349. metadata.lockTime = file.lockTime
  350. metadata.lockTimeOut = file.lockTimeOut
  351. metadata.path = file.path
  352. metadata.permissions = file.permissions
  353. metadata.placePhotos = file.placePhotos
  354. metadata.quotaUsedBytes = file.quotaUsedBytes
  355. metadata.quotaAvailableBytes = file.quotaAvailableBytes
  356. metadata.richWorkspace = file.richWorkspace
  357. metadata.resourceType = file.resourceType
  358. metadata.serverUrl = file.serverUrl
  359. metadata.serveUrlFileName = file.serverUrl + "/" + file.fileName
  360. metadata.sharePermissionsCollaborationServices = file.sharePermissionsCollaborationServices
  361. for element in file.sharePermissionsCloudMesh {
  362. metadata.sharePermissionsCloudMesh.append(element)
  363. }
  364. for element in file.shareType {
  365. metadata.shareType.append(element)
  366. }
  367. for element in file.tags {
  368. metadata.tags.append(element)
  369. }
  370. metadata.size = file.size
  371. metadata.classFile = file.classFile
  372. // iOS 12.0,* don't detect UTI text/markdown, text/x-markdown
  373. if (metadata.contentType == "text/markdown" || metadata.contentType == "text/x-markdown") && metadata.classFile == NKCommon.TypeClassFile.unknow.rawValue {
  374. metadata.classFile = NKCommon.TypeClassFile.document.rawValue
  375. }
  376. if let date = file.uploadDate {
  377. metadata.uploadDate = date as NSDate
  378. } else {
  379. metadata.uploadDate = file.date as NSDate
  380. }
  381. metadata.urlBase = file.urlBase
  382. metadata.user = file.user
  383. metadata.userId = file.userId
  384. metadata.latitude = file.latitude
  385. metadata.longitude = file.longitude
  386. metadata.altitude = file.altitude
  387. metadata.height = Int(file.height)
  388. metadata.width = Int(file.width)
  389. metadata.livePhotoFile = file.livePhotoFile
  390. metadata.isFlaggedAsLivePhotoByServer = file.isFlaggedAsLivePhotoByServer
  391. // E2EE find the fileName for fileNameView
  392. if isDirectoryE2EE || file.e2eEncrypted {
  393. if let tableE2eEncryption = getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", file.account, file.serverUrl, file.fileName)) {
  394. metadata.fileNameView = tableE2eEncryption.fileName
  395. let results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: metadata.fileNameView, mimeType: file.contentType, directory: file.directory, account: file.account)
  396. metadata.contentType = results.mimeType
  397. metadata.iconName = results.iconName
  398. metadata.classFile = results.classFile
  399. }
  400. }
  401. return metadata
  402. }
  403. func convertFilesToMetadatas(_ files: [NKFile], useFirstAsMetadataFolder: Bool, completion: @escaping (_ metadataFolder: tableMetadata, _ metadatas: [tableMetadata]) -> Void) {
  404. var counter: Int = 0
  405. var isDirectoryE2EE: Bool = false
  406. let listServerUrl = ThreadSafeDictionary<String, Bool>()
  407. var metadataFolder = tableMetadata()
  408. var metadatas: [tableMetadata] = []
  409. for file in files {
  410. if let key = listServerUrl[file.serverUrl] {
  411. isDirectoryE2EE = key
  412. } else {
  413. isDirectoryE2EE = NCUtilityFileSystem().isDirectoryE2EE(file: file)
  414. listServerUrl[file.serverUrl] = isDirectoryE2EE
  415. }
  416. let metadata = convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE)
  417. if counter == 0 && useFirstAsMetadataFolder {
  418. metadataFolder = tableMetadata(value: metadata)
  419. } else {
  420. metadatas.append(metadata)
  421. }
  422. counter += 1
  423. }
  424. completion(metadataFolder, metadatas)
  425. }
  426. func getMetadataDirectoryFrom(files: [NKFile]) -> tableMetadata? {
  427. guard let file = files.first else { return nil }
  428. let isDirectoryE2EE = NCUtilityFileSystem().isDirectoryE2EE(file: file)
  429. let metadata = convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE)
  430. return metadata
  431. }
  432. func convertFilesToMetadatas(_ files: [NKFile], useFirstAsMetadataFolder: Bool) async -> (metadataFolder: tableMetadata, metadatas: [tableMetadata]) {
  433. await withUnsafeContinuation({ continuation in
  434. convertFilesToMetadatas(files, useFirstAsMetadataFolder: useFirstAsMetadataFolder) { metadataFolder, metadatas in
  435. continuation.resume(returning: (metadataFolder, metadatas))
  436. }
  437. })
  438. }
  439. func createMetadata(fileName: String, fileNameView: String, ocId: String, serverUrl: String, url: String, contentType: String, isUrl: Bool = false, name: String = NCGlobal.shared.appName, subline: String? = nil, iconName: String? = nil, iconUrl: String? = nil, directory: Bool = false, session: NCSession.Session, sceneIdentifier: String?) -> tableMetadata {
  440. let metadata = tableMetadata()
  441. if isUrl {
  442. metadata.contentType = "text/uri-list"
  443. if let iconName = iconName {
  444. metadata.iconName = iconName
  445. } else {
  446. metadata.iconName = NKCommon.TypeClassFile.url.rawValue
  447. }
  448. metadata.classFile = NKCommon.TypeClassFile.url.rawValue
  449. } else {
  450. let (mimeType, classFile, iconName, _, _, _) = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: fileName, mimeType: contentType, directory: directory, account: session.account)
  451. metadata.contentType = mimeType
  452. metadata.iconName = iconName
  453. metadata.classFile = classFile
  454. // iOS 12.0,* don't detect UTI text/markdown, text/x-markdown
  455. if classFile == NKCommon.TypeClassFile.unknow.rawValue && (mimeType == "text/x-markdown" || mimeType == "text/markdown") {
  456. metadata.iconName = NKCommon.TypeIconFile.txt.rawValue
  457. metadata.classFile = NKCommon.TypeClassFile.document.rawValue
  458. }
  459. }
  460. if let iconUrl = iconUrl {
  461. metadata.iconUrl = iconUrl
  462. }
  463. let fileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
  464. metadata.account = session.account
  465. metadata.creationDate = Date() as NSDate
  466. metadata.date = Date() as NSDate
  467. metadata.directory = directory
  468. metadata.hasPreview = true
  469. metadata.etag = ocId
  470. metadata.fileName = fileName
  471. metadata.fileNameView = fileName
  472. metadata.name = name
  473. metadata.ocId = ocId
  474. metadata.ocIdTransfer = ocId
  475. metadata.permissions = "RGDNVW"
  476. metadata.serverUrl = serverUrl
  477. metadata.serveUrlFileName = serverUrl + "/" + fileName
  478. metadata.subline = subline
  479. metadata.uploadDate = Date() as NSDate
  480. metadata.url = url
  481. metadata.urlBase = session.urlBase
  482. metadata.user = session.user
  483. metadata.userId = session.userId
  484. metadata.sceneIdentifier = sceneIdentifier
  485. if !metadata.urlBase.isEmpty, metadata.serverUrl.hasPrefix(metadata.urlBase) {
  486. metadata.path = String(metadata.serverUrl.dropFirst(metadata.urlBase.count)) + "/"
  487. }
  488. return metadata
  489. }
  490. func isMetadataShareOrMounted(metadata: tableMetadata, metadataFolder: tableMetadata?) -> Bool {
  491. let permissions = NCPermissions()
  492. var isShare = false
  493. var isMounted = false
  494. if metadataFolder != nil {
  495. isShare = metadata.permissions.contains(permissions.permissionShared) && !metadataFolder!.permissions.contains(permissions.permissionShared)
  496. isMounted = metadata.permissions.contains(permissions.permissionMounted) && !metadataFolder!.permissions.contains(permissions.permissionMounted)
  497. } else if let directory = getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", metadata.account, metadata.serverUrl)) {
  498. isShare = metadata.permissions.contains(permissions.permissionShared) && !directory.permissions.contains(permissions.permissionShared)
  499. isMounted = metadata.permissions.contains(permissions.permissionMounted) && !directory.permissions.contains(permissions.permissionMounted)
  500. }
  501. if isShare || isMounted {
  502. return true
  503. } else {
  504. return false
  505. }
  506. }
  507. // MARK: - Set
  508. func createMetadata(_ metadata: tableMetadata) -> tableMetadata? {
  509. do {
  510. let realm = try Realm()
  511. var managedMetadata: tableMetadata?
  512. try realm.write {
  513. managedMetadata = realm.create(tableMetadata.self, value: metadata, update: .all)
  514. }
  515. if let managedMetadata {
  516. return tableMetadata(value: managedMetadata)
  517. }
  518. } catch let error {
  519. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  520. }
  521. return nil
  522. }
  523. func addMetadata(_ metadata: tableMetadata) {
  524. let metadata = tableMetadata(value: metadata)
  525. do {
  526. let realm = try Realm()
  527. try realm.write {
  528. realm.add(metadata, update: .all)
  529. }
  530. } catch let error {
  531. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  532. }
  533. }
  534. func addMetadatas(_ metadatas: [tableMetadata]) {
  535. do {
  536. let realm = try Realm()
  537. try realm.write {
  538. realm.add(metadatas, update: .all)
  539. }
  540. } catch let error {
  541. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  542. }
  543. }
  544. func deleteMetadata(predicate: NSPredicate) {
  545. do {
  546. let realm = try Realm()
  547. try realm.write {
  548. let results = realm.objects(tableMetadata.self).filter(predicate)
  549. realm.delete(results)
  550. }
  551. } catch let error {
  552. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  553. }
  554. }
  555. func deleteMetadataOcId(_ ocId: String?) {
  556. guard let ocId else { return }
  557. do {
  558. let realm = try Realm()
  559. try realm.write {
  560. let results = realm.objects(tableMetadata.self).filter("ocId == %@", ocId)
  561. realm.delete(results)
  562. }
  563. } catch let error as NSError {
  564. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  565. }
  566. }
  567. func deleteMetadatas(_ metadatas: [tableMetadata]) {
  568. do {
  569. let realm = try Realm()
  570. try realm.write {
  571. realm.delete(metadatas)
  572. }
  573. } catch let error {
  574. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  575. }
  576. }
  577. func renameMetadata(fileNameNew: String, ocId: String, status: Int = NCGlobal.shared.metadataStatusNormal) {
  578. do {
  579. let realm = try Realm()
  580. try realm.write {
  581. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  582. let fileNameView = result.fileNameView
  583. let fileIdMOV = result.livePhotoFile
  584. let directoryServerUrl = self.utilityFileSystem.stringAppendServerUrl(result.serverUrl, addFileName: fileNameView)
  585. let resultsType = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: fileNameNew, mimeType: "", directory: result.directory, account: result.account)
  586. result.fileName = fileNameNew
  587. result.fileNameView = fileNameNew
  588. result.iconName = resultsType.iconName
  589. result.contentType = resultsType.mimeType
  590. result.classFile = resultsType.classFile
  591. result.status = status
  592. if status == NCGlobal.shared.metadataStatusNormal {
  593. result.sessionDate = nil
  594. } else {
  595. result.sessionDate = Date()
  596. }
  597. if result.directory,
  598. let resultDirectory = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", result.account, directoryServerUrl).first {
  599. let serverUrlTo = self.utilityFileSystem.stringAppendServerUrl(result.serverUrl, addFileName: fileNameNew)
  600. resultDirectory.serverUrl = serverUrlTo
  601. } else {
  602. let atPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId) + "/" + fileNameView
  603. let toPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId) + "/" + fileNameNew
  604. self.utilityFileSystem.moveFile(atPath: atPath, toPath: toPath)
  605. }
  606. if result.isLivePhoto,
  607. let resultMOV = realm.objects(tableMetadata.self).filter("fileId == %@ AND account == %@", fileIdMOV, result.account).first {
  608. let fileNameView = resultMOV.fileNameView
  609. let fileName = (fileNameNew as NSString).deletingPathExtension
  610. let ext = (resultMOV.fileName as NSString).pathExtension
  611. resultMOV.fileName = fileName + "." + ext
  612. resultMOV.fileNameView = fileName + "." + ext
  613. let atPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(resultMOV.ocId) + "/" + fileNameView
  614. let toPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(resultMOV.ocId) + "/" + fileName + "." + ext
  615. self.utilityFileSystem.moveFile(atPath: atPath, toPath: toPath)
  616. }
  617. }
  618. }
  619. } catch let error {
  620. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  621. }
  622. }
  623. func restoreMetadataFileName(ocId: String) {
  624. do {
  625. let realm = try Realm()
  626. try realm.write {
  627. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first,
  628. let encodedURLString = result.serveUrlFileName.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
  629. let url = URL(string: encodedURLString) {
  630. let fileIdMOV = result.livePhotoFile
  631. let directoryServerUrl = self.utilityFileSystem.stringAppendServerUrl(result.serverUrl, addFileName: result.fileNameView)
  632. let lastPathComponent = url.lastPathComponent
  633. let fileName = lastPathComponent.removingPercentEncoding ?? lastPathComponent
  634. let fileNameView = result.fileNameView
  635. result.fileName = fileName
  636. result.fileNameView = fileName
  637. result.status = NCGlobal.shared.metadataStatusNormal
  638. result.sessionDate = nil
  639. if result.directory,
  640. let resultDirectory = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", result.account, directoryServerUrl).first {
  641. let serverUrlTo = self.utilityFileSystem.stringAppendServerUrl(result.serverUrl, addFileName: fileName)
  642. resultDirectory.serverUrl = serverUrlTo
  643. } else {
  644. let atPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId) + "/" + fileNameView
  645. let toPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(result.ocId) + "/" + fileName
  646. self.utilityFileSystem.moveFile(atPath: atPath, toPath: toPath)
  647. }
  648. if result.isLivePhoto,
  649. let resultMOV = realm.objects(tableMetadata.self).filter("fileId == %@ AND account == %@", fileIdMOV, result.account).first {
  650. let fileNameView = resultMOV.fileNameView
  651. let fileName = (fileName as NSString).deletingPathExtension
  652. let ext = (resultMOV.fileName as NSString).pathExtension
  653. resultMOV.fileName = fileName + "." + ext
  654. resultMOV.fileNameView = fileName + "." + ext
  655. let atPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(resultMOV.ocId) + "/" + fileNameView
  656. let toPath = self.utilityFileSystem.getDirectoryProviderStorageOcId(resultMOV.ocId) + "/" + fileName + "." + ext
  657. self.utilityFileSystem.moveFile(atPath: atPath, toPath: toPath)
  658. }
  659. }
  660. }
  661. } catch let error {
  662. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  663. }
  664. }
  665. func setMetadataServeUrlFileNameStatusNormal(ocId: String) {
  666. do {
  667. let realm = try Realm()
  668. try realm.write {
  669. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  670. result.serveUrlFileName = self.utilityFileSystem.stringAppendServerUrl(result.serverUrl, addFileName: result.fileName)
  671. result.status = NCGlobal.shared.metadataStatusNormal
  672. result.sessionDate = nil
  673. }
  674. }
  675. } catch let error {
  676. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  677. }
  678. }
  679. func setMetadataEtagResource(ocId: String, etagResource: String?) {
  680. guard let etagResource else { return }
  681. do {
  682. let realm = try Realm()
  683. try realm.write {
  684. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  685. result?.etagResource = etagResource
  686. }
  687. } catch let error {
  688. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  689. }
  690. }
  691. func setMetadataLivePhotoByServer(account: String, ocId: String, livePhotoFile: String) {
  692. do {
  693. let realm = try Realm()
  694. try realm.write {
  695. if let result = realm.objects(tableMetadata.self).filter("account == %@ AND ocId == %@", account, ocId).first {
  696. result.isFlaggedAsLivePhotoByServer = true
  697. result.livePhotoFile = livePhotoFile
  698. }
  699. }
  700. } catch let error {
  701. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  702. }
  703. }
  704. func updateMetadatasFavorite(account: String, metadatas: [tableMetadata]) {
  705. do {
  706. let realm = try Realm()
  707. try realm.write {
  708. let results = realm.objects(tableMetadata.self).filter("account == %@ AND favorite == true", account)
  709. for result in results {
  710. result.favorite = false
  711. }
  712. for metadata in metadatas {
  713. if let result = realm.objects(tableMetadata.self).filter("account == %@ AND ocId == %@", account, metadata.ocId).first {
  714. result.favorite = true
  715. } else {
  716. realm.add(metadata, update: .modified)
  717. }
  718. }
  719. }
  720. } catch let error {
  721. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  722. }
  723. }
  724. func updateMetadatasFiles(_ metadatas: [tableMetadata], serverUrl: String, account: String) {
  725. do {
  726. let realm = try Realm()
  727. try realm.write {
  728. let results = realm.objects(tableMetadata.self).filter(NSPredicate(format: "account == %@ AND serverUrl == %@ AND status == %d", account, serverUrl, NCGlobal.shared.metadataStatusNormal))
  729. realm.delete(results)
  730. for metadata in metadatas {
  731. if realm.objects(tableMetadata.self).filter(NSPredicate(format: "ocId == %@ AND status != %d", metadata.ocId, NCGlobal.shared.metadataStatusNormal)).first != nil {
  732. continue
  733. }
  734. realm.add(tableMetadata(value: metadata), update: .all)
  735. }
  736. }
  737. } catch let error {
  738. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  739. }
  740. }
  741. func setMetadataEncrypted(ocId: String, encrypted: Bool) {
  742. do {
  743. let realm = try Realm()
  744. try realm.write {
  745. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  746. result?.e2eEncrypted = encrypted
  747. }
  748. } catch let error {
  749. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  750. }
  751. }
  752. func setMetadataFileNameView(serverUrl: String, fileName: String, newFileNameView: String, account: String) {
  753. do {
  754. let realm = try Realm()
  755. try realm.write {
  756. let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first
  757. result?.fileNameView = newFileNameView
  758. }
  759. } catch let error {
  760. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  761. }
  762. }
  763. func moveMetadata(ocId: String, serverUrlTo: String) {
  764. do {
  765. let realm = try Realm()
  766. try realm.write {
  767. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  768. result.serverUrl = serverUrlTo
  769. }
  770. }
  771. } catch let error {
  772. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  773. }
  774. }
  775. func clearAssetLocalIdentifiers(_ assetLocalIdentifiers: [String]) {
  776. do {
  777. let realm = try Realm()
  778. try realm.write {
  779. let results = realm.objects(tableMetadata.self).filter("assetLocalIdentifier IN %@", assetLocalIdentifiers)
  780. for result in results {
  781. result.assetLocalIdentifier = ""
  782. }
  783. }
  784. } catch let error {
  785. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  786. }
  787. }
  788. func setMetadataFavorite(ocId: String, favorite: Bool?, saveOldFavorite: String?, status: Int) {
  789. do {
  790. let realm = try Realm()
  791. try realm.write {
  792. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  793. if let favorite {
  794. result?.favorite = favorite
  795. }
  796. result?.storeFlag = saveOldFavorite
  797. result?.status = status
  798. if status == NCGlobal.shared.metadataStatusNormal {
  799. result?.sessionDate = nil
  800. } else {
  801. result?.sessionDate = Date()
  802. }
  803. }
  804. } catch let error {
  805. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  806. }
  807. }
  808. func setMetadataCopyMove(ocId: String, serverUrlTo: String, overwrite: String?, status: Int) {
  809. do {
  810. let realm = try Realm()
  811. try realm.write {
  812. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  813. result?.serverUrlTo = serverUrlTo
  814. result?.storeFlag = overwrite
  815. result?.status = status
  816. if status == NCGlobal.shared.metadataStatusNormal {
  817. result?.sessionDate = nil
  818. } else {
  819. result?.sessionDate = Date()
  820. }
  821. }
  822. } catch let error {
  823. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  824. }
  825. }
  826. // MARK: - GetMetadata
  827. func getMetadata(predicate: NSPredicate) -> tableMetadata? {
  828. do {
  829. let realm = try Realm()
  830. guard let result = realm.objects(tableMetadata.self).filter(predicate).first else { return nil }
  831. return tableMetadata(value: result)
  832. } catch let error as NSError {
  833. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  834. }
  835. return nil
  836. }
  837. func getMetadatas(predicate: NSPredicate) -> [tableMetadata] {
  838. do {
  839. let realm = try Realm()
  840. let results = realm.objects(tableMetadata.self).filter(predicate)
  841. return Array(results.map { tableMetadata(value: $0) })
  842. } catch let error as NSError {
  843. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  844. }
  845. return []
  846. }
  847. func getMetadatas(predicate: NSPredicate, sortedByKeyPath: String, ascending: Bool = false) -> [tableMetadata]? {
  848. do {
  849. let realm = try Realm()
  850. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sortedByKeyPath, ascending: ascending)
  851. return Array(results.map { tableMetadata(value: $0) })
  852. } catch let error as NSError {
  853. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  854. }
  855. return nil
  856. }
  857. func getMetadatas(predicate: NSPredicate, numItems: Int, sorted: String, ascending: Bool) -> [tableMetadata] {
  858. var counter: Int = 0
  859. var metadatas: [tableMetadata] = []
  860. do {
  861. let realm = try Realm()
  862. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  863. for result in results where counter < numItems {
  864. metadatas.append(tableMetadata(value: result))
  865. counter += 1
  866. }
  867. } catch let error as NSError {
  868. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  869. }
  870. return metadatas
  871. }
  872. func getMetadataFromOcId(_ ocId: String?) -> tableMetadata? {
  873. guard let ocId else { return nil }
  874. do {
  875. let realm = try Realm()
  876. guard let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first else { return nil }
  877. return tableMetadata(value: result)
  878. } catch let error as NSError {
  879. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  880. }
  881. return nil
  882. }
  883. func getMetadataFromOcIdAndocIdTransfer(_ ocId: String?) -> tableMetadata? {
  884. guard let ocId else { return nil }
  885. do {
  886. let realm = try Realm()
  887. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  888. return tableMetadata(value: result)
  889. }
  890. if let result = realm.objects(tableMetadata.self).filter("ocIdTransfer == %@", ocId).first {
  891. return tableMetadata(value: result)
  892. }
  893. } catch let error as NSError {
  894. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  895. }
  896. return nil
  897. }
  898. func getMetadataFolder(session: NCSession.Session, serverUrl: String) -> tableMetadata? {
  899. var serverUrl = serverUrl
  900. var fileName = ""
  901. let serverUrlHome = utilityFileSystem.getHomeServer(session: session)
  902. if serverUrlHome == serverUrl {
  903. fileName = "."
  904. serverUrl = ".."
  905. } else {
  906. fileName = (serverUrl as NSString).lastPathComponent
  907. if let path = utilityFileSystem.deleteLastPath(serverUrlPath: serverUrl) {
  908. serverUrl = path
  909. }
  910. }
  911. do {
  912. let realm = try Realm()
  913. guard let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", session.account, serverUrl, fileName).first else { return nil }
  914. return tableMetadata(value: result)
  915. } catch let error as NSError {
  916. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  917. }
  918. return nil
  919. }
  920. func getMetadataLivePhoto(metadata: tableMetadata) -> tableMetadata? {
  921. guard metadata.isLivePhoto else { return nil }
  922. do {
  923. let realm = try Realm()
  924. guard let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileId == %@",
  925. metadata.account,
  926. metadata.serverUrl,
  927. metadata.livePhotoFile)).first else { return nil }
  928. return tableMetadata(value: result)
  929. } catch let error as NSError {
  930. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  931. }
  932. return nil
  933. }
  934. func getMetadataConflict(account: String, serverUrl: String, fileNameView: String) -> tableMetadata? {
  935. let fileNameExtension = (fileNameView as NSString).pathExtension.lowercased()
  936. let fileNameNoExtension = (fileNameView as NSString).deletingPathExtension
  937. var fileNameConflict = fileNameView
  938. if fileNameExtension == "heic", NCKeychain().formatCompatibility {
  939. fileNameConflict = fileNameNoExtension + ".jpg"
  940. }
  941. return getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@",
  942. account,
  943. serverUrl,
  944. fileNameConflict))
  945. }
  946. // MARK: - GetResult(s)Metadata
  947. func getResultsMetadatasPredicate(_ predicate: NSPredicate, layoutForView: NCDBLayoutForView?) -> [tableMetadata] {
  948. do {
  949. let realm = try Realm()
  950. var results = realm.objects(tableMetadata.self).filter(predicate).freeze()
  951. let layout: NCDBLayoutForView = layoutForView ?? NCDBLayoutForView()
  952. if layout.sort == "fileName" {
  953. let sortedResults = results.sorted {
  954. let ordered = layout.ascending ? ComparisonResult.orderedAscending : ComparisonResult.orderedDescending
  955. // 1. favorite order
  956. if $0.favorite == $1.favorite {
  957. // 2. directory order TOP
  958. if layout.directoryOnTop {
  959. if $0.directory == $1.directory {
  960. // 3. natural fileName
  961. return $0.fileNameView.localizedStandardCompare($1.fileNameView) == ordered
  962. } else {
  963. return $0.directory && !$1.directory
  964. }
  965. } else {
  966. return $0.fileNameView.localizedStandardCompare($1.fileNameView) == ordered
  967. }
  968. } else {
  969. return $0.favorite && !$1.favorite
  970. }
  971. }
  972. return sortedResults
  973. } else {
  974. if layout.directoryOnTop {
  975. results = results.sorted(byKeyPath: layout.sort, ascending: layout.ascending).sorted(byKeyPath: "favorite", ascending: false).sorted(byKeyPath: "directory", ascending: false)
  976. } else {
  977. results = results.sorted(byKeyPath: layout.sort, ascending: layout.ascending).sorted(byKeyPath: "favorite", ascending: false)
  978. }
  979. }
  980. return Array(results)
  981. } catch let error as NSError {
  982. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  983. }
  984. return []
  985. }
  986. func getResultsMetadatas(predicate: NSPredicate, sortedByKeyPath: String, ascending: Bool, arraySlice: Int) -> [tableMetadata] {
  987. do {
  988. let realm = try Realm()
  989. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sortedByKeyPath, ascending: ascending).prefix(arraySlice)
  990. return Array(results)
  991. } catch let error as NSError {
  992. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  993. }
  994. return []
  995. }
  996. func getResultMetadata(predicate: NSPredicate) -> tableMetadata? {
  997. do {
  998. let realm = try Realm()
  999. return realm.objects(tableMetadata.self).filter(predicate).first
  1000. } catch let error as NSError {
  1001. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  1002. }
  1003. return nil
  1004. }
  1005. func getResultMetadataFromFileName(_ fileName: String, serverUrl: String, sessionTaskIdentifier: Int) -> tableMetadata? {
  1006. do {
  1007. let realm = try Realm()
  1008. return realm.objects(tableMetadata.self).filter("fileName == %@ AND serverUrl == %@ AND sessionTaskIdentifier == %d", fileName, serverUrl, sessionTaskIdentifier).first
  1009. } catch let error as NSError {
  1010. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  1011. }
  1012. return nil
  1013. }
  1014. func getResultsMetadatasFromGroupfolders(session: NCSession.Session) -> Results<tableMetadata>? {
  1015. var ocId: [String] = []
  1016. let homeServerUrl = utilityFileSystem.getHomeServer(session: session)
  1017. do {
  1018. let realm = try Realm()
  1019. let groupfolders = realm.objects(TableGroupfolders.self).filter("account == %@", session.account).sorted(byKeyPath: "mountPoint", ascending: true)
  1020. for groupfolder in groupfolders {
  1021. let mountPoint = groupfolder.mountPoint.hasPrefix("/") ? groupfolder.mountPoint : "/" + groupfolder.mountPoint
  1022. let serverUrlFileName = homeServerUrl + mountPoint
  1023. if let directory = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", session.account, serverUrlFileName).first,
  1024. let result = realm.objects(tableMetadata.self).filter("ocId == %@", directory.ocId).first {
  1025. ocId.append(result.ocId)
  1026. }
  1027. }
  1028. return realm.objects(tableMetadata.self).filter("ocId IN %@", ocId)
  1029. } catch let error as NSError {
  1030. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  1031. }
  1032. return nil
  1033. }
  1034. func getResultsImageCacheMetadatas(predicate: NSPredicate) -> Results<tableMetadata>? {
  1035. do {
  1036. let realm = try Realm()
  1037. return realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  1038. } catch let error as NSError {
  1039. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  1040. }
  1041. return nil
  1042. }
  1043. func getTableMetadatasDirectoryFavoriteIdentifierRank(account: String) -> [String: NSNumber] {
  1044. var listIdentifierRank: [String: NSNumber] = [:]
  1045. var counter = 10 as Int64
  1046. do {
  1047. let realm = try Realm()
  1048. let results = realm.objects(tableMetadata.self).filter("account == %@ AND directory == true AND favorite == true", account).sorted(byKeyPath: "fileNameView", ascending: true)
  1049. for result in results {
  1050. counter += 1
  1051. listIdentifierRank[result.ocId] = NSNumber(value: Int64(counter))
  1052. }
  1053. } catch let error as NSError {
  1054. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  1055. }
  1056. return listIdentifierRank
  1057. }
  1058. func clearMetadatasUpload(account: String) {
  1059. do {
  1060. let realm = try Realm()
  1061. try realm.write {
  1062. let results = realm.objects(tableMetadata.self).filter("account == %@ AND (status == %d OR status == %d)", account, NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusUploadError)
  1063. realm.delete(results)
  1064. }
  1065. } catch let error {
  1066. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not write to database: \(error)")
  1067. }
  1068. }
  1069. func getAssetLocalIdentifiersUploaded() -> [String]? {
  1070. var assetLocalIdentifiers: [String] = []
  1071. do {
  1072. let realm = try Realm()
  1073. let results = realm.objects(tableMetadata.self).filter("assetLocalIdentifier != ''")
  1074. for result in results {
  1075. assetLocalIdentifiers.append(result.assetLocalIdentifier)
  1076. }
  1077. return assetLocalIdentifiers
  1078. } catch let error as NSError {
  1079. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  1080. }
  1081. return nil
  1082. }
  1083. func getMetadataFromDirectory(account: String, serverUrl: String) -> Bool {
  1084. do {
  1085. let realm = try Realm()
  1086. guard let directory = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first,
  1087. realm.objects(tableMetadata.self).filter("ocId == %@", directory.ocId).first != nil else { return false }
  1088. return true
  1089. } catch let error as NSError {
  1090. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  1091. }
  1092. return false
  1093. }
  1094. func getResultMetadataFromFileId(_ fileId: String?) -> tableMetadata? {
  1095. guard let fileId else { return nil }
  1096. do {
  1097. let realm = try Realm()
  1098. return realm.objects(tableMetadata.self).filter("fileId == %@", fileId).first
  1099. } catch let error as NSError {
  1100. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  1101. }
  1102. return nil
  1103. }
  1104. func getResultMetadataFromOcId(_ ocId: String?) -> tableMetadata? {
  1105. guard let ocId else { return nil }
  1106. do {
  1107. let realm = try Realm()
  1108. return realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  1109. } catch let error as NSError {
  1110. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  1111. }
  1112. return nil
  1113. }
  1114. func getResultsMetadatas(predicate: NSPredicate, sortedByKeyPath: String? = nil, ascending: Bool = false, freeze: Bool = false) -> Results<tableMetadata>? {
  1115. do {
  1116. let realm = try Realm()
  1117. realm.refresh()
  1118. if let sortedByKeyPath {
  1119. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sortedByKeyPath, ascending: ascending)
  1120. if freeze {
  1121. return results.freeze()
  1122. }
  1123. return results
  1124. } else {
  1125. let results = realm.objects(tableMetadata.self).filter(predicate)
  1126. if freeze {
  1127. return results.freeze()
  1128. }
  1129. return results
  1130. }
  1131. } catch let error as NSError {
  1132. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] Could not access database: \(error)")
  1133. }
  1134. return nil
  1135. }
  1136. func getCalculateCumulativeHash(for metadatas: [tableMetadata], account: String, serverUrl: String) -> String {
  1137. let concatenatedEtags = metadatas.map { $0.etag }.joined(separator: "-")
  1138. return sha256Hash(concatenatedEtags)
  1139. }
  1140. }