NCManageDatabase.swift 101 KB

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