NCManageDatabase.swift 59 KB

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