NCManageDatabase.swift 115 KB

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