NCManageDatabase.swift 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660
  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. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import RealmSwift
  24. import NCCommunication
  25. import SwiftyJSON
  26. class NCManageDatabase: NSObject {
  27. @objc static let sharedInstance: NCManageDatabase = {
  28. let instance = NCManageDatabase()
  29. return instance
  30. }()
  31. override init() {
  32. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups)
  33. let databaseFilePath = dirGroup?.appendingPathComponent("\(k_appDatabaseNextcloud)/\(k_databaseDefault)")
  34. let bundleUrl: URL = Bundle.main.bundleURL
  35. let bundlePathExtension: String = bundleUrl.pathExtension
  36. let isAppex: Bool = bundlePathExtension == "appex"
  37. if isAppex {
  38. // App Extension config
  39. let config = Realm.Configuration(
  40. fileURL: dirGroup?.appendingPathComponent("\(k_appDatabaseNextcloud)/\(k_databaseDefault)"),
  41. schemaVersion: UInt64(k_databaseSchemaVersion),
  42. objectTypes: [tableMetadata.self, tableLocalFile.self, tableDirectory.self, tableTag.self, tableAccount.self, tableCapabilities.self, tableE2eEncryption.self]
  43. )
  44. Realm.Configuration.defaultConfiguration = config
  45. } else {
  46. // App config
  47. let configCompact = Realm.Configuration(
  48. fileURL: databaseFilePath,
  49. schemaVersion: UInt64(k_databaseSchemaVersion),
  50. migrationBlock: { migration, oldSchemaVersion in
  51. if oldSchemaVersion < 61 {
  52. migration.deleteData(forType: tableShare.className())
  53. }
  54. if oldSchemaVersion < 74 {
  55. migration.enumerateObjects(ofType: tableLocalFile.className()) { oldObject, newObject in
  56. newObject!["ocId"] = oldObject!["fileID"]
  57. }
  58. migration.enumerateObjects(ofType: tableTrash.className()) { oldObject, newObject in
  59. newObject!["fileId"] = oldObject!["fileID"]
  60. }
  61. migration.enumerateObjects(ofType: tableTag.className()) { oldObject, newObject in
  62. newObject!["ocId"] = oldObject!["fileID"]
  63. }
  64. migration.enumerateObjects(ofType: tableE2eEncryptionLock.className()) { oldObject, newObject in
  65. newObject!["ocId"] = oldObject!["fileID"]
  66. }
  67. }
  68. if oldSchemaVersion < 87 {
  69. migration.deleteData(forType: tableActivity.className())
  70. migration.deleteData(forType: tableActivityPreview.className())
  71. migration.deleteData(forType: tableActivitySubjectRich.className())
  72. migration.deleteData(forType: tableDirectEditingCreators.className())
  73. migration.deleteData(forType: tableDirectEditingEditors.className())
  74. migration.deleteData(forType: tableExternalSites.className())
  75. migration.deleteData(forType: tableGPS.className())
  76. migration.deleteData(forType: tableShare.className())
  77. migration.deleteData(forType: tableTag.className())
  78. migration.deleteData(forType: tableTrash.className())
  79. }
  80. if oldSchemaVersion < 120 {
  81. migration.deleteData(forType: tableE2eEncryptionLock.className())
  82. migration.deleteData(forType: tableCapabilities.className())
  83. migration.deleteData(forType: tableComments.className())
  84. migration.deleteData(forType: tableDirectory.className())
  85. }
  86. if oldSchemaVersion < 134 {
  87. migration.deleteData(forType: tableShare.className())
  88. migration.deleteData(forType: tableDirectEditingCreators.className())
  89. migration.deleteData(forType: tableDirectEditingEditors.className())
  90. migration.deleteData(forType: tableExternalSites.className())
  91. }
  92. if oldSchemaVersion < 139 {
  93. migration.deleteData(forType: tableMetadata.className())
  94. }
  95. if oldSchemaVersion < 141 {
  96. migration.enumerateObjects(ofType: tableAccount.className()) { oldObject, newObject in
  97. newObject!["urlBase"] = oldObject!["url"]
  98. }
  99. }
  100. }, shouldCompactOnLaunch: { totalBytes, usedBytes in
  101. // totalBytes refers to the size of the file on disk in bytes (data + free space)
  102. // usedBytes refers to the number of bytes used by data in the file
  103. // Compact if the file is over 100MB in size and less than 50% 'used'
  104. let oneHundredMB = 100 * 1024 * 1024
  105. return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
  106. }
  107. )
  108. do {
  109. _ = try Realm(configuration: configCompact)
  110. } catch {
  111. if let databaseFilePath = databaseFilePath {
  112. do {
  113. #if !EXTENSION
  114. NCContentPresenter.shared.messageNotification("_error_", description: "_database_corrupt_", delay: TimeInterval(k_dismissAfterSecondLong), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorInternalError), forced: true)
  115. #endif
  116. try FileManager.default.removeItem(at: databaseFilePath)
  117. } catch {}
  118. }
  119. }
  120. let config = Realm.Configuration(
  121. fileURL: dirGroup?.appendingPathComponent("\(k_appDatabaseNextcloud)/\(k_databaseDefault)"),
  122. schemaVersion: UInt64(k_databaseSchemaVersion)
  123. )
  124. Realm.Configuration.defaultConfiguration = config
  125. }
  126. // Verify Database, if corrupr remove it
  127. do {
  128. let _ = try Realm()
  129. } catch {
  130. if let databaseFilePath = databaseFilePath {
  131. do {
  132. #if !EXTENSION
  133. NCContentPresenter.shared.messageNotification("_error_", description: "_database_corrupt_", delay: TimeInterval(k_dismissAfterSecondLong), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorInternalError), forced: true)
  134. #endif
  135. try FileManager.default.removeItem(at: databaseFilePath)
  136. } catch {}
  137. }
  138. }
  139. // Open Real
  140. _ = try! Realm()
  141. }
  142. //MARK: -
  143. //MARK: Utility Database
  144. @objc func clearTable(_ table : Object.Type, account: String?) {
  145. let realm = try! Realm()
  146. do {
  147. try realm.safeWrite {
  148. var results : Results<Object>
  149. if let account = account {
  150. results = realm.objects(table).filter("account == %@", account)
  151. } else {
  152. results = realm.objects(table)
  153. }
  154. realm.delete(results)
  155. }
  156. } catch let error {
  157. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  158. }
  159. }
  160. @objc func clearDatabase(account: String?, removeAccount: Bool) {
  161. self.clearTable(tableActivity.self, account: account)
  162. self.clearTable(tableActivityPreview.self, account: account)
  163. self.clearTable(tableActivitySubjectRich.self, account: account)
  164. self.clearTable(tableCapabilities.self, account: account)
  165. self.clearTable(tableComments.self, account: account)
  166. self.clearTable(tableDirectEditingCreators.self, account: account)
  167. self.clearTable(tableDirectEditingEditors.self, account: account)
  168. self.clearTable(tableDirectory.self, account: account)
  169. self.clearTable(tableE2eEncryption.self, account: account)
  170. self.clearTable(tableE2eEncryptionLock.self, account: account)
  171. self.clearTable(tableExternalSites.self, account: account)
  172. self.clearTable(tableGPS.self, account: nil)
  173. self.clearTable(tableLocalFile.self, account: account)
  174. self.clearTable(tableMetadata.self, account: account)
  175. self.clearTable(tablePhotoLibrary.self, account: account)
  176. self.clearTable(tableShare.self, account: account)
  177. self.clearTable(tableTag.self, account: account)
  178. self.clearTable(tableTrash.self, account: account)
  179. if removeAccount {
  180. self.clearTable(tableAccount.self, account: account)
  181. }
  182. }
  183. @objc func removeDB() {
  184. let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
  185. let realmURLs = [
  186. realmURL,
  187. realmURL.appendingPathExtension("lock"),
  188. realmURL.appendingPathExtension("note"),
  189. realmURL.appendingPathExtension("management")
  190. ]
  191. for URL in realmURLs {
  192. do {
  193. try FileManager.default.removeItem(at: URL)
  194. } catch let error {
  195. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  196. }
  197. }
  198. }
  199. @objc func getThreadConfined(_ object: Object) -> Any {
  200. // id tradeReference = [[NCManageDatabase sharedInstance] getThreadConfined:metadata];
  201. return ThreadSafeReference(to: object)
  202. }
  203. @objc func putThreadConfined(_ tableRef: Any) -> Object? {
  204. //tableMetadata *metadataThread = (tableMetadata *)[[NCManageDatabase sharedInstance] putThreadConfined:tradeReference];
  205. let realm = try! Realm()
  206. return realm.resolve(tableRef as! ThreadSafeReference<Object>)
  207. }
  208. @objc func isTableInvalidated(_ object: Object) -> Bool {
  209. return object.isInvalidated
  210. }
  211. //MARK: -
  212. //MARK: Table Account
  213. @objc func copyObject(account: tableAccount) -> tableAccount {
  214. return tableAccount.init(value: account)
  215. }
  216. @objc func addAccount(_ account: String, urlBase: String, user: String, password: String) {
  217. let realm = try! Realm()
  218. do {
  219. try realm.safeWrite {
  220. let addObject = tableAccount()
  221. addObject.account = account
  222. // Brand
  223. if NCBrandOptions.sharedInstance.use_default_auto_upload {
  224. addObject.autoUpload = true
  225. addObject.autoUploadImage = true
  226. addObject.autoUploadVideo = true
  227. addObject.autoUploadWWAnVideo = true
  228. }
  229. CCUtility.setPassword(account, password: password)
  230. addObject.urlBase = urlBase
  231. addObject.user = user
  232. addObject.userID = user
  233. realm.add(addObject, update: .all)
  234. }
  235. } catch let error {
  236. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  237. }
  238. }
  239. @objc func updateAccount(_ account: tableAccount) {
  240. let realm = try! Realm()
  241. do {
  242. try realm.safeWrite {
  243. realm.add(account, update: .all)
  244. }
  245. } catch let error {
  246. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  247. }
  248. }
  249. @objc func deleteAccount(_ account: String) {
  250. let realm = try! Realm()
  251. do {
  252. try realm.safeWrite {
  253. let result = realm.objects(tableAccount.self).filter("account == %@", account)
  254. realm.delete(result)
  255. }
  256. } catch let error {
  257. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  258. }
  259. }
  260. @objc func getAccountActive() -> tableAccount? {
  261. let realm = try! Realm()
  262. guard let result = realm.objects(tableAccount.self).filter("active == true").first else {
  263. return nil
  264. }
  265. return tableAccount.init(value: result)
  266. }
  267. @objc func getAccounts() -> [String]? {
  268. let realm = try! Realm()
  269. let results = realm.objects(tableAccount.self).sorted(byKeyPath: "account", ascending: true)
  270. if results.count > 0 {
  271. return Array(results.map { $0.account })
  272. }
  273. return nil
  274. }
  275. @objc func getAccount(predicate: NSPredicate) -> tableAccount? {
  276. let realm = try! Realm()
  277. guard let result = realm.objects(tableAccount.self).filter(predicate).first else {
  278. return nil
  279. }
  280. return tableAccount.init(value: result)
  281. }
  282. @objc func getAllAccount() -> [tableAccount] {
  283. let realm = try! Realm()
  284. let results = realm.objects(tableAccount.self)
  285. return Array(results.map { tableAccount.init(value:$0) })
  286. }
  287. @objc func getAccountAutoUploadFileName() -> String {
  288. let realm = try! Realm()
  289. guard let result = realm.objects(tableAccount.self).filter("active == true").first else {
  290. return ""
  291. }
  292. if result.autoUploadFileName.count > 0 {
  293. return result.autoUploadFileName
  294. } else {
  295. return NCBrandOptions.sharedInstance.folderDefaultAutoUpload
  296. }
  297. }
  298. @objc func getAccountAutoUploadDirectory(urlBase : String, account: String) -> String {
  299. let realm = try! Realm()
  300. guard let result = realm.objects(tableAccount.self).filter("active == true").first else {
  301. return ""
  302. }
  303. if result.autoUploadDirectory.count > 0 {
  304. return result.autoUploadDirectory
  305. } else {
  306. return NCUtility.shared.getHomeServer(urlBase: urlBase, account: account)
  307. }
  308. }
  309. @objc func getAccountAutoUploadPath(urlBase : String, account: String) -> String {
  310. let cameraFileName = self.getAccountAutoUploadFileName()
  311. let cameraDirectory = self.getAccountAutoUploadDirectory(urlBase: urlBase, account: account)
  312. let folderPhotos = CCUtility.stringAppendServerUrl(cameraDirectory, addFileName: cameraFileName)!
  313. return folderPhotos
  314. }
  315. @objc func setAccountActive(_ account: String) -> tableAccount? {
  316. let realm = try! Realm()
  317. var accountReturn = tableAccount()
  318. do {
  319. try realm.safeWrite {
  320. let results = realm.objects(tableAccount.self)
  321. for result in results {
  322. if result.account == account {
  323. result.active = true
  324. accountReturn = result
  325. } else {
  326. result.active = false
  327. }
  328. }
  329. }
  330. } catch let error {
  331. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  332. return nil
  333. }
  334. return tableAccount.init(value: accountReturn)
  335. }
  336. @objc func removePasswordAccount(_ account: String) {
  337. let realm = try! Realm()
  338. do {
  339. try realm.safeWrite {
  340. if let result = realm.objects(tableAccount.self).filter("account == %@", account).first {
  341. result.password = "********"
  342. }
  343. }
  344. } catch let error {
  345. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  346. }
  347. }
  348. @objc func setAccountAutoUploadProperty(_ property: String, state: Bool) {
  349. let realm = try! Realm()
  350. do {
  351. try realm.safeWrite {
  352. if let result = realm.objects(tableAccount.self).filter("active == true").first {
  353. if (tableAccount().objectSchema.properties.contains { $0.name == property }) {
  354. result[property] = state
  355. }
  356. }
  357. }
  358. } catch let error {
  359. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  360. }
  361. }
  362. @objc func setAccountAutoUploadFileName(_ fileName: String?) {
  363. let realm = try! Realm()
  364. do {
  365. try realm.safeWrite {
  366. if let result = realm.objects(tableAccount.self).filter("active == true").first {
  367. if let fileName = fileName {
  368. result.autoUploadFileName = fileName
  369. } else {
  370. result.autoUploadFileName = self.getAccountAutoUploadFileName()
  371. }
  372. }
  373. }
  374. } catch let error {
  375. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  376. }
  377. }
  378. @objc func setAccountAutoUploadDirectory(_ serverUrl: String?, urlBase: String, account: String) {
  379. let realm = try! Realm()
  380. do {
  381. try realm.safeWrite {
  382. if let result = realm.objects(tableAccount.self).filter("active == true").first {
  383. if let serverUrl = serverUrl {
  384. result.autoUploadDirectory = serverUrl
  385. } else {
  386. result.autoUploadDirectory = self.getAccountAutoUploadDirectory(urlBase: urlBase, account: account)
  387. }
  388. }
  389. }
  390. } catch let error {
  391. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  392. }
  393. }
  394. @objc func setAccountUserProfile(_ userProfile: NCCommunicationUserProfile) -> tableAccount? {
  395. let realm = try! Realm()
  396. var returnAccount = tableAccount()
  397. do {
  398. guard let account = self.getAccountActive() else {
  399. return nil
  400. }
  401. try realm.safeWrite {
  402. guard let result = realm.objects(tableAccount.self).filter("account == %@", account.account).first else {
  403. return
  404. }
  405. result.address = userProfile.address
  406. result.backend = userProfile.backend
  407. result.backendCapabilitiesSetDisplayName = userProfile.backendCapabilitiesSetDisplayName
  408. result.backendCapabilitiesSetPassword = userProfile.backendCapabilitiesSetPassword
  409. result.displayName = userProfile.displayName
  410. result.email = userProfile.email
  411. result.enabled = userProfile.enabled
  412. result.groups = userProfile.groups.joined(separator: ",")
  413. result.language = userProfile.language
  414. result.lastLogin = userProfile.lastLogin
  415. result.locale = userProfile.locale
  416. result.phone = userProfile.phone
  417. result.quota = userProfile.quota
  418. result.quotaFree = userProfile.quotaFree
  419. result.quotaRelative = userProfile.quotaRelative
  420. result.quotaTotal = userProfile.quotaTotal
  421. result.quotaUsed = userProfile.quotaUsed
  422. result.storageLocation = userProfile.storageLocation
  423. result.subadmin = userProfile.subadmin.joined(separator: ",")
  424. result.twitter = userProfile.twitter
  425. result.userID = userProfile.userId
  426. result.webpage = userProfile.webpage
  427. returnAccount = result
  428. }
  429. } catch let error {
  430. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  431. }
  432. return tableAccount.init(value: returnAccount)
  433. }
  434. @objc func setAccountUserProfileHC(businessSize: String, businessType: String, city: String, company: String, country: String, role: String, zip: String) -> tableAccount? {
  435. let realm = try! Realm()
  436. var returnAccount = tableAccount()
  437. do {
  438. guard let account = self.getAccountActive() else {
  439. return nil
  440. }
  441. try realm.safeWrite {
  442. guard let result = realm.objects(tableAccount.self).filter("account == %@", account.account).first else {
  443. return
  444. }
  445. result.businessSize = businessSize
  446. result.businessType = businessType
  447. result.city = city
  448. result.company = company
  449. result.country = country
  450. result.role = role
  451. result.zip = zip
  452. returnAccount = result
  453. }
  454. } catch let error {
  455. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  456. }
  457. return tableAccount.init(value: returnAccount)
  458. }
  459. /*
  460. #if !EXTENSION
  461. @objc func setAccountHCFeatures(_ features: HCFeatures) -> tableAccount? {
  462. let realm = try! Realm()
  463. var returnAccount = tableAccount()
  464. do {
  465. guard let account = self.getAccountActive() else {
  466. return nil
  467. }
  468. try realm.write {
  469. guard let result = realm.objects(tableAccount.self).filter("account == %@", account.account).first else {
  470. return
  471. }
  472. result.hcIsTrial = features.isTrial
  473. result.hcTrialExpired = features.trialExpired
  474. result.hcTrialRemainingSec = features.trialRemainingSec
  475. if features.trialEndTime > 0 {
  476. result.hcTrialEndTime = Date(timeIntervalSince1970: features.trialEndTime) as NSDate
  477. } else {
  478. result.hcTrialEndTime = nil
  479. }
  480. result.hcAccountRemoveExpired = features.accountRemoveExpired
  481. result.hcAccountRemoveRemainingSec = features.accountRemoveRemainingSec
  482. if features.accountRemoveTime > 0 {
  483. result.hcAccountRemoveTime = Date(timeIntervalSince1970: features.accountRemoveTime) as NSDate
  484. } else {
  485. result.hcAccountRemoveTime = nil
  486. }
  487. result.hcNextGroupExpirationGroup = features.nextGroupExpirationGroup
  488. result.hcNextGroupExpirationGroupExpired = features.nextGroupExpirationGroupExpired
  489. if features.nextGroupExpirationExpiresTime > 0 {
  490. result.hcNextGroupExpirationExpiresTime = Date(timeIntervalSince1970: features.nextGroupExpirationExpiresTime) as NSDate
  491. } else {
  492. result.hcNextGroupExpirationExpiresTime = nil
  493. }
  494. result.hcNextGroupExpirationExpires = features.nextGroupExpirationExpires
  495. returnAccount = result
  496. }
  497. } catch let error {
  498. print("[LOG] Could not write to database: ", error)
  499. }
  500. return tableAccount.init(value: returnAccount)
  501. }
  502. #endif
  503. */
  504. @objc func setAccountMediaPath(_ path: String, account: String) {
  505. let realm = try! Realm()
  506. do {
  507. try realm.safeWrite {
  508. if let result = realm.objects(tableAccount.self).filter("account == %@", account).first {
  509. result.mediaPath = path
  510. }
  511. }
  512. } catch let error {
  513. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  514. }
  515. }
  516. //MARK: -
  517. //MARK: Table Activity
  518. @objc func addActivity(_ activities: [NCCommunicationActivity], account: String) {
  519. let realm = try! Realm()
  520. do {
  521. try realm.write {
  522. for activity in activities {
  523. let addObjectActivity = tableActivity()
  524. addObjectActivity.account = account
  525. addObjectActivity.idActivity = activity.idActivity
  526. addObjectActivity.idPrimaryKey = account + String(activity.idActivity)
  527. addObjectActivity.date = activity.date
  528. addObjectActivity.app = activity.app
  529. addObjectActivity.type = activity.type
  530. addObjectActivity.user = activity.user
  531. addObjectActivity.subject = activity.subject
  532. if let subject_rich = activity.subject_rich {
  533. if let json = JSON(subject_rich).array {
  534. addObjectActivity.subjectRich = json[0].stringValue
  535. if json.count > 1 {
  536. if let dict = json[1].dictionary {
  537. for (key, value) in dict {
  538. let addObjectActivitySubjectRich = tableActivitySubjectRich()
  539. let dict = value as JSON
  540. addObjectActivitySubjectRich.account = account
  541. if dict["id"].intValue > 0 {
  542. addObjectActivitySubjectRich.id = String(dict["id"].intValue)
  543. } else {
  544. addObjectActivitySubjectRich.id = dict["id"].stringValue
  545. }
  546. addObjectActivitySubjectRich.name = dict["name"].stringValue
  547. addObjectActivitySubjectRich.idPrimaryKey = account + String(activity.idActivity) + addObjectActivitySubjectRich.id + addObjectActivitySubjectRich.name
  548. addObjectActivitySubjectRich.key = key
  549. addObjectActivitySubjectRich.idActivity = activity.idActivity
  550. addObjectActivitySubjectRich.link = dict["link"].stringValue
  551. addObjectActivitySubjectRich.path = dict["path"].stringValue
  552. addObjectActivitySubjectRich.type = dict["type"].stringValue
  553. realm.add(addObjectActivitySubjectRich, update: .all)
  554. }
  555. }
  556. }
  557. }
  558. }
  559. if let previews = activity.previews {
  560. if let json = JSON(previews).array {
  561. for preview in json {
  562. let addObjectActivityPreview = tableActivityPreview()
  563. addObjectActivityPreview.account = account
  564. addObjectActivityPreview.idActivity = activity.idActivity
  565. addObjectActivityPreview.fileId = preview["fileId"].intValue
  566. addObjectActivityPreview.idPrimaryKey = account + String(activity.idActivity) + String(addObjectActivityPreview.fileId)
  567. addObjectActivityPreview.source = preview["source"].stringValue
  568. addObjectActivityPreview.link = preview["link"].stringValue
  569. addObjectActivityPreview.mimeType = preview["mimeType"].stringValue
  570. addObjectActivityPreview.view = preview["view"].stringValue
  571. addObjectActivityPreview.isMimeTypeIcon = preview["isMimeTypeIcon"].boolValue
  572. realm.add(addObjectActivityPreview, update: .all)
  573. }
  574. }
  575. }
  576. addObjectActivity.icon = activity.icon
  577. addObjectActivity.link = activity.link
  578. addObjectActivity.message = activity.message
  579. addObjectActivity.objectType = activity.object_type
  580. addObjectActivity.objectId = activity.object_id
  581. addObjectActivity.objectName = activity.object_name
  582. realm.add(addObjectActivity, update: .all)
  583. }
  584. }
  585. } catch let error {
  586. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  587. }
  588. }
  589. func getActivity(predicate: NSPredicate, filterFileId: String?) -> (all: [tableActivity], filter: [tableActivity]) {
  590. let realm = try! Realm()
  591. let results = realm.objects(tableActivity.self).filter(predicate).sorted(byKeyPath: "idActivity", ascending: false)
  592. let allActivity = Array(results.map { tableActivity.init(value:$0) })
  593. if filterFileId != nil {
  594. var resultsFilter: [tableActivity] = []
  595. for result in results {
  596. let resultsActivitySubjectRich = realm.objects(tableActivitySubjectRich.self).filter("account == %@ && idActivity == %d", result.account, result.idActivity)
  597. for resultActivitySubjectRich in resultsActivitySubjectRich {
  598. if filterFileId!.contains(resultActivitySubjectRich.id) && resultActivitySubjectRich.key == "file" {
  599. resultsFilter.append(result)
  600. break
  601. }
  602. }
  603. }
  604. return(all: allActivity, filter: Array(resultsFilter.map { tableActivity.init(value:$0) }))
  605. } else {
  606. return(all: allActivity, filter: allActivity)
  607. }
  608. }
  609. @objc func getActivitySubjectRich(account: String, idActivity: Int, key: String) -> tableActivitySubjectRich? {
  610. let realm = try! Realm()
  611. let results = realm.objects(tableActivitySubjectRich.self).filter("account == %@ && idActivity == %d && key == %@", account, idActivity, key).first
  612. return results.map { tableActivitySubjectRich.init(value:$0) }
  613. }
  614. @objc func getActivitySubjectRich(account: String, idActivity: Int, id: String) -> tableActivitySubjectRich? {
  615. let realm = try! Realm()
  616. let results = realm.objects(tableActivitySubjectRich.self).filter("account == %@ && idActivity == %d && id == %@", account, idActivity, id).first
  617. return results.map { tableActivitySubjectRich.init(value:$0) }
  618. }
  619. @objc func getActivityPreview(account: String, idActivity: Int, orderKeysId: [String]) -> [tableActivityPreview] {
  620. let realm = try! Realm()
  621. var results: [tableActivityPreview] = []
  622. for id in orderKeysId {
  623. if let result = realm.objects(tableActivityPreview.self).filter("account == %@ && idActivity == %d && fileId == %d", account, idActivity, Int(id) ?? 0).first {
  624. results.append(result)
  625. }
  626. }
  627. return results
  628. }
  629. @objc func getActivityLastIdActivity(account: String) -> Int {
  630. let realm = try! Realm()
  631. if let entities = realm.objects(tableActivity.self).filter("account == %@", account).max(by: { $0.idActivity < $1.idActivity }) {
  632. return entities.idActivity
  633. }
  634. return 0
  635. }
  636. //MARK: -
  637. //MARK: Table Capabilities
  638. @objc func addCapabilitiesJSon(_ data: Data, account: String) {
  639. let realm = try! Realm()
  640. do {
  641. try realm.safeWrite {
  642. let addObject = tableCapabilities()
  643. addObject.account = account
  644. addObject.jsondata = data
  645. realm.add(addObject, update: .all)
  646. }
  647. } catch let error {
  648. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  649. }
  650. }
  651. @objc func getCapabilities(account: String) -> String? {
  652. let realm = try! Realm()
  653. guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
  654. return nil
  655. }
  656. guard let jsondata = result.jsondata else {
  657. return nil
  658. }
  659. let json = JSON(jsondata)
  660. return json.rawString()?.replacingOccurrences(of: "\\/", with: "/")
  661. }
  662. @objc func getCapabilitiesServerString(account: String, elements: Array<String>) -> String? {
  663. let realm = try! Realm()
  664. guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
  665. return nil
  666. }
  667. guard let jsondata = result.jsondata else {
  668. return nil
  669. }
  670. let json = JSON(jsondata)
  671. return json[elements].string
  672. }
  673. @objc func getCapabilitiesServerInt(account: String, elements: Array<String>) -> Int {
  674. let realm = try! Realm()
  675. guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
  676. return 0
  677. }
  678. guard let jsondata = result.jsondata else {
  679. return 0
  680. }
  681. let json = JSON(jsondata)
  682. return json[elements].intValue
  683. }
  684. @objc func getCapabilitiesServerBool(account: String, elements: Array<String>, exists: Bool) -> Bool {
  685. let realm = try! Realm()
  686. guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
  687. return false
  688. }
  689. guard let jsondata = result.jsondata else {
  690. return false
  691. }
  692. let json = JSON(jsondata)
  693. if exists {
  694. return json[elements].exists()
  695. } else {
  696. return json[elements].boolValue
  697. }
  698. }
  699. @objc func getCapabilitiesServerArray(account: String, elements: Array<String>) -> [String]? {
  700. let realm = try! Realm()
  701. var resultArray: [String] = []
  702. guard let result = realm.objects(tableCapabilities.self).filter("account == %@", account).first else {
  703. return nil
  704. }
  705. guard let jsondata = result.jsondata else {
  706. return nil
  707. }
  708. let json = JSON(jsondata)
  709. if let results = json[elements].array {
  710. for result in results {
  711. resultArray.append(result.string ?? "")
  712. }
  713. return resultArray
  714. }
  715. return nil
  716. }
  717. //MARK: -
  718. //MARK: Table Comments
  719. @objc func addComments(_ comments: [NCCommunicationComments], account: String, objectId: String) {
  720. let realm = try! Realm()
  721. do {
  722. try realm.safeWrite {
  723. let results = realm.objects(tableComments.self).filter("account == %@ AND objectId == %@", account, objectId)
  724. realm.delete(results)
  725. for comment in comments {
  726. let object = tableComments()
  727. object.account = account
  728. object.actorDisplayName = comment.actorDisplayName
  729. object.actorId = comment.actorId
  730. object.actorType = comment.actorType
  731. object.creationDateTime = comment.creationDateTime as NSDate
  732. object.isUnread = comment.isUnread
  733. object.message = comment.message
  734. object.messageId = comment.messageId
  735. object.objectId = comment.objectId
  736. object.objectType = comment.objectType
  737. object.path = comment.path
  738. object.verb = comment.verb
  739. realm.add(object, update: .all)
  740. }
  741. }
  742. } catch let error {
  743. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  744. }
  745. }
  746. @objc func getComments(account: String, objectId: String) -> [tableComments] {
  747. let realm = try! Realm()
  748. let results = realm.objects(tableComments.self).filter("account == %@ AND objectId == %@", account, objectId).sorted(byKeyPath: "creationDateTime", ascending: false)
  749. return Array(results.map { tableComments.init(value:$0) })
  750. }
  751. //MARK: -
  752. //MARK: Table Direct Editing
  753. @objc func addDirectEditing(account: String, editors: [NCCommunicationEditorDetailsEditors], creators: [NCCommunicationEditorDetailsCreators]) {
  754. let realm = try! Realm()
  755. do {
  756. try realm.safeWrite {
  757. let resultsCreators = realm.objects(tableDirectEditingCreators.self).filter("account == %@", account)
  758. realm.delete(resultsCreators)
  759. let resultsEditors = realm.objects(tableDirectEditingEditors.self).filter("account == %@", account)
  760. realm.delete(resultsEditors)
  761. for creator in creators {
  762. let addObject = tableDirectEditingCreators()
  763. addObject.account = account
  764. addObject.editor = creator.editor
  765. addObject.ext = creator.ext
  766. addObject.identifier = creator.identifier
  767. addObject.mimetype = creator.mimetype
  768. addObject.name = creator.name
  769. addObject.templates = creator.templates
  770. realm.add(addObject)
  771. }
  772. for editor in editors {
  773. let addObject = tableDirectEditingEditors()
  774. addObject.account = account
  775. for mimeType in editor.mimetypes {
  776. addObject.mimetypes.append(mimeType)
  777. }
  778. addObject.name = editor.name
  779. if editor.name.lowercased() == k_editor_onlyoffice {
  780. addObject.editor = k_editor_onlyoffice
  781. } else {
  782. addObject.editor = k_editor_text
  783. }
  784. for mimeType in editor.optionalMimetypes {
  785. addObject.optionalMimetypes.append(mimeType)
  786. }
  787. addObject.secure = editor.secure
  788. realm.add(addObject)
  789. }
  790. }
  791. } catch let error {
  792. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  793. }
  794. }
  795. @objc func getDirectEditingCreators(account: String) -> [tableDirectEditingCreators]? {
  796. let realm = try! Realm()
  797. let results = realm.objects(tableDirectEditingCreators.self).filter("account == %@", account)
  798. if (results.count > 0) {
  799. return Array(results.map { tableDirectEditingCreators.init(value:$0) })
  800. } else {
  801. return nil
  802. }
  803. }
  804. @objc func getDirectEditingCreators(predicate: NSPredicate) -> [tableDirectEditingCreators]? {
  805. let realm = try! Realm()
  806. let results = realm.objects(tableDirectEditingCreators.self).filter(predicate)
  807. if (results.count > 0) {
  808. return Array(results.map { tableDirectEditingCreators.init(value:$0) })
  809. } else {
  810. return nil
  811. }
  812. }
  813. @objc func getDirectEditingEditors(account: String) -> [tableDirectEditingEditors]? {
  814. let realm = try! Realm()
  815. let results = realm.objects(tableDirectEditingEditors.self).filter("account == %@", account)
  816. if (results.count > 0) {
  817. return Array(results.map { tableDirectEditingEditors.init(value:$0) })
  818. } else {
  819. return nil
  820. }
  821. }
  822. //MARK: -
  823. //MARK: Table Directory
  824. @objc func copyObject(directory: tableDirectory) -> tableDirectory {
  825. return tableDirectory.init(value: directory)
  826. }
  827. @objc func addDirectory(encrypted: Bool, favorite: Bool, ocId: String, fileId: String, etag: String? = nil, permissions: String? = nil, serverUrl: String, richWorkspace: String? = nil, creationDate: NSDate? = nil, account: String) {
  828. let realm = try! Realm()
  829. do {
  830. try realm.safeWrite {
  831. var addObject = tableDirectory()
  832. let result = realm.objects(tableDirectory.self).filter("ocId == %@", ocId).first
  833. if result != nil {
  834. addObject = result!
  835. } else {
  836. addObject.ocId = ocId
  837. }
  838. addObject.account = account
  839. if let creationDate = creationDate {
  840. addObject.creationDate = creationDate
  841. }
  842. addObject.e2eEncrypted = encrypted
  843. addObject.favorite = favorite
  844. addObject.fileId = fileId
  845. if let etag = etag {
  846. addObject.etag = etag
  847. }
  848. if let permissions = permissions {
  849. addObject.permissions = permissions
  850. }
  851. addObject.richWorkspace = richWorkspace
  852. addObject.serverUrl = serverUrl
  853. realm.add(addObject, update: .all)
  854. }
  855. } catch let error {
  856. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  857. }
  858. }
  859. @objc func deleteDirectoryAndSubDirectory(serverUrl: String, account: String) {
  860. let realm = try! Realm()
  861. let results = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl BEGINSWITH %@", account, serverUrl)
  862. // Delete table Metadata & LocalFile
  863. for result in results {
  864. self.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", result.account, result.serverUrl))
  865. self.deleteLocalFile(predicate: NSPredicate(format: "ocId == %@", result.ocId))
  866. }
  867. // Delete table Dirrectory
  868. do {
  869. try realm.safeWrite {
  870. realm.delete(results)
  871. }
  872. } catch let error {
  873. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  874. }
  875. }
  876. @objc func setDirectory(serverUrl: String, serverUrlTo: String? = nil, etag: String? = nil, ocId: String? = nil, fileId: String? = nil, encrypted: Bool, richWorkspace: String? = nil, account: String) {
  877. let realm = try! Realm()
  878. do {
  879. try realm.safeWrite {
  880. guard let result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else {
  881. return
  882. }
  883. let directory = tableDirectory.init(value: result)
  884. realm.delete(result)
  885. directory.e2eEncrypted = encrypted
  886. if let etag = etag {
  887. directory.etag = etag
  888. }
  889. if let ocId = ocId {
  890. directory.ocId = ocId
  891. }
  892. if let fileId = fileId {
  893. directory.fileId = fileId
  894. }
  895. if let serverUrlTo = serverUrlTo {
  896. directory.serverUrl = serverUrlTo
  897. }
  898. if let richWorkspace = richWorkspace {
  899. directory.richWorkspace = richWorkspace
  900. }
  901. realm.add(directory, update: .all)
  902. }
  903. } catch let error {
  904. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  905. }
  906. }
  907. @objc func getTableDirectory(predicate: NSPredicate) -> tableDirectory? {
  908. let realm = try! Realm()
  909. guard let result = realm.objects(tableDirectory.self).filter(predicate).first else {
  910. return nil
  911. }
  912. return tableDirectory.init(value: result)
  913. }
  914. @objc func getTablesDirectory(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableDirectory]? {
  915. let realm = try! Realm()
  916. let results = realm.objects(tableDirectory.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  917. if (results.count > 0) {
  918. return Array(results.map { tableDirectory.init(value:$0) })
  919. } else {
  920. return nil
  921. }
  922. }
  923. @objc func renameDirectory(ocId: String, serverUrl: String) {
  924. let realm = try! Realm()
  925. do {
  926. try realm.safeWrite {
  927. let result = realm.objects(tableDirectory.self).filter("ocId == %@", ocId).first
  928. result?.serverUrl = serverUrl
  929. }
  930. } catch let error {
  931. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  932. }
  933. }
  934. @objc func setDirectory(serverUrl: String, offline: Bool, account: String) {
  935. let realm = try! Realm()
  936. do {
  937. try realm.safeWrite {
  938. let result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first
  939. result?.offline = offline
  940. }
  941. } catch let error {
  942. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  943. }
  944. }
  945. @objc func setDirectory(richWorkspace: String?, serverUrl: String, account: String) {
  946. let realm = try! Realm()
  947. do {
  948. try realm.safeWrite {
  949. let result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first
  950. result?.richWorkspace = richWorkspace
  951. }
  952. } catch let error {
  953. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  954. }
  955. }
  956. //MARK: -
  957. //MARK: Table e2e Encryption
  958. @objc func addE2eEncryption(_ e2e: tableE2eEncryption) {
  959. let realm = try! Realm()
  960. do {
  961. try realm.safeWrite {
  962. realm.add(e2e, update: .all)
  963. }
  964. } catch let error {
  965. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  966. }
  967. }
  968. @objc func deleteE2eEncryption(predicate: NSPredicate) {
  969. let realm = try! Realm()
  970. do {
  971. try realm.safeWrite {
  972. let results = realm.objects(tableE2eEncryption.self).filter(predicate)
  973. realm.delete(results)
  974. }
  975. } catch let error {
  976. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  977. }
  978. }
  979. @objc func getE2eEncryption(predicate: NSPredicate) -> tableE2eEncryption? {
  980. let realm = try! Realm()
  981. guard let result = realm.objects(tableE2eEncryption.self).filter(predicate).sorted(byKeyPath: "metadataKeyIndex", ascending: false).first else {
  982. return nil
  983. }
  984. return tableE2eEncryption.init(value: result)
  985. }
  986. @objc func getE2eEncryptions(predicate: NSPredicate) -> [tableE2eEncryption]? {
  987. guard self.getAccountActive() != nil else {
  988. return nil
  989. }
  990. let realm = try! Realm()
  991. let results : Results<tableE2eEncryption>
  992. results = realm.objects(tableE2eEncryption.self).filter(predicate)
  993. if (results.count > 0) {
  994. return Array(results.map { tableE2eEncryption.init(value:$0) })
  995. } else {
  996. return nil
  997. }
  998. }
  999. @objc func renameFileE2eEncryption(serverUrl: String, fileNameIdentifier: String, newFileName: String, newFileNamePath: String) {
  1000. guard let tableAccount = self.getAccountActive() else {
  1001. return
  1002. }
  1003. let realm = try! Realm()
  1004. realm.beginWrite()
  1005. guard let result = realm.objects(tableE2eEncryption.self).filter("account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", tableAccount.account, serverUrl, fileNameIdentifier).first else {
  1006. realm.cancelWrite()
  1007. return
  1008. }
  1009. let object = tableE2eEncryption.init(value: result)
  1010. realm.delete(result)
  1011. object.fileName = newFileName
  1012. object.fileNamePath = newFileNamePath
  1013. realm.add(object)
  1014. do {
  1015. try realm.commitWrite()
  1016. } catch let error {
  1017. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1018. }
  1019. }
  1020. //MARK: -
  1021. //MARK: Table e2e Encryption Lock
  1022. @objc func getE2ETokenLock(account: String, serverUrl: String) -> tableE2eEncryptionLock? {
  1023. let realm = try! Realm()
  1024. guard let result = realm.objects(tableE2eEncryptionLock.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else {
  1025. return nil
  1026. }
  1027. return tableE2eEncryptionLock.init(value: result)
  1028. }
  1029. @objc func setE2ETokenLock(account: String, serverUrl: String, fileId: String, e2eToken: String) {
  1030. let realm = try! Realm()
  1031. do {
  1032. try realm.safeWrite {
  1033. let addObject = tableE2eEncryptionLock()
  1034. addObject.account = account
  1035. addObject.fileId = fileId
  1036. addObject.serverUrl = serverUrl
  1037. addObject.e2eToken = e2eToken
  1038. realm.add(addObject, update: .all)
  1039. }
  1040. } catch let error {
  1041. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1042. }
  1043. }
  1044. @objc func deteleE2ETokenLock(account: String, serverUrl: String) {
  1045. let realm = try! Realm()
  1046. do {
  1047. try realm.safeWrite {
  1048. if let result = realm.objects(tableE2eEncryptionLock.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first {
  1049. realm.delete(result)
  1050. }
  1051. }
  1052. } catch let error {
  1053. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1054. }
  1055. }
  1056. //MARK: -
  1057. //MARK: Table External Sites
  1058. @objc func addExternalSites(_ externalSite: NCCommunicationExternalSite, account: String) {
  1059. let realm = try! Realm()
  1060. do {
  1061. try realm.safeWrite {
  1062. let addObject = tableExternalSites()
  1063. addObject.account = account
  1064. addObject.idExternalSite = externalSite.idExternalSite
  1065. addObject.icon = externalSite.icon
  1066. addObject.lang = externalSite.lang
  1067. addObject.name = externalSite.name
  1068. addObject.url = externalSite.url
  1069. addObject.type = externalSite.type
  1070. realm.add(addObject)
  1071. }
  1072. } catch let error {
  1073. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1074. }
  1075. }
  1076. @objc func deleteExternalSites(account: String) {
  1077. let realm = try! Realm()
  1078. do {
  1079. try realm.safeWrite {
  1080. let results = realm.objects(tableExternalSites.self).filter("account == %@", account)
  1081. realm.delete(results)
  1082. }
  1083. } catch let error {
  1084. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1085. }
  1086. }
  1087. @objc func getAllExternalSites(account: String) -> [tableExternalSites]? {
  1088. let realm = try! Realm()
  1089. let results = realm.objects(tableExternalSites.self).filter("account == %@", account).sorted(byKeyPath: "idExternalSite", ascending: true)
  1090. if results.count > 0 {
  1091. return Array(results.map { tableExternalSites.init(value:$0) })
  1092. } else {
  1093. return nil
  1094. }
  1095. }
  1096. //MARK: -
  1097. //MARK: Table GPS
  1098. @objc func addGeocoderLocation(_ location: String, placemarkAdministrativeArea: String, placemarkCountry: String, placemarkLocality: String, placemarkPostalCode: String, placemarkThoroughfare: String, latitude: String, longitude: String) {
  1099. let realm = try! Realm()
  1100. realm.beginWrite()
  1101. // Verify if exists
  1102. guard realm.objects(tableGPS.self).filter("latitude == %@ AND longitude == %@", latitude, longitude).first == nil else {
  1103. realm.cancelWrite()
  1104. return
  1105. }
  1106. // Add new GPS
  1107. let addObject = tableGPS()
  1108. addObject.latitude = latitude
  1109. addObject.location = location
  1110. addObject.longitude = longitude
  1111. addObject.placemarkAdministrativeArea = placemarkAdministrativeArea
  1112. addObject.placemarkCountry = placemarkCountry
  1113. addObject.placemarkLocality = placemarkLocality
  1114. addObject.placemarkPostalCode = placemarkPostalCode
  1115. addObject.placemarkThoroughfare = placemarkThoroughfare
  1116. realm.add(addObject)
  1117. do {
  1118. try realm.commitWrite()
  1119. } catch let error {
  1120. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1121. }
  1122. }
  1123. @objc func getLocationFromGeoLatitude(_ latitude: String, longitude: String) -> String? {
  1124. let realm = try! Realm()
  1125. let result = realm.objects(tableGPS.self).filter("latitude == %@ AND longitude == %@", latitude, longitude).first
  1126. return result?.location
  1127. }
  1128. //MARK: -
  1129. //MARK: Table LocalFile
  1130. @objc func copyObject(localFile: tableLocalFile) -> tableLocalFile {
  1131. return tableLocalFile.init(value: localFile)
  1132. }
  1133. @objc func addLocalFile(metadata: tableMetadata) {
  1134. let realm = try! Realm()
  1135. do {
  1136. try realm.safeWrite {
  1137. let addObject = tableLocalFile()
  1138. addObject.account = metadata.account
  1139. addObject.etag = metadata.etag
  1140. addObject.exifDate = NSDate()
  1141. addObject.exifLatitude = "-1"
  1142. addObject.exifLongitude = "-1"
  1143. addObject.ocId = metadata.ocId
  1144. addObject.fileName = metadata.fileName
  1145. addObject.size = metadata.size
  1146. realm.add(addObject, update: .all)
  1147. }
  1148. } catch let error {
  1149. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1150. }
  1151. }
  1152. @objc func deleteLocalFile(predicate: NSPredicate) {
  1153. let realm = try! Realm()
  1154. do {
  1155. try realm.safeWrite {
  1156. let results = realm.objects(tableLocalFile.self).filter(predicate)
  1157. realm.delete(results)
  1158. }
  1159. } catch let error {
  1160. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1161. }
  1162. }
  1163. @objc func setLocalFile(ocId: String, fileName: String?, etag: String?) {
  1164. let realm = try! Realm()
  1165. do {
  1166. try realm.safeWrite {
  1167. let result = realm.objects(tableLocalFile.self).filter("ocId == %@", ocId).first
  1168. if let fileName = fileName {
  1169. result?.fileName = fileName
  1170. }
  1171. if let etag = etag {
  1172. result?.etag = etag
  1173. }
  1174. }
  1175. } catch let error {
  1176. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1177. }
  1178. }
  1179. @objc func getTableLocalFile(predicate: NSPredicate) -> tableLocalFile? {
  1180. let realm = try! Realm()
  1181. guard let result = realm.objects(tableLocalFile.self).filter(predicate).first else {
  1182. return nil
  1183. }
  1184. return tableLocalFile.init(value: result)
  1185. }
  1186. @objc func getTableLocalFiles(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableLocalFile] {
  1187. let realm = try! Realm()
  1188. let results = realm.objects(tableLocalFile.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1189. return Array(results.map { tableLocalFile.init(value:$0) })
  1190. }
  1191. @objc func setLocalFile(ocId: String, offline: Bool) {
  1192. let realm = try! Realm()
  1193. do {
  1194. try realm.safeWrite {
  1195. let result = realm.objects(tableLocalFile.self).filter("ocId == %@", ocId).first
  1196. result?.offline = offline
  1197. }
  1198. } catch let error {
  1199. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1200. }
  1201. }
  1202. @objc func setLocalFile(ocId: String, lastAccessDate: Date) {
  1203. let realm = try! Realm()
  1204. do {
  1205. try realm.safeWrite {
  1206. let result = realm.objects(tableLocalFile.self).filter("ocId == %@", ocId).first
  1207. result?.lastAccessDate = lastAccessDate as NSDate
  1208. }
  1209. } catch let error {
  1210. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1211. }
  1212. }
  1213. //MARK: -
  1214. //MARK: Table Metadata
  1215. @objc func copyObject(metadata: tableMetadata) -> tableMetadata {
  1216. return tableMetadata.init(value: metadata)
  1217. }
  1218. @objc func convertNCFileToMetadata(_ file: NCCommunicationFile, isEncrypted: Bool, account: String) -> tableMetadata {
  1219. let metadata = tableMetadata()
  1220. metadata.account = account
  1221. metadata.commentsUnread = file.commentsUnread
  1222. metadata.contentType = file.contentType
  1223. if let date = file.creationDate {
  1224. metadata.creationDate = date
  1225. } else {
  1226. metadata.creationDate = file.date
  1227. }
  1228. metadata.date = file.date
  1229. metadata.directory = file.directory
  1230. metadata.e2eEncrypted = file.e2eEncrypted
  1231. metadata.etag = file.etag
  1232. metadata.ext = file.ext
  1233. metadata.favorite = file.favorite
  1234. metadata.fileId = file.fileId
  1235. metadata.fileName = file.fileName
  1236. metadata.fileNameView = file.fileName
  1237. metadata.fileNameWithoutExt = file.fileNameWithoutExt
  1238. metadata.hasPreview = file.hasPreview
  1239. metadata.iconName = file.iconName
  1240. metadata.livePhoto = file.livePhoto
  1241. metadata.mountType = file.mountType
  1242. metadata.ocId = file.ocId
  1243. metadata.ownerId = file.ownerId
  1244. metadata.ownerDisplayName = file.ownerDisplayName
  1245. metadata.permissions = file.permissions
  1246. metadata.quotaUsedBytes = file.quotaUsedBytes
  1247. metadata.quotaAvailableBytes = file.quotaAvailableBytes
  1248. metadata.richWorkspace = file.richWorkspace
  1249. metadata.resourceType = file.resourceType
  1250. metadata.serverUrl = file.serverUrl
  1251. metadata.size = file.size
  1252. metadata.typeFile = file.typeFile
  1253. if let date = file.uploadDate {
  1254. metadata.uploadDate = date
  1255. } else {
  1256. metadata.uploadDate = file.date
  1257. }
  1258. metadata.urlBase = file.urlBase
  1259. // E2EE find the fileName for fileNameView
  1260. if isEncrypted || metadata.e2eEncrypted {
  1261. if let tableE2eEncryption = NCManageDatabase.sharedInstance.getE2eEncryption(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameIdentifier == %@", account, file.serverUrl, file.fileName)) {
  1262. metadata.fileNameView = tableE2eEncryption.fileName
  1263. let results = NCCommunicationCommon.shared.getInternalContenType(fileName: metadata.fileNameView, contentType: file.contentType, directory: file.directory)
  1264. metadata.contentType = results.contentType
  1265. metadata.iconName = results.iconName
  1266. metadata.typeFile = results.typeFile
  1267. }
  1268. }
  1269. return metadata
  1270. }
  1271. @objc func convertNCCommunicationFilesToMetadatas(_ files: [NCCommunicationFile], useMetadataFolder: Bool, account: String, completion: @escaping (_ metadataFolder: tableMetadata,_ metadatasFolder: [tableMetadata], _ metadatas: [tableMetadata])->()) {
  1272. var counter: Int = 0
  1273. var isEncrypted: Bool = false
  1274. var listServerUrl: [String: Bool] = [:]
  1275. var metadataFolder = tableMetadata()
  1276. var metadataFolders: [tableMetadata] = []
  1277. var metadatas: [tableMetadata] = []
  1278. for file in files {
  1279. if let key = listServerUrl[file.serverUrl] {
  1280. isEncrypted = key
  1281. } else {
  1282. isEncrypted = CCUtility.isFolderEncrypted(file.serverUrl, e2eEncrypted: file.e2eEncrypted, account: account, urlBase: file.urlBase)
  1283. listServerUrl[file.serverUrl] = isEncrypted
  1284. }
  1285. let metadata = convertNCFileToMetadata(file, isEncrypted: isEncrypted, account: account)
  1286. if counter == 0 && useMetadataFolder {
  1287. metadataFolder = tableMetadata.init(value: metadata)
  1288. } else {
  1289. metadatas.append(metadata)
  1290. if metadata.directory {
  1291. metadataFolders.append(metadata)
  1292. }
  1293. }
  1294. counter += 1
  1295. }
  1296. completion(metadataFolder, metadataFolders, metadatas)
  1297. }
  1298. @objc func createMetadata(account: String, fileName: String, ocId: String, serverUrl: String, urlBase: String, url: String, contentType: String, livePhoto: Bool) -> tableMetadata {
  1299. let metadata = tableMetadata()
  1300. let results = NCCommunicationCommon.shared.getInternalContenType(fileName: fileName, contentType: contentType, directory: false)
  1301. metadata.account = account
  1302. metadata.contentType = results.contentType
  1303. metadata.creationDate = Date() as NSDate
  1304. metadata.date = Date() as NSDate
  1305. metadata.hasPreview = true
  1306. metadata.iconName = results.iconName
  1307. metadata.etag = ocId
  1308. metadata.ext = (fileName as NSString).pathExtension.lowercased()
  1309. metadata.fileName = fileName
  1310. metadata.fileNameView = fileName
  1311. metadata.fileNameWithoutExt = (fileName as NSString).deletingPathExtension
  1312. metadata.livePhoto = livePhoto
  1313. metadata.ocId = ocId
  1314. metadata.permissions = "RGDNVW"
  1315. metadata.serverUrl = serverUrl
  1316. metadata.typeFile = results.typeFile
  1317. metadata.uploadDate = Date() as NSDate
  1318. metadata.url = url
  1319. metadata.urlBase = urlBase
  1320. return metadata
  1321. }
  1322. @objc func addMetadata(_ metadata: tableMetadata) {
  1323. let realm = try! Realm()
  1324. do {
  1325. try realm.safeWrite {
  1326. realm.add(metadata, update: .all)
  1327. }
  1328. } catch let error {
  1329. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1330. }
  1331. }
  1332. @objc func addMetadatas(_ metadatas: [tableMetadata]) {
  1333. let realm = try! Realm()
  1334. do {
  1335. try realm.safeWrite {
  1336. for metadata in metadatas {
  1337. realm.add(metadata, update: .all)
  1338. }
  1339. }
  1340. } catch let error {
  1341. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1342. }
  1343. }
  1344. @objc func addMetadatas(files: [NCCommunicationFile]?, account: String) {
  1345. guard let files = files else { return }
  1346. let realm = try! Realm()
  1347. do {
  1348. try realm.safeWrite {
  1349. for file in files {
  1350. let metadata = tableMetadata()
  1351. metadata.account = account
  1352. metadata.commentsUnread = file.commentsUnread
  1353. metadata.contentType = file.contentType
  1354. if let date = file.creationDate {
  1355. metadata.creationDate = date
  1356. } else {
  1357. metadata.creationDate = file.date
  1358. }
  1359. metadata.date = file.date
  1360. metadata.directory = file.directory
  1361. metadata.e2eEncrypted = file.e2eEncrypted
  1362. metadata.etag = file.etag
  1363. metadata.ext = file.ext
  1364. metadata.favorite = file.favorite
  1365. metadata.fileId = file.fileId
  1366. metadata.fileName = file.fileName
  1367. metadata.fileNameView = file.fileName
  1368. metadata.fileNameWithoutExt = file.fileNameWithoutExt
  1369. metadata.hasPreview = file.hasPreview
  1370. metadata.iconName = file.iconName
  1371. metadata.livePhoto = file.livePhoto
  1372. metadata.mountType = file.mountType
  1373. metadata.ocId = file.ocId
  1374. metadata.ownerId = file.ownerId
  1375. metadata.ownerDisplayName = file.ownerDisplayName
  1376. metadata.permissions = file.permissions
  1377. metadata.quotaUsedBytes = file.quotaUsedBytes
  1378. metadata.quotaAvailableBytes = file.quotaAvailableBytes
  1379. metadata.resourceType = file.resourceType
  1380. metadata.serverUrl = file.serverUrl
  1381. metadata.size = file.size
  1382. metadata.typeFile = file.typeFile
  1383. if let date = file.uploadDate {
  1384. metadata.uploadDate = date
  1385. } else {
  1386. metadata.uploadDate = file.date
  1387. }
  1388. metadata.urlBase = file.urlBase
  1389. realm.add(metadata, update: .all)
  1390. }
  1391. }
  1392. } catch let error {
  1393. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1394. }
  1395. }
  1396. @objc func deleteMetadata(predicate: NSPredicate) {
  1397. let realm = try! Realm()
  1398. do {
  1399. try realm.safeWrite {
  1400. let results = realm.objects(tableMetadata.self).filter(predicate)
  1401. realm.delete(results)
  1402. }
  1403. } catch let error {
  1404. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1405. }
  1406. }
  1407. @objc func moveMetadata(ocId: String, serverUrlTo: String) {
  1408. let realm = try! Realm()
  1409. do {
  1410. try realm.safeWrite {
  1411. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  1412. result.serverUrl = serverUrlTo
  1413. }
  1414. }
  1415. } catch let error {
  1416. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1417. }
  1418. }
  1419. @objc func addMetadataServerUrl(ocId: String, serverUrl: String) {
  1420. let realm = try! Realm()
  1421. do {
  1422. try realm.safeWrite {
  1423. let results = realm.objects(tableMetadata.self).filter("ocId == %@", ocId)
  1424. for result in results {
  1425. result.serverUrl = serverUrl
  1426. }
  1427. }
  1428. } catch let error {
  1429. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1430. }
  1431. }
  1432. @objc func renameMetadata(fileNameTo: String, ocId: String) {
  1433. let realm = try! Realm()
  1434. do {
  1435. try realm.safeWrite {
  1436. if let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first {
  1437. result.fileName = fileNameTo
  1438. result.fileNameView = fileNameTo
  1439. }
  1440. }
  1441. } catch let error {
  1442. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1443. }
  1444. }
  1445. @discardableResult
  1446. func updateMetadatas(_ metadatas: [tableMetadata], metadatasResult: [tableMetadata], addExistsInLocal: Bool = false, addCompareEtagLocal: Bool = false) -> (metadatasUpdate: [tableMetadata], metadatasLocalUpdate: [tableMetadata]) {
  1447. let realm = try! Realm()
  1448. var ocIdsUdate : [String] = []
  1449. var ocIdsLocalUdate : [String] = []
  1450. var metadatasUpdate : [tableMetadata] = []
  1451. var metadatasLocalUpdate : [tableMetadata] = []
  1452. realm.refresh()
  1453. do {
  1454. try realm.safeWrite {
  1455. // DELETE
  1456. for metadataResult in metadatasResult {
  1457. if metadatas.firstIndex(where: { $0.ocId == metadataResult.ocId }) == nil {
  1458. if let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "ocId == %@", metadataResult.ocId)).first {
  1459. realm.delete(result)
  1460. }
  1461. }
  1462. }
  1463. // UPDATE/NEW
  1464. for metadata in metadatas {
  1465. if let result = metadatasResult.first(where: { $0.ocId == metadata.ocId }) {
  1466. // update
  1467. if result.status == k_metadataStatusNormal && (result.etag != metadata.etag || result.fileNameView != metadata.fileNameView || result.date != metadata.date || result.livePhoto != metadata.livePhoto || result.permissions != metadata.permissions) {
  1468. ocIdsUdate.append(metadata.ocId)
  1469. realm.add(metadata, update: .all)
  1470. }
  1471. } else {
  1472. // new
  1473. ocIdsUdate.append(metadata.ocId)
  1474. realm.add(metadata, update: .all)
  1475. }
  1476. if metadata.directory && !ocIdsUdate.contains(metadata.ocId) {
  1477. let table = realm.objects(tableDirectory.self).filter(NSPredicate(format: "ocId == %@", metadata.ocId)).first
  1478. if table?.etag != metadata.etag {
  1479. ocIdsUdate.append(metadata.ocId)
  1480. }
  1481. }
  1482. // Local
  1483. if !metadata.directory && (addExistsInLocal || addCompareEtagLocal) {
  1484. let localFile = realm.objects(tableLocalFile.self).filter(NSPredicate(format: "ocId == %@", metadata.ocId)).first
  1485. if addCompareEtagLocal && localFile != nil && localFile?.etag != metadata.etag {
  1486. ocIdsLocalUdate.append(metadata.ocId)
  1487. }
  1488. if addExistsInLocal && (localFile == nil || localFile?.etag != metadata.etag) && !ocIdsLocalUdate.contains(metadata.ocId) {
  1489. ocIdsLocalUdate.append(metadata.ocId)
  1490. }
  1491. }
  1492. }
  1493. }
  1494. } catch let error {
  1495. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1496. }
  1497. for ocId in ocIdsUdate {
  1498. if let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "ocId == %@", ocId)).first {
  1499. metadatasUpdate.append(tableMetadata.init(value: result))
  1500. }
  1501. }
  1502. for ocId in ocIdsLocalUdate {
  1503. if let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "ocId == %@", ocId)).first {
  1504. metadatasLocalUpdate.append(tableMetadata.init(value: result))
  1505. }
  1506. }
  1507. return (metadatasUpdate, metadatasLocalUpdate)
  1508. }
  1509. func setMetadataSession(ocId: String, session: String? = nil, sessionError: String? = nil, sessionSelector: String? = nil, sessionTaskIdentifier: Int? = nil, status: Int? = nil, etag: String? = nil, setFavorite: Bool = false) {
  1510. let realm = try! Realm()
  1511. realm.refresh()
  1512. do {
  1513. try realm.safeWrite {
  1514. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  1515. if let session = session {
  1516. result?.session = session
  1517. }
  1518. if let sessionError = sessionError {
  1519. result?.sessionError = sessionError
  1520. }
  1521. if let sessionSelector = sessionSelector {
  1522. result?.sessionSelector = sessionSelector
  1523. }
  1524. if let sessionTaskIdentifier = sessionTaskIdentifier {
  1525. result?.sessionTaskIdentifier = sessionTaskIdentifier
  1526. }
  1527. if let status = status {
  1528. result?.status = status
  1529. }
  1530. if let etag = etag {
  1531. result?.etag = etag
  1532. }
  1533. if setFavorite {
  1534. result?.favorite = true
  1535. }
  1536. }
  1537. } catch let error {
  1538. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1539. }
  1540. }
  1541. func setMetadataStatus(ocId: String, status: Int) -> tableMetadata? {
  1542. let realm = try! Realm()
  1543. var result: tableMetadata?
  1544. do {
  1545. try realm.safeWrite {
  1546. result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  1547. result?.status = status
  1548. }
  1549. } catch let error {
  1550. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1551. }
  1552. if let result = result {
  1553. return tableMetadata.init(value: result)
  1554. } else {
  1555. return nil
  1556. }
  1557. }
  1558. @objc func setMetadataFavorite(ocId: String, favorite: Bool) {
  1559. let realm = try! Realm()
  1560. do {
  1561. try realm.safeWrite {
  1562. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  1563. result?.favorite = favorite
  1564. }
  1565. } catch let error {
  1566. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1567. }
  1568. }
  1569. @objc func setMetadataEncrypted(ocId: String, encrypted: Bool) {
  1570. let realm = try! Realm()
  1571. do {
  1572. try realm.safeWrite {
  1573. let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first
  1574. result?.e2eEncrypted = encrypted
  1575. }
  1576. } catch let error {
  1577. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1578. }
  1579. }
  1580. @objc func setMetadataFileNameView(serverUrl: String, fileName: String, newFileNameView: String, account: String) {
  1581. let realm = try! Realm()
  1582. do {
  1583. try realm.safeWrite {
  1584. let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first
  1585. result?.fileNameView = newFileNameView
  1586. }
  1587. } catch let error {
  1588. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1589. }
  1590. }
  1591. @objc func getMetadata(predicate: NSPredicate) -> tableMetadata? {
  1592. let realm = try! Realm()
  1593. realm.refresh()
  1594. guard let result = realm.objects(tableMetadata.self).filter(predicate).first else {
  1595. return nil
  1596. }
  1597. return tableMetadata.init(value: result)
  1598. }
  1599. @objc func getMetadata(predicate: NSPredicate, sorted: String, ascending: Bool) -> tableMetadata? {
  1600. let realm = try! Realm()
  1601. realm.refresh()
  1602. guard let result = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending).first else {
  1603. return nil
  1604. }
  1605. return tableMetadata.init(value: result)
  1606. }
  1607. @objc func getMetadatasViewer(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableMetadata]? {
  1608. let realm = try! Realm()
  1609. realm.refresh()
  1610. let results: Results<tableMetadata>
  1611. var finals: [tableMetadata] = []
  1612. if (tableMetadata().objectSchema.properties.contains { $0.name == sorted }) {
  1613. results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1614. } else {
  1615. results = realm.objects(tableMetadata.self).filter(predicate)
  1616. }
  1617. // For Live Photo
  1618. var fileNameImages: [String] = []
  1619. let filtered = results.filter{ $0.typeFile.contains(k_metadataTypeFile_image) }
  1620. filtered.forEach { print($0)
  1621. let fileName = ($0.fileNameView as NSString).deletingPathExtension
  1622. fileNameImages.append(fileName)
  1623. }
  1624. for result in results {
  1625. let ext = (result.fileNameView as NSString).pathExtension.uppercased()
  1626. let fileName = (result.fileNameView as NSString).deletingPathExtension
  1627. if !(ext == "MOV" && fileNameImages.contains(fileName)) {
  1628. finals.append(result)
  1629. }
  1630. }
  1631. if (finals.count > 0) {
  1632. return Array(finals.map { tableMetadata.init(value:$0) })
  1633. } else {
  1634. return nil
  1635. }
  1636. }
  1637. @objc func getMetadatas(predicate: NSPredicate, page: Int = 0, limit: Int = 0, sorted: String = "fileName", ascending: Bool = false) -> [tableMetadata] {
  1638. let realm = try! Realm()
  1639. realm.refresh()
  1640. var metadatas: [tableMetadata] = []
  1641. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1642. if results.count > 0 {
  1643. if page == 0 || limit == 0 {
  1644. return Array(results.map { tableMetadata.init(value:$0) })
  1645. } else {
  1646. let nFrom = (page - 1) * limit
  1647. let nTo = nFrom + (limit - 1)
  1648. for n in nFrom...nTo {
  1649. if n == results.count {
  1650. break
  1651. }
  1652. metadatas.append(tableMetadata.init(value:results[n]))
  1653. }
  1654. }
  1655. }
  1656. return metadatas
  1657. }
  1658. @objc func getMetadataAtIndex(predicate: NSPredicate, sorted: String, ascending: Bool, index: Int) -> tableMetadata? {
  1659. let realm = try! Realm()
  1660. realm.refresh()
  1661. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1662. if (results.count > 0 && results.count > index) {
  1663. return tableMetadata.init(value: results[index])
  1664. } else {
  1665. return nil
  1666. }
  1667. }
  1668. @objc func getMetadataFromOcId(_ ocId: String?) -> tableMetadata? {
  1669. let realm = try! Realm()
  1670. realm.refresh()
  1671. guard let ocId = ocId else { return nil }
  1672. guard let result = realm.objects(tableMetadata.self).filter("ocId == %@", ocId).first else { return nil }
  1673. return tableMetadata.init(value: result)
  1674. }
  1675. @objc func getTableMetadatasDirectoryFavoriteIdentifierRank(account: String) -> [String: NSNumber] {
  1676. var listIdentifierRank: [String: NSNumber] = [:]
  1677. let realm = try! Realm()
  1678. var counter = 10 as Int64
  1679. let results = realm.objects(tableMetadata.self).filter("account == %@ AND directory == true AND favorite == true", account).sorted(byKeyPath: "fileNameView", ascending: true)
  1680. for result in results {
  1681. counter += 1
  1682. listIdentifierRank[result.ocId] = NSNumber(value: Int64(counter))
  1683. }
  1684. return listIdentifierRank
  1685. }
  1686. @objc func clearMetadatasUpload(account: String) {
  1687. let realm = try! Realm()
  1688. realm.refresh()
  1689. do {
  1690. try realm.safeWrite {
  1691. let results = realm.objects(tableMetadata.self).filter("account == %@ AND (status == %d OR status == %@)", account, k_metadataStatusWaitUpload, k_metadataStatusUploadError)
  1692. realm.delete(results)
  1693. }
  1694. } catch let error {
  1695. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1696. }
  1697. }
  1698. @objc func readMarkerMetadata(account: String, fileId: String) {
  1699. let realm = try! Realm()
  1700. do {
  1701. try realm.safeWrite {
  1702. let results = realm.objects(tableMetadata.self).filter("account == %@ AND fileId == %@", account, fileId)
  1703. for result in results {
  1704. result.commentsUnread = false
  1705. }
  1706. }
  1707. } catch let error {
  1708. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1709. }
  1710. }
  1711. @objc func getAssetLocalIdentifiersUploaded(account: String, sessionSelector: String) -> [String] {
  1712. let realm = try! Realm()
  1713. realm.refresh()
  1714. var assetLocalIdentifiers: [String] = []
  1715. let results = realm.objects(tableMetadata.self).filter("account == %@ AND assetLocalIdentifier != '' AND deleteAssetLocalIdentifier == true AND sessionSelector == %@", account, sessionSelector)
  1716. for result in results {
  1717. assetLocalIdentifiers.append(result.assetLocalIdentifier)
  1718. }
  1719. return assetLocalIdentifiers
  1720. }
  1721. @objc func clearAssetLocalIdentifiers(_ assetLocalIdentifiers: [String], account: String) {
  1722. let realm = try! Realm()
  1723. do {
  1724. try realm.safeWrite {
  1725. let results = realm.objects(tableMetadata.self).filter("account == %@ AND assetLocalIdentifier IN %@", account, assetLocalIdentifiers)
  1726. for result in results {
  1727. result.assetLocalIdentifier = ""
  1728. result.deleteAssetLocalIdentifier = false
  1729. }
  1730. }
  1731. } catch let error {
  1732. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1733. }
  1734. }
  1735. @objc func isLivePhoto(metadata: tableMetadata) -> tableMetadata? {
  1736. let realm = try! Realm()
  1737. realm.refresh()
  1738. if !metadata.livePhoto || !CCUtility.getLivePhoto() {
  1739. return nil
  1740. }
  1741. guard let result = realm.objects(tableMetadata.self).filter(NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameWithoutExt == %@ AND ocId != %@", metadata.account, metadata.serverUrl, metadata.fileNameWithoutExt, metadata.ocId)).first else {
  1742. return nil
  1743. }
  1744. return tableMetadata.init(value: result)
  1745. }
  1746. func getMetadatasMedia(predicate: NSPredicate, sort: String, ascending: Bool = false) -> [tableMetadata] {
  1747. let realm = try! Realm()
  1748. realm.refresh()
  1749. let sortProperties = [SortDescriptor(keyPath: sort, ascending: ascending), SortDescriptor(keyPath: "fileNameView", ascending: false)]
  1750. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(by: sortProperties)
  1751. return Array(results.map { tableMetadata.init(value:$0) })
  1752. }
  1753. //MARK: -
  1754. //MARK: Table Photo Library
  1755. @objc func addPhotoLibrary(_ assets: [PHAsset], account: String) -> Bool {
  1756. let realm = try! Realm()
  1757. do {
  1758. try realm.safeWrite {
  1759. var creationDateString = ""
  1760. for asset in assets {
  1761. let addObject = tablePhotoLibrary()
  1762. addObject.account = account
  1763. addObject.assetLocalIdentifier = asset.localIdentifier
  1764. addObject.mediaType = asset.mediaType.rawValue
  1765. if let creationDate = asset.creationDate {
  1766. addObject.creationDate = creationDate as NSDate
  1767. creationDateString = String(describing: creationDate)
  1768. } else {
  1769. creationDateString = ""
  1770. }
  1771. if let modificationDate = asset.modificationDate {
  1772. addObject.modificationDate = modificationDate as NSDate
  1773. }
  1774. addObject.idAsset = "\(account)\(asset.localIdentifier)\(creationDateString)"
  1775. realm.add(addObject, update: .all)
  1776. }
  1777. }
  1778. } catch let error {
  1779. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1780. return false
  1781. }
  1782. return true
  1783. }
  1784. @objc func getPhotoLibraryIdAsset(image: Bool, video: Bool, account: String) -> [String]? {
  1785. let realm = try! Realm()
  1786. var predicate = NSPredicate()
  1787. if (image && video) {
  1788. predicate = NSPredicate(format: "account == %@ AND (mediaType == %d OR mediaType == %d)", account, PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
  1789. } else if (image) {
  1790. predicate = NSPredicate(format: "account == %@ AND mediaType == %d", account, PHAssetMediaType.image.rawValue)
  1791. } else if (video) {
  1792. predicate = NSPredicate(format: "account == %@ AND mediaType == %d", account, PHAssetMediaType.video.rawValue)
  1793. }
  1794. let results = realm.objects(tablePhotoLibrary.self).filter(predicate)
  1795. let idsAsset = results.map { $0.idAsset }
  1796. return Array(idsAsset)
  1797. }
  1798. @objc func getPhotoLibrary(predicate: NSPredicate) -> [tablePhotoLibrary] {
  1799. let realm = try! Realm()
  1800. let results = realm.objects(tablePhotoLibrary.self).filter(predicate)
  1801. return Array(results.map { tablePhotoLibrary.init(value:$0) })
  1802. }
  1803. //MARK: -
  1804. //MARK: Table Share
  1805. @objc func addShare(urlBase: String, account: String, shares: [NCCommunicationShare]) {
  1806. let realm = try! Realm()
  1807. realm.beginWrite()
  1808. for share in shares {
  1809. let addObject = tableShare()
  1810. let fullPath = NCUtility.shared.getHomeServer(urlBase: urlBase, account: account) + share.path
  1811. let serverUrl = CCUtility.deletingLastPathComponent(fromServerUrl: fullPath)!
  1812. let fileName = NSString(string: fullPath).lastPathComponent
  1813. addObject.account = account
  1814. addObject.fileName = fileName
  1815. addObject.serverUrl = serverUrl
  1816. addObject.canEdit = share.canEdit
  1817. addObject.canDelete = share.canDelete
  1818. addObject.date = share.date
  1819. addObject.displaynameFileOwner = share.displaynameFileOwner
  1820. addObject.displaynameOwner = share.displaynameOwner
  1821. addObject.expirationDate = share.expirationDate
  1822. addObject.fileParent = share.fileParent
  1823. addObject.fileSource = share.fileSource
  1824. addObject.fileTarget = share.fileTarget
  1825. addObject.hideDownload = share.hideDownload
  1826. addObject.idShare = share.idShare
  1827. addObject.itemSource = share.itemSource
  1828. addObject.itemType = share.itemType
  1829. addObject.label = share.label
  1830. addObject.mailSend = share.mailSend
  1831. addObject.mimeType = share.mimeType
  1832. addObject.note = share.note
  1833. addObject.parent = share.parent
  1834. addObject.password = share.password
  1835. addObject.path = share.path
  1836. addObject.permissions = share.permissions
  1837. addObject.sendPasswordByTalk = share.sendPasswordByTalk
  1838. addObject.shareType = share.shareType
  1839. addObject.shareWith = share.shareWith
  1840. addObject.shareWithDisplayname = share.shareWithDisplayname
  1841. addObject.storage = share.storage
  1842. addObject.storageId = share.storageId
  1843. addObject.token = share.token
  1844. addObject.uidOwner = share.uidOwner
  1845. addObject.uidFileOwner = share.uidFileOwner
  1846. addObject.url = share.url
  1847. realm.add(addObject, update: .all)
  1848. }
  1849. do {
  1850. try realm.commitWrite()
  1851. } catch let error {
  1852. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1853. }
  1854. }
  1855. @objc func getTableShares(account: String) -> [tableShare] {
  1856. let realm = try! Realm()
  1857. let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
  1858. let results = realm.objects(tableShare.self).filter("account == %@", account).sorted(by: sortProperties)
  1859. return Array(results.map { tableShare.init(value:$0) })
  1860. }
  1861. func getTableShares(metadata: tableMetadata) -> (firstShareLink: tableShare?, share: [tableShare]?) {
  1862. let realm = try! Realm()
  1863. let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
  1864. let firstShareLink = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@ AND shareType == 3", metadata.account, metadata.serverUrl, metadata.fileName).first
  1865. if firstShareLink == nil {
  1866. let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", metadata.account, metadata.serverUrl, metadata.fileName).sorted(by: sortProperties)
  1867. return(firstShareLink: firstShareLink, share: Array(results.map { tableShare.init(value:$0) }))
  1868. } else {
  1869. 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)
  1870. return(firstShareLink: firstShareLink, share: Array(results.map { tableShare.init(value:$0) }))
  1871. }
  1872. }
  1873. func getTableShare(account: String, idShare: Int) -> tableShare? {
  1874. let realm = try! Realm()
  1875. guard let result = realm.objects(tableShare.self).filter("account = %@ AND idShare = %d", account, idShare).first else {
  1876. return nil
  1877. }
  1878. return tableShare.init(value: result)
  1879. }
  1880. @objc func getTableShares(account: String, serverUrl: String) -> [tableShare] {
  1881. let realm = try! Realm()
  1882. let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
  1883. let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).sorted(by: sortProperties)
  1884. return Array(results.map { tableShare.init(value:$0) })
  1885. }
  1886. @objc func getTableShares(account: String, serverUrl: String, fileName: String) -> [tableShare] {
  1887. let realm = try! Realm()
  1888. let sortProperties = [SortDescriptor(keyPath: "shareType", ascending: false), SortDescriptor(keyPath: "idShare", ascending: false)]
  1889. let results = realm.objects(tableShare.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).sorted(by: sortProperties)
  1890. return Array(results.map { tableShare.init(value:$0) })
  1891. }
  1892. @objc func deleteTableShare(account: String, idShare: Int) {
  1893. let realm = try! Realm()
  1894. realm.beginWrite()
  1895. let result = realm.objects(tableShare.self).filter("account == %@ AND idShare == %d", account, idShare)
  1896. realm.delete(result)
  1897. do {
  1898. try realm.commitWrite()
  1899. } catch let error {
  1900. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1901. }
  1902. }
  1903. @objc func deleteTableShare(account: String) {
  1904. let realm = try! Realm()
  1905. realm.beginWrite()
  1906. let result = realm.objects(tableShare.self).filter("account == %@", account)
  1907. realm.delete(result)
  1908. do {
  1909. try realm.commitWrite()
  1910. } catch let error {
  1911. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1912. }
  1913. }
  1914. //MARK: -
  1915. //MARK: Table Tag
  1916. @objc func addTag(_ ocId: String ,tagIOS: Data?, account: String) {
  1917. let realm = try! Realm()
  1918. do {
  1919. try realm.safeWrite {
  1920. // Add new
  1921. let addObject = tableTag()
  1922. addObject.account = account
  1923. addObject.ocId = ocId
  1924. addObject.tagIOS = tagIOS
  1925. realm.add(addObject, update: .all)
  1926. }
  1927. } catch let error {
  1928. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1929. }
  1930. }
  1931. @objc func deleteTag(_ ocId: String) {
  1932. let realm = try! Realm()
  1933. realm.beginWrite()
  1934. let result = realm.objects(tableTag.self).filter("ocId == %@", ocId)
  1935. realm.delete(result)
  1936. do {
  1937. try realm.commitWrite()
  1938. } catch let error {
  1939. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1940. }
  1941. }
  1942. @objc func getTags(predicate: NSPredicate) -> [tableTag] {
  1943. let realm = try! Realm()
  1944. let results = realm.objects(tableTag.self).filter(predicate)
  1945. return Array(results.map { tableTag.init(value:$0) })
  1946. }
  1947. @objc func getTag(predicate: NSPredicate) -> tableTag? {
  1948. let realm = try! Realm()
  1949. guard let result = realm.objects(tableTag.self).filter(predicate).first else {
  1950. return nil
  1951. }
  1952. return tableTag.init(value: result)
  1953. }
  1954. //MARK: -
  1955. //MARK: Table Trash
  1956. @objc func addTrash(account: String, items: [NCCommunicationTrash]) {
  1957. let realm = try! Realm()
  1958. do {
  1959. try realm.safeWrite {
  1960. for trash in items {
  1961. let object = tableTrash()
  1962. object.account = account
  1963. object.contentType = trash.contentType
  1964. object.date = trash.date
  1965. object.directory = trash.directory
  1966. object.fileId = trash.fileId
  1967. object.fileName = trash.fileName
  1968. object.filePath = trash.filePath
  1969. object.hasPreview = trash.hasPreview
  1970. object.iconName = trash.iconName
  1971. object.size = trash.size
  1972. object.trashbinDeletionTime = trash.trashbinDeletionTime
  1973. object.trashbinFileName = trash.trashbinFileName
  1974. object.trashbinOriginalLocation = trash.trashbinOriginalLocation
  1975. object.typeFile = trash.typeFile
  1976. realm.add(object, update: .all)
  1977. }
  1978. }
  1979. } catch let error {
  1980. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1981. }
  1982. }
  1983. @objc func deleteTrash(filePath: String?, account: String) {
  1984. let realm = try! Realm()
  1985. var predicate = NSPredicate()
  1986. do {
  1987. try realm.safeWrite {
  1988. if filePath == nil {
  1989. predicate = NSPredicate(format: "account == %@", account)
  1990. } else {
  1991. predicate = NSPredicate(format: "account == %@ AND filePath == %@", account, filePath!)
  1992. }
  1993. let result = realm.objects(tableTrash.self).filter(predicate)
  1994. realm.delete(result)
  1995. }
  1996. } catch let error {
  1997. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  1998. }
  1999. }
  2000. @objc func deleteTrash(fileId: String?, account: String) {
  2001. let realm = try! Realm()
  2002. var predicate = NSPredicate()
  2003. do {
  2004. try realm.safeWrite {
  2005. if fileId == nil {
  2006. predicate = NSPredicate(format: "account == %@", account)
  2007. } else {
  2008. predicate = NSPredicate(format: "account == %@ AND fileId == %@", account, fileId!)
  2009. }
  2010. let result = realm.objects(tableTrash.self).filter(predicate)
  2011. realm.delete(result)
  2012. }
  2013. } catch let error {
  2014. NCCommunicationCommon.shared.writeLog("Could not write to database: \(error)")
  2015. }
  2016. }
  2017. @objc func getTrash(filePath: String, sort: String, ascending: Bool, account: String) -> [tableTrash]? {
  2018. let realm = try! Realm()
  2019. let results = realm.objects(tableTrash.self).filter("account == %@ AND filePath == %@", account, filePath).sorted(byKeyPath: sort, ascending: ascending)
  2020. return Array(results.map { tableTrash.init(value:$0) })
  2021. }
  2022. @objc func getTrashItem(fileId: String, account: String) -> tableTrash? {
  2023. let realm = try! Realm()
  2024. guard let result = realm.objects(tableTrash.self).filter("account == %@ AND fileId == %@", account, fileId).first else {
  2025. return nil
  2026. }
  2027. return tableTrash.init(value: result)
  2028. }
  2029. //MARK: -
  2030. }
  2031. extension Realm {
  2032. public func safeWrite(_ block: (() throws -> Void)) throws {
  2033. if isInWriteTransaction {
  2034. try block()
  2035. } else {
  2036. try write(block)
  2037. }
  2038. }
  2039. }