NCManageDatabase.swift 109 KB

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