NCManageDatabase.swift 56 KB

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