NCManageDatabase.swift 106 KB

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