NCManageDatabase.swift 98 KB

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