NCManageDatabase.swift 99 KB

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