NCManageDatabase.swift 111 KB

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