NCManageDatabase.swift 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517
  1. //
  2. // NCManageDatabase.swift
  3. // Nextcloud iOS
  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. class NCManageDatabase: NSObject {
  25. @objc static let sharedInstance: NCManageDatabase = {
  26. let instance = NCManageDatabase()
  27. return instance
  28. }()
  29. override init() {
  30. let dirGroup = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: NCBrandOptions.sharedInstance.capabilitiesGroups)
  31. var configCompact = Realm.Configuration(
  32. fileURL: dirGroup?.appendingPathComponent("\(k_appDatabaseNextcloud)/\(k_databaseDefault)"),
  33. shouldCompactOnLaunch: { totalBytes, usedBytes in
  34. // totalBytes refers to the size of the file on disk in bytes (data + free space)
  35. // usedBytes refers to the number of bytes used by data in the file
  36. // Compact if the file is over 100MB in size and less than 50% 'used'
  37. let oneHundredMB = 100 * 1024 * 1024
  38. return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
  39. })
  40. // Encrypting the database file on disk with AES-256+SHA2 by supplying a 64-byte encryption key
  41. if NCBrandOptions.sharedInstance.use_database_encryption {
  42. if let keyData = Data(base64Encoded: NCBrandOptions.sharedInstance.databaseEncryptionKey) {
  43. configCompact.encryptionKey = keyData
  44. }
  45. }
  46. do {
  47. // Realm is compacted on the first open if the configuration block conditions were met.
  48. _ = try Realm(configuration: configCompact)
  49. } catch {
  50. // handle error compacting or opening Realm
  51. }
  52. var config = Realm.Configuration(
  53. fileURL: dirGroup?.appendingPathComponent("\(k_appDatabaseNextcloud)/\(k_databaseDefault)"),
  54. schemaVersion: 41,
  55. // 10 : Version 2.18.0
  56. // 11 : Version 2.18.2
  57. // 12 : Version 2.19.0.5
  58. // 13 : Version 2.19.0.14
  59. // 14 : Version 2.19.0.xx
  60. // 15 : Version 2.19.2
  61. // 16 : Version 2.20.2
  62. // 17 : Version 2.20.4
  63. // 18 : Version 2.20.6
  64. // 19 : Version 2.20.7
  65. // 20 : Version 2.21.0
  66. // 21 : Version 2.21.0.3
  67. // 22 : Version 2.21.0.9
  68. // 23 : Version 2.21.0.15
  69. // 24 : Version 2.21.2.5
  70. // 25 : Version 2.21.3.1
  71. // 26 : Version 2.22.0.4
  72. // 27 : Version 2.22.0.7
  73. // 28 : Version 2.22.3.5
  74. // 29 : Version 2.22.5.2
  75. // 30 : Version 2.22.6.0
  76. // 31 : Version 2.22.6.3
  77. // 32 : Version 2.22.6.10
  78. // 33 : Version 2.22.7.1
  79. // 34 : Version 2.22.8.14
  80. // 35 : Version 2.22.8.14
  81. // 36 : Version 2.22.8.14
  82. // 37 : Version 2.22.8.14
  83. // 38 : Version 2.22.8.20
  84. // 39 : Version 2.22.9.1
  85. // 40 : Version 2.22.9.3
  86. // 41 : Version 2.22.9.5
  87. migrationBlock: { migration, oldSchemaVersion in
  88. // We haven’t migrated anything yet, so oldSchemaVersion == 0
  89. /*
  90. if (oldSchemaVersion < 37) {
  91. migration.enumerateObjects(ofType: tableMetadata.className()) { oldObject, newObject in
  92. let account = oldObject!["account"] as! String
  93. let serverUrl = oldObject!["serverUrl"] as! String
  94. let fileName = oldObject!["fileName"] as! String
  95. newObject!["metadataID"] = CCUtility.createMetadataID(fromAccount: account, serverUrl: serverUrl, fileName: fileName)
  96. }
  97. migration.enumerateObjects(ofType: tablePhotos.className()) { oldObject, newObject in
  98. let account = oldObject!["account"] as! String
  99. let serverUrl = oldObject!["serverUrl"] as! String
  100. let fileName = oldObject!["fileName"] as! String
  101. newObject!["metadataID"] = CCUtility.createMetadataID(fromAccount: account, serverUrl: serverUrl, fileName: fileName)
  102. }
  103. }
  104. */
  105. if oldSchemaVersion < 41 {
  106. migration.deleteData(forType: tableActivity.className())
  107. migration.deleteData(forType: tableMetadata.className())
  108. migration.deleteData(forType: tablePhotos.className())
  109. migration.deleteData(forType: tableDirectory.className())
  110. }
  111. })
  112. // Encrypting the database file on disk with AES-256+SHA2 by supplying a 64-byte encryption key
  113. if NCBrandOptions.sharedInstance.use_database_encryption {
  114. if let keyData = Data(base64Encoded: NCBrandOptions.sharedInstance.databaseEncryptionKey) {
  115. config.encryptionKey = keyData
  116. }
  117. }
  118. Realm.Configuration.defaultConfiguration = config
  119. _ = try! Realm()
  120. }
  121. //MARK: -
  122. //MARK: Utility Database
  123. @objc func clearTable(_ table : Object.Type, account: String?) {
  124. let results : Results<Object>
  125. let realm = try! Realm()
  126. realm.beginWrite()
  127. if let account = account {
  128. results = realm.objects(table).filter("account = %@", account)
  129. } else {
  130. results = realm.objects(table)
  131. }
  132. realm.delete(results)
  133. do {
  134. try realm.commitWrite()
  135. } catch let error {
  136. print("[LOG] Could not write to database: ", error)
  137. }
  138. }
  139. @objc func removeDB() {
  140. let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
  141. let realmURLs = [
  142. realmURL,
  143. realmURL.appendingPathExtension("lock"),
  144. realmURL.appendingPathExtension("note"),
  145. realmURL.appendingPathExtension("management")
  146. ]
  147. for URL in realmURLs {
  148. do {
  149. try FileManager.default.removeItem(at: URL)
  150. } catch let error {
  151. print("[LOG] Could not write to database: ", error)
  152. }
  153. }
  154. }
  155. @objc func getThreadConfined(_ object: Object) -> Any {
  156. // id tradeReference = [[NCManageDatabase sharedInstance] getThreadConfined:metadata];
  157. return ThreadSafeReference(to: object)
  158. }
  159. @objc func putThreadConfined(_ tableRef: Any) -> Object? {
  160. //tableMetadata *metadataThread = (tableMetadata *)[[NCManageDatabase sharedInstance] putThreadConfined:tradeReference];
  161. let realm = try! Realm()
  162. return realm.resolve(tableRef as! ThreadSafeReference<Object>)
  163. }
  164. @objc func isTableInvalidated(_ object: Object) -> Bool {
  165. return object.isInvalidated
  166. }
  167. //MARK: -
  168. //MARK: Table Account
  169. @objc func addAccount(_ account: String, url: String, user: String, password: String, loginFlow: Bool) {
  170. let realm = try! Realm()
  171. realm.beginWrite()
  172. let addObject = tableAccount()
  173. addObject.account = account
  174. addObject.loginFlow = loginFlow
  175. // Brand
  176. if NCBrandOptions.sharedInstance.use_default_auto_upload {
  177. addObject.autoUpload = true
  178. addObject.autoUploadImage = true
  179. addObject.autoUploadVideo = true
  180. addObject.autoUploadWWAnVideo = true
  181. }
  182. addObject.password = password
  183. addObject.url = url
  184. addObject.user = user
  185. addObject.userID = user
  186. realm.add(addObject)
  187. do {
  188. try realm.commitWrite()
  189. } catch let error {
  190. print("[LOG] Could not write to database: ", error)
  191. }
  192. }
  193. @objc func setAccountPassword(_ account: String, password: String) -> tableAccount? {
  194. let realm = try! Realm()
  195. realm.beginWrite()
  196. guard let result = realm.objects(tableAccount.self).filter("account = %@", account).first else {
  197. realm.cancelWrite()
  198. return nil
  199. }
  200. result.password = password
  201. do {
  202. try realm.commitWrite()
  203. } catch let error {
  204. print("[LOG] Could not write to database: ", error)
  205. return nil
  206. }
  207. return result
  208. }
  209. @objc func deleteAccount(_ account: String) {
  210. let realm = try! Realm()
  211. realm.beginWrite()
  212. guard let result = realm.objects(tableAccount.self).filter("account = %@", account).first else {
  213. realm.cancelWrite()
  214. return
  215. }
  216. realm.delete(result)
  217. do {
  218. try realm.commitWrite()
  219. } catch let error {
  220. print("[LOG] Could not write to database: ", error)
  221. }
  222. }
  223. @objc func getAccountActive() -> tableAccount? {
  224. let realm = try! Realm()
  225. realm.refresh()
  226. guard let result = realm.objects(tableAccount.self).filter("active = true").first else {
  227. return nil
  228. }
  229. return result
  230. }
  231. @objc func getAccounts() -> [String]? {
  232. let realm = try! Realm()
  233. realm.refresh()
  234. let results = realm.objects(tableAccount.self).sorted(byKeyPath: "account", ascending: true)
  235. if results.count > 0 {
  236. return Array(results.map { $0.account })
  237. }
  238. return nil
  239. }
  240. @objc func getAccount(predicate: NSPredicate) -> tableAccount? {
  241. let realm = try! Realm()
  242. realm.refresh()
  243. if let result = realm.objects(tableAccount.self).filter(predicate).first {
  244. return tableAccount.init(value: result)
  245. }
  246. return nil
  247. }
  248. @objc func getAccountAutoUploadFileName() -> String {
  249. let realm = try! Realm()
  250. realm.refresh()
  251. guard let result = realm.objects(tableAccount.self).filter("active = true").first else {
  252. return ""
  253. }
  254. if result.autoUploadFileName.count > 0 {
  255. return result.autoUploadFileName
  256. } else {
  257. return NCBrandOptions.sharedInstance.folderDefaultAutoUpload
  258. }
  259. }
  260. @objc func getAccountAutoUploadDirectory(_ activeUrl : String) -> String {
  261. let realm = try! Realm()
  262. realm.refresh()
  263. guard let result = realm.objects(tableAccount.self).filter("active = true").first else {
  264. return ""
  265. }
  266. if result.autoUploadDirectory.count > 0 {
  267. return result.autoUploadDirectory
  268. } else {
  269. return CCUtility.getHomeServerUrlActiveUrl(activeUrl)
  270. }
  271. }
  272. @objc func getAccountAutoUploadPath(_ activeUrl : String) -> String {
  273. let cameraFileName = self.getAccountAutoUploadFileName()
  274. let cameraDirectory = self.getAccountAutoUploadDirectory(activeUrl)
  275. let folderPhotos = CCUtility.stringAppendServerUrl(cameraDirectory, addFileName: cameraFileName)!
  276. return folderPhotos
  277. }
  278. @objc func setAccountActive(_ account: String) -> tableAccount? {
  279. let realm = try! Realm()
  280. var activeAccount = tableAccount()
  281. do {
  282. try realm.write {
  283. let results = realm.objects(tableAccount.self)
  284. for result in results {
  285. if result.account == account {
  286. result.active = true
  287. activeAccount = result
  288. } else {
  289. result.active = false
  290. }
  291. }
  292. }
  293. } catch let error {
  294. print("[LOG] Could not write to database: ", error)
  295. return nil
  296. }
  297. return activeAccount
  298. }
  299. @objc func setAccountAutoUploadProperty(_ property: String, state: Bool) {
  300. let realm = try! Realm()
  301. realm.beginWrite()
  302. guard let result = realm.objects(tableAccount.self).filter("active = true").first else {
  303. realm.cancelWrite()
  304. return
  305. }
  306. if (tableAccount().objectSchema.properties.contains { $0.name == property }) {
  307. result[property] = state
  308. do {
  309. try realm.commitWrite()
  310. } catch let error {
  311. print("[LOG] Could not write to database: ", error)
  312. }
  313. } else {
  314. print("[LOG] property not found")
  315. }
  316. }
  317. @objc func setAccountAutoUploadFileName(_ fileName: String?) {
  318. let realm = try! Realm()
  319. do {
  320. try realm.write {
  321. if let result = realm.objects(tableAccount.self).filter("active = true").first {
  322. if let fileName = fileName {
  323. result.autoUploadFileName = fileName
  324. } else {
  325. result.autoUploadFileName = self.getAccountAutoUploadFileName()
  326. }
  327. }
  328. }
  329. } catch let error {
  330. print("[LOG] Could not write to database: ", error)
  331. }
  332. }
  333. @objc func setAccountAutoUploadDirectory(_ serverUrl: String?, activeUrl: String) {
  334. let realm = try! Realm()
  335. do {
  336. try realm.write {
  337. if let result = realm.objects(tableAccount.self).filter("active = true").first {
  338. if let serverUrl = serverUrl {
  339. result.autoUploadDirectory = serverUrl
  340. } else {
  341. result.autoUploadDirectory = self.getAccountAutoUploadDirectory(activeUrl)
  342. }
  343. }
  344. }
  345. } catch let error {
  346. print("[LOG] Could not write to database: ", error)
  347. }
  348. }
  349. @objc func setAccountUserProfile(_ userProfile: OCUserProfile) -> tableAccount? {
  350. guard let activeAccount = self.getAccountActive() else {
  351. return nil
  352. }
  353. let realm = try! Realm()
  354. do {
  355. try realm.write {
  356. guard let result = realm.objects(tableAccount.self).filter("account = %@", activeAccount.account).first else {
  357. return
  358. }
  359. // Update userID
  360. if userProfile.id.count == 0 { // for old config.
  361. result.userID = result.user
  362. } else {
  363. result.userID = userProfile.id
  364. }
  365. result.enabled = userProfile.enabled
  366. result.address = userProfile.address
  367. result.displayName = userProfile.displayName
  368. result.email = userProfile.email
  369. result.phone = userProfile.phone
  370. result.twitter = userProfile.twitter
  371. result.webpage = userProfile.webpage
  372. result.quota = userProfile.quota
  373. result.quotaFree = userProfile.quotaFree
  374. result.quotaRelative = userProfile.quotaRelative
  375. result.quotaTotal = userProfile.quotaTotal
  376. result.quotaUsed = userProfile.quotaUsed
  377. }
  378. } catch let error {
  379. print("[LOG] Could not write to database: ", error)
  380. }
  381. return activeAccount
  382. }
  383. @objc func setAccountDateSearchContentTypeImageVideo(_ date: Date) {
  384. guard let activeAccount = self.getAccountActive() else {
  385. return
  386. }
  387. let realm = try! Realm()
  388. do {
  389. try realm.write {
  390. guard let result = realm.objects(tableAccount.self).filter("account = %@", activeAccount.account).first else {
  391. return
  392. }
  393. result.dateSearchContentTypeImageVideo = date
  394. }
  395. } catch let error {
  396. print("[LOG] Could not write to database: ", error)
  397. }
  398. }
  399. @objc func getAccountStartDirectoryMediaTabView(_ homeServerUrl: String) -> String {
  400. guard let activeAccount = self.getAccountActive() else {
  401. return ""
  402. }
  403. let realm = try! Realm()
  404. realm.refresh()
  405. guard let result = realm.objects(tableAccount.self).filter("account = %@", activeAccount.account).first else {
  406. return ""
  407. }
  408. if result.startDirectoryPhotosTab == "" {
  409. self.setAccountStartDirectoryMediaTabView(homeServerUrl)
  410. return homeServerUrl
  411. } else {
  412. return result.startDirectoryPhotosTab
  413. }
  414. }
  415. @objc func setAccountStartDirectoryMediaTabView(_ directory: String) {
  416. guard let activeAccount = self.getAccountActive() else {
  417. return
  418. }
  419. let realm = try! Realm()
  420. do {
  421. try realm.write {
  422. guard let result = realm.objects(tableAccount.self).filter("account = %@", activeAccount.account).first else {
  423. return
  424. }
  425. result.startDirectoryPhotosTab = directory
  426. }
  427. } catch let error {
  428. print("[LOG] Could not write to database: ", error)
  429. }
  430. }
  431. //MARK: -
  432. //MARK: Table Activity
  433. @objc func addActivity(_ listOfActivity: [OCActivity], account: String) {
  434. let realm = try! Realm()
  435. do {
  436. try realm.write {
  437. for activity in listOfActivity {
  438. let addObjectActivity = tableActivity()
  439. addObjectActivity.account = account
  440. addObjectActivity.idActivity = activity.idActivity
  441. addObjectActivity.idPrimaryKey = account + String(activity.idActivity)
  442. if let date = activity.date {
  443. addObjectActivity.date = date as NSDate
  444. }
  445. addObjectActivity.app = activity.app
  446. addObjectActivity.type = activity.type
  447. addObjectActivity.user = activity.user
  448. addObjectActivity.subject = activity.subject
  449. if activity.subject_rich.count > 0 {
  450. addObjectActivity.subjectRich = activity.subject_rich[0] as? String ?? ""
  451. if activity.subject_rich.count > 1 {
  452. if let dict = activity.subject_rich[1] as? [String:AnyObject] {
  453. for (key, value) in dict {
  454. let addObjectActivitySubjectRich = tableActivitySubjectRich()
  455. if let dict = value as? [String:AnyObject] {
  456. addObjectActivitySubjectRich.account = account
  457. switch dict["id"] {
  458. case is String:
  459. addObjectActivitySubjectRich.id = dict["id"] as? String ?? ""
  460. case is Int:
  461. addObjectActivitySubjectRich.id = String(dict["id"] as? Int ?? 0)
  462. default: addObjectActivitySubjectRich.id = ""
  463. }
  464. addObjectActivitySubjectRich.name = dict["name"] as? String ?? ""
  465. addObjectActivitySubjectRich.idPrimaryKey = account + String(activity.idActivity) + addObjectActivitySubjectRich.id + addObjectActivitySubjectRich.name
  466. addObjectActivitySubjectRich.key = key
  467. addObjectActivitySubjectRich.idActivity = activity.idActivity
  468. addObjectActivitySubjectRich.link = dict["link"] as? String ?? ""
  469. addObjectActivitySubjectRich.path = dict["path"] as? String ?? ""
  470. addObjectActivitySubjectRich.type = dict["type"] as? String ?? ""
  471. realm.add(addObjectActivitySubjectRich, update: true)
  472. }
  473. }
  474. }
  475. }
  476. }
  477. if activity.previews.count > 0 {
  478. for case let activityPreview as [String:AnyObject] in activity.previews {
  479. let addObjectActivityPreview = tableActivityPreview()
  480. addObjectActivityPreview.account = account
  481. addObjectActivityPreview.idActivity = activity.idActivity
  482. addObjectActivityPreview.fileId = activityPreview["fileId"] as? Int ?? 0
  483. addObjectActivityPreview.idPrimaryKey = account + String(activity.idActivity) + String(addObjectActivityPreview.fileId)
  484. addObjectActivityPreview.source = activityPreview["source"] as? String ?? ""
  485. addObjectActivityPreview.link = activityPreview["link"] as? String ?? ""
  486. addObjectActivityPreview.mimeType = activityPreview["mimeType"] as? String ?? ""
  487. addObjectActivityPreview.view = activityPreview["view"] as? String ?? ""
  488. addObjectActivityPreview.isMimeTypeIcon = activityPreview["isMimeTypeIcon"] as? Bool ?? false
  489. realm.add(addObjectActivityPreview, update: true)
  490. }
  491. }
  492. addObjectActivity.icon = activity.icon
  493. addObjectActivity.link = activity.link
  494. addObjectActivity.message = activity.message
  495. addObjectActivity.objectType = activity.object_type
  496. addObjectActivity.objectId = activity.object_id
  497. addObjectActivity.objectName = activity.object_name
  498. realm.add(addObjectActivity, update: true)
  499. }
  500. }
  501. } catch let error {
  502. print("[LOG] Could not write to database: ", error)
  503. }
  504. }
  505. @objc func getActivity(predicate: NSPredicate) -> [tableActivity] {
  506. let realm = try! Realm()
  507. realm.refresh()
  508. let results = realm.objects(tableActivity.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  509. return Array(results.map { tableActivity.init(value:$0) })
  510. }
  511. @objc func getActivitySubjectRich(account: String, idActivity: Int, key: String) -> tableActivitySubjectRich? {
  512. let realm = try! Realm()
  513. realm.refresh()
  514. let results = realm.objects(tableActivitySubjectRich.self).filter("account = %@ && idActivity == %d && key = %@", account, idActivity, key).first
  515. return results.map { tableActivitySubjectRich.init(value:$0) }
  516. }
  517. @objc func getActivitySubjectRich(account: String, idActivity: Int, id: String) -> tableActivitySubjectRich? {
  518. let realm = try! Realm()
  519. realm.refresh()
  520. let results = realm.objects(tableActivitySubjectRich.self).filter("account = %@ && idActivity == %d && id == %@", account, idActivity, id).first
  521. return results.map { tableActivitySubjectRich.init(value:$0) }
  522. }
  523. @objc func getActivityPreview(account: String, idActivity: Int, orderKeysId: [String]) -> [tableActivityPreview] {
  524. let realm = try! Realm()
  525. realm.refresh()
  526. var results = [tableActivityPreview]()
  527. for id in orderKeysId {
  528. if let result = realm.objects(tableActivityPreview.self).filter("account = %@ && idActivity == %d && fileId == %d", account, idActivity, Int(id) ?? 0).first {
  529. results.append(result)
  530. }
  531. }
  532. return results
  533. }
  534. @objc func getActivityLastIdActivity(account: String) -> Int {
  535. let realm = try! Realm()
  536. realm.refresh()
  537. if let entities = realm.objects(tableActivity.self).filter("account = %@", account).max(by: { $0.idActivity < $1.idActivity }) {
  538. return entities.idActivity
  539. }
  540. return 0
  541. }
  542. //MARK: -
  543. //MARK: Table Capabilities
  544. @objc func addCapabilities(_ capabilities: OCCapabilities, account: String) {
  545. let realm = try! Realm()
  546. do {
  547. try realm.write {
  548. let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first
  549. var resultCapabilities = tableCapabilities()
  550. if let result = result {
  551. resultCapabilities = result
  552. }
  553. resultCapabilities.account = account
  554. resultCapabilities.themingBackground = capabilities.themingBackground
  555. resultCapabilities.themingBackgroundDefault = capabilities.themingBackgroundDefault
  556. resultCapabilities.themingBackgroundPlain = capabilities.themingBackgroundPlain
  557. resultCapabilities.themingColor = capabilities.themingColor
  558. resultCapabilities.themingColorElement = capabilities.themingColorElement
  559. resultCapabilities.themingColorText = capabilities.themingColorText
  560. resultCapabilities.themingLogo = capabilities.themingLogo
  561. resultCapabilities.themingName = capabilities.themingName
  562. resultCapabilities.themingSlogan = capabilities.themingSlogan
  563. resultCapabilities.themingUrl = capabilities.themingUrl
  564. resultCapabilities.versionMajor = capabilities.versionMajor
  565. resultCapabilities.versionMinor = capabilities.versionMinor
  566. resultCapabilities.versionMicro = capabilities.versionMicro
  567. resultCapabilities.versionString = capabilities.versionString
  568. resultCapabilities.endToEndEncryption = capabilities.isEndToEndEncryptionEnabled
  569. resultCapabilities.endToEndEncryptionVersion = capabilities.endToEndEncryptionVersion
  570. resultCapabilities.richdocumentsMimetypes.removeAll()
  571. for mimeType in capabilities.richdocumentsMimetypes {
  572. resultCapabilities.richdocumentsMimetypes.append(mimeType as! String)
  573. }
  574. resultCapabilities.richdocumentsDirectEditing = capabilities.richdocumentsDirectEditing
  575. if result == nil {
  576. realm.add(resultCapabilities)
  577. }
  578. }
  579. } catch let error {
  580. print("[LOG] Could not write to database: ", error)
  581. }
  582. }
  583. @objc func getCapabilites(account: String) -> tableCapabilities? {
  584. let realm = try! Realm()
  585. realm.refresh()
  586. return realm.objects(tableCapabilities.self).filter("account = %@", account).first
  587. }
  588. @objc func getServerVersion(account: String) -> Int {
  589. let realm = try! Realm()
  590. realm.refresh()
  591. guard let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  592. return 0
  593. }
  594. return result.versionMajor
  595. }
  596. @objc func getEndToEndEncryptionVersion(account: String) -> Float {
  597. let realm = try! Realm()
  598. realm.refresh()
  599. guard let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  600. return 0
  601. }
  602. return Float(result.endToEndEncryptionVersion)!
  603. }
  604. @objc func compareServerVersion(_ versionCompare: String, account: String) -> Int {
  605. let realm = try! Realm()
  606. guard let capabilities = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  607. return -1
  608. }
  609. let versionServer = capabilities.versionString
  610. var v1 = versionServer.split(separator:".").map { Int(String($0)) }
  611. var v2 = versionCompare.split(separator:".").map { Int(String($0)) }
  612. var result = 0
  613. for i in 0..<max(v1.count,v2.count) {
  614. let left = i >= v1.count ? 0 : v1[i]
  615. let right = i >= v2.count ? 0 : v2[i]
  616. if (left == right) {
  617. result = 0
  618. } else if left! > right! {
  619. return 1
  620. } else if right! > left! {
  621. return -1
  622. }
  623. }
  624. return result
  625. }
  626. @objc func getRichdocumentsMimetypes(account: String) -> [String]? {
  627. let realm = try! Realm()
  628. realm.refresh()
  629. guard let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  630. return nil
  631. }
  632. return Array(result.richdocumentsMimetypes)
  633. }
  634. //MARK: -
  635. //MARK: Table Certificates
  636. @objc func addCertificates(_ certificateLocation: String) {
  637. let realm = try! Realm()
  638. do {
  639. try realm.write {
  640. let addObject = tableCertificates()
  641. addObject.certificateLocation = certificateLocation
  642. realm.add(addObject)
  643. }
  644. } catch let error {
  645. print("[LOG] Could not write to database: ", error)
  646. }
  647. }
  648. @objc func getCertificatesLocation(_ localCertificatesFolder: String) -> [String] {
  649. let realm = try! Realm()
  650. realm.refresh()
  651. let results = realm.objects(tableCertificates.self)
  652. return Array(results.map { "\(localCertificatesFolder)/\($0.certificateLocation)" })
  653. }
  654. //MARK: -
  655. //MARK: Table Directory
  656. @objc func addDirectory(encrypted: Bool, favorite: Bool, fileID: String?, permissions: String?, serverUrl: String, account: String) -> tableDirectory? {
  657. let realm = try! Realm()
  658. realm.beginWrite()
  659. var addObject = tableDirectory()
  660. let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first
  661. if result != nil {
  662. addObject = result!
  663. } else {
  664. addObject.directoryID = CCUtility.createDirectoyID(fromAccount: account, serverUrl: serverUrl)
  665. }
  666. addObject.account = account
  667. addObject.e2eEncrypted = encrypted
  668. addObject.favorite = favorite
  669. if let fileID = fileID {
  670. addObject.fileID = fileID
  671. }
  672. if let permissions = permissions {
  673. addObject.permissions = permissions
  674. }
  675. addObject.serverUrl = serverUrl
  676. realm.add(addObject, update: true)
  677. do {
  678. try realm.commitWrite()
  679. } catch let error {
  680. print("[LOG] Could not write to database: ", error)
  681. return nil
  682. }
  683. return tableDirectory.init(value: addObject)
  684. }
  685. @objc func deleteDirectoryAndSubDirectory(serverUrl: String, account: String) {
  686. let realm = try! Realm()
  687. realm.refresh()
  688. let results = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl BEGINSWITH %@", account, serverUrl)
  689. // Delete table Metadata & LocalFile
  690. for result in results {
  691. self.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", result.account, result.serverUrl))
  692. self.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", result.fileID))
  693. }
  694. // Delete table Dirrectory
  695. do {
  696. try realm.write {
  697. realm.delete(results)
  698. }
  699. } catch let error {
  700. print("[LOG] Could not write to database: ", error)
  701. }
  702. }
  703. @objc func setDirectory(serverUrl: String, serverUrlTo: String?, etag: String?, fileID: String?, encrypted: Bool, account: String) {
  704. let realm = try! Realm()
  705. do {
  706. try realm.write {
  707. guard let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first else {
  708. return
  709. }
  710. let directory = tableDirectory.init(value: result)
  711. realm.delete(result)
  712. directory.e2eEncrypted = encrypted
  713. if let etag = etag {
  714. directory.etag = etag
  715. }
  716. if let fileID = fileID {
  717. directory.fileID = fileID
  718. }
  719. if let serverUrlTo = serverUrlTo {
  720. directory.serverUrl = serverUrlTo
  721. }
  722. directory.directoryID = CCUtility.createDirectoyID(fromAccount: account, serverUrl: directory.serverUrl)
  723. realm.add(directory, update: true)
  724. }
  725. } catch let error {
  726. print("[LOG] Could not write to database: ", error)
  727. }
  728. }
  729. @objc func clearDateRead(serverUrl: String, account: String) {
  730. let realm = try! Realm()
  731. do {
  732. try realm.write {
  733. var predicate = NSPredicate()
  734. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl)
  735. guard let result = realm.objects(tableDirectory.self).filter(predicate).first else {
  736. return
  737. }
  738. result.dateReadDirectory = nil
  739. result.etag = ""
  740. realm.add(result, update: true)
  741. }
  742. } catch let error {
  743. print("[LOG] Could not write to database: ", error)
  744. }
  745. }
  746. @objc func getTableDirectory(predicate: NSPredicate) -> tableDirectory? {
  747. let realm = try! Realm()
  748. realm.refresh()
  749. guard let result = realm.objects(tableDirectory.self).filter(predicate).first else {
  750. return nil
  751. }
  752. return tableDirectory.init(value: result)
  753. }
  754. @objc func getTablesDirectory(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableDirectory]? {
  755. let realm = try! Realm()
  756. realm.refresh()
  757. let results = realm.objects(tableDirectory.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  758. if (results.count > 0) {
  759. return Array(results.map { tableDirectory.init(value:$0) })
  760. } else {
  761. return nil
  762. }
  763. }
  764. @objc func setDateReadDirectory(serverUrl: String, account: String) {
  765. let realm = try! Realm()
  766. realm.beginWrite()
  767. guard let result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else {
  768. realm.cancelWrite()
  769. return
  770. }
  771. result.dateReadDirectory = NSDate()
  772. do {
  773. try realm.commitWrite()
  774. } catch let error {
  775. print("[LOG] Could not write to database: ", error)
  776. }
  777. }
  778. @objc func setClearAllDateReadDirectory() {
  779. let realm = try! Realm()
  780. do {
  781. try realm.write {
  782. let results = realm.objects(tableDirectory.self)
  783. for result in results {
  784. result.dateReadDirectory = nil;
  785. result.etag = ""
  786. }
  787. }
  788. } catch let error {
  789. print("[LOG] Could not write to database: ", error)
  790. }
  791. }
  792. @objc func setDirectoryLock(serverUrl: String, lock: Bool, account: String) -> Bool {
  793. let realm = try! Realm()
  794. var update = false
  795. do {
  796. try realm.write {
  797. guard let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first else {
  798. realm.cancelWrite()
  799. return
  800. }
  801. result.lock = lock
  802. update = true
  803. }
  804. } catch let error {
  805. print("[LOG] Could not write to database: ", error)
  806. return false
  807. }
  808. return update
  809. }
  810. @objc func setAllDirectoryUnLock(account: String) {
  811. let realm = try! Realm()
  812. do {
  813. try realm.write {
  814. let results = realm.objects(tableDirectory.self).filter("account = %@", account)
  815. for result in results {
  816. result.lock = false;
  817. }
  818. }
  819. } catch let error {
  820. print("[LOG] Could not write to database: ", error)
  821. }
  822. }
  823. @objc func setDirectory(serverUrl: String, offline: Bool, account: String) {
  824. let realm = try! Realm()
  825. do {
  826. try realm.write {
  827. guard let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first else {
  828. realm.cancelWrite()
  829. return
  830. }
  831. result.offline = offline
  832. }
  833. } catch let error {
  834. print("[LOG] Could not write to database: ", error)
  835. }
  836. }
  837. //MARK: -
  838. //MARK: Table e2e Encryption
  839. @objc func addE2eEncryption(_ e2e: tableE2eEncryption) -> Bool {
  840. guard self.getAccountActive() != nil else {
  841. return false
  842. }
  843. let realm = try! Realm()
  844. do {
  845. try realm.write {
  846. realm.add(e2e, update: true)
  847. }
  848. } catch let error {
  849. print("[LOG] Could not write to database: ", error)
  850. return false
  851. }
  852. return true
  853. }
  854. @objc func deleteE2eEncryption(predicate: NSPredicate) {
  855. guard self.getAccountActive() != nil else {
  856. return
  857. }
  858. let realm = try! Realm()
  859. do {
  860. try realm.write {
  861. let results = realm.objects(tableE2eEncryption.self).filter(predicate)
  862. realm.delete(results)
  863. }
  864. } catch let error {
  865. print("[LOG] Could not write to database: ", error)
  866. }
  867. }
  868. @objc func getE2eEncryption(predicate: NSPredicate) -> tableE2eEncryption? {
  869. guard self.getAccountActive() != nil else {
  870. return nil
  871. }
  872. let realm = try! Realm()
  873. realm.refresh()
  874. guard let result = realm.objects(tableE2eEncryption.self).filter(predicate).sorted(byKeyPath: "metadataKeyIndex", ascending: false).first else {
  875. return nil
  876. }
  877. return tableE2eEncryption.init(value: result)
  878. }
  879. @objc func getE2eEncryptions(predicate: NSPredicate) -> [tableE2eEncryption]? {
  880. guard self.getAccountActive() != nil else {
  881. return nil
  882. }
  883. let realm = try! Realm()
  884. realm.refresh()
  885. let results : Results<tableE2eEncryption>
  886. results = realm.objects(tableE2eEncryption.self).filter(predicate)
  887. if (results.count > 0) {
  888. return Array(results.map { tableE2eEncryption.init(value:$0) })
  889. } else {
  890. return nil
  891. }
  892. }
  893. @objc func renameFileE2eEncryption(serverUrl: String, fileNameIdentifier: String, newFileName: String, newFileNamePath: String) {
  894. guard let tableAccount = self.getAccountActive() else {
  895. return
  896. }
  897. let realm = try! Realm()
  898. realm.beginWrite()
  899. guard let result = realm.objects(tableE2eEncryption.self).filter("account = %@ AND serverUrl = %@ AND fileNameIdentifier = %@", tableAccount.account, serverUrl, fileNameIdentifier).first else {
  900. realm.cancelWrite()
  901. return
  902. }
  903. let object = tableE2eEncryption.init(value: result)
  904. realm.delete(result)
  905. object.fileName = newFileName
  906. object.fileNamePath = newFileNamePath
  907. realm.add(object)
  908. do {
  909. try realm.commitWrite()
  910. } catch let error {
  911. print("[LOG] Could not write to database: ", error)
  912. return
  913. }
  914. return
  915. }
  916. //MARK: -
  917. //MARK: Table e2e Encryption Lock
  918. @objc func getE2ETokenLock(serverUrl: String) -> tableE2eEncryptionLock? {
  919. guard let tableAccount = self.getAccountActive() else {
  920. return nil
  921. }
  922. let realm = try! Realm()
  923. realm.refresh()
  924. guard let result = realm.objects(tableE2eEncryptionLock.self).filter("account = %@ AND serverUrl = %@", tableAccount.account, serverUrl).first else {
  925. return nil
  926. }
  927. return tableE2eEncryptionLock.init(value: result)
  928. }
  929. @objc func setE2ETokenLock(serverUrl: String, fileID: String, token: String) {
  930. guard let tableAccount = self.getAccountActive() else {
  931. return
  932. }
  933. let realm = try! Realm()
  934. realm.beginWrite()
  935. let addObject = tableE2eEncryptionLock()
  936. addObject.account = tableAccount.account
  937. addObject.fileID = fileID
  938. addObject.serverUrl = serverUrl
  939. addObject.token = token
  940. realm.add(addObject, update: true)
  941. do {
  942. try realm.commitWrite()
  943. } catch let error {
  944. print("[LOG] Could not write to database: ", error)
  945. }
  946. }
  947. @objc func deteleE2ETokenLock(serverUrl: String) {
  948. guard let tableAccount = self.getAccountActive() else {
  949. return
  950. }
  951. let realm = try! Realm()
  952. realm.beginWrite()
  953. guard let result = realm.objects(tableE2eEncryptionLock.self).filter("account = %@ AND serverUrl = %@", tableAccount.account, serverUrl).first else {
  954. return
  955. }
  956. realm.delete(result)
  957. do {
  958. try realm.commitWrite()
  959. } catch let error {
  960. print("[LOG] Could not write to database: ", error)
  961. }
  962. }
  963. //MARK: -
  964. //MARK: Table External Sites
  965. @objc func addExternalSites(_ externalSites: OCExternalSites, account: String) {
  966. let realm = try! Realm()
  967. do {
  968. try realm.write {
  969. let addObject = tableExternalSites()
  970. addObject.account = account
  971. addObject.idExternalSite = externalSites.idExternalSite
  972. addObject.icon = externalSites.icon
  973. addObject.lang = externalSites.lang
  974. addObject.name = externalSites.name
  975. addObject.url = externalSites.url
  976. addObject.type = externalSites.type
  977. realm.add(addObject)
  978. }
  979. } catch let error {
  980. print("[LOG] Could not write to database: ", error)
  981. }
  982. }
  983. @objc func deleteExternalSites(account: String) {
  984. let realm = try! Realm()
  985. do {
  986. try realm.write {
  987. let results = realm.objects(tableExternalSites.self).filter("account = %@", account)
  988. realm.delete(results)
  989. }
  990. } catch let error {
  991. print("[LOG] Could not write to database: ", error)
  992. }
  993. }
  994. @objc func getAllExternalSites(account: String) -> [tableExternalSites]? {
  995. let realm = try! Realm()
  996. realm.refresh()
  997. let results = realm.objects(tableExternalSites.self).filter("account = %@", account).sorted(byKeyPath: "idExternalSite", ascending: true)
  998. return Array(results)
  999. }
  1000. //MARK: -
  1001. //MARK: Table GPS
  1002. @objc func addGeocoderLocation(_ location: String, placemarkAdministrativeArea: String, placemarkCountry: String, placemarkLocality: String, placemarkPostalCode: String, placemarkThoroughfare: String, latitude: String, longitude: String) {
  1003. let realm = try! Realm()
  1004. realm.beginWrite()
  1005. // Verify if exists
  1006. guard realm.objects(tableGPS.self).filter("latitude = %@ AND longitude = %@", latitude, longitude).first == nil else {
  1007. realm.cancelWrite()
  1008. return
  1009. }
  1010. // Add new GPS
  1011. let addObject = tableGPS()
  1012. addObject.latitude = latitude
  1013. addObject.location = location
  1014. addObject.longitude = longitude
  1015. addObject.placemarkAdministrativeArea = placemarkAdministrativeArea
  1016. addObject.placemarkCountry = placemarkCountry
  1017. addObject.placemarkLocality = placemarkLocality
  1018. addObject.placemarkPostalCode = placemarkPostalCode
  1019. addObject.placemarkThoroughfare = placemarkThoroughfare
  1020. realm.add(addObject)
  1021. do {
  1022. try realm.commitWrite()
  1023. } catch let error {
  1024. print("[LOG] Could not write to database: ", error)
  1025. }
  1026. }
  1027. @objc func getLocationFromGeoLatitude(_ latitude: String, longitude: String) -> String? {
  1028. let realm = try! Realm()
  1029. realm.refresh()
  1030. guard let result = realm.objects(tableGPS.self).filter("latitude = %@ AND longitude = %@", latitude, longitude).first else {
  1031. return nil
  1032. }
  1033. return result.location
  1034. }
  1035. //MARK: -
  1036. //MARK: Table LocalFile
  1037. @objc func addLocalFile(metadata: tableMetadata) {
  1038. let realm = try! Realm()
  1039. do {
  1040. try realm.write {
  1041. let addObject = tableLocalFile()
  1042. addObject.account = metadata.account
  1043. addObject.date = metadata.date
  1044. addObject.etag = metadata.etag
  1045. addObject.exifDate = NSDate()
  1046. addObject.exifLatitude = "-1"
  1047. addObject.exifLongitude = "-1"
  1048. addObject.fileID = metadata.fileID
  1049. addObject.fileName = metadata.fileName
  1050. addObject.size = metadata.size
  1051. realm.add(addObject, update: true)
  1052. }
  1053. } catch let error {
  1054. print("[LOG] Could not write to database: ", error)
  1055. }
  1056. }
  1057. @objc func deleteLocalFile(predicate: NSPredicate) {
  1058. let realm = try! Realm()
  1059. do {
  1060. try realm.write {
  1061. let results = realm.objects(tableLocalFile.self).filter(predicate)
  1062. realm.delete(results)
  1063. }
  1064. } catch let error {
  1065. print("[LOG] Could not write to database: ", error)
  1066. }
  1067. }
  1068. @objc func setLocalFile(fileID: String, date: NSDate?, exifDate: NSDate?, exifLatitude: String?, exifLongitude: String?, fileName: String?, etag: String?) {
  1069. let realm = try! Realm()
  1070. do {
  1071. try realm.write {
  1072. guard let result = realm.objects(tableLocalFile.self).filter("fileID = %@", fileID).first else {
  1073. realm.cancelWrite()
  1074. return
  1075. }
  1076. if let date = date {
  1077. result.date = date
  1078. }
  1079. if let exifDate = exifDate {
  1080. result.exifDate = exifDate
  1081. }
  1082. if let exifLatitude = exifLatitude {
  1083. result.exifLatitude = exifLatitude
  1084. }
  1085. if let exifLongitude = exifLongitude {
  1086. result.exifLongitude = exifLongitude
  1087. }
  1088. if let fileName = fileName {
  1089. result.fileName = fileName
  1090. }
  1091. if let etag = etag {
  1092. result.etag = etag
  1093. }
  1094. }
  1095. } catch let error {
  1096. print("[LOG] Could not write to database: ", error)
  1097. }
  1098. }
  1099. @objc func getTableLocalFile(predicate: NSPredicate) -> tableLocalFile? {
  1100. let realm = try! Realm()
  1101. realm.refresh()
  1102. guard let result = realm.objects(tableLocalFile.self).filter(predicate).first else {
  1103. return nil
  1104. }
  1105. return tableLocalFile.init(value: result)
  1106. }
  1107. @objc func getTableLocalFiles(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableLocalFile]? {
  1108. let realm = try! Realm()
  1109. realm.refresh()
  1110. let results = realm.objects(tableLocalFile.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1111. if (results.count > 0) {
  1112. return Array(results.map { tableLocalFile.init(value:$0) })
  1113. } else {
  1114. return nil
  1115. }
  1116. }
  1117. @objc func setLocalFile(fileID: String, offline: Bool) {
  1118. let realm = try! Realm()
  1119. do {
  1120. try realm.write {
  1121. guard let result = realm.objects(tableLocalFile.self).filter("fileID = %@", fileID).first else {
  1122. realm.cancelWrite()
  1123. return
  1124. }
  1125. result.offline = offline
  1126. }
  1127. } catch let error {
  1128. print("[LOG] Could not write to database: ", error)
  1129. }
  1130. }
  1131. //MARK: -
  1132. //MARK: Table Metadata
  1133. @objc func addMetadata(_ metadata: tableMetadata) -> tableMetadata? {
  1134. if metadata.isInvalidated {
  1135. return nil
  1136. }
  1137. let serverUrl = metadata.serverUrl
  1138. let account = metadata.account
  1139. let realm = try! Realm()
  1140. do {
  1141. try realm.write {
  1142. realm.add(metadata, update: true)
  1143. }
  1144. } catch let error {
  1145. print("[LOG] Could not write to database: ", error)
  1146. return nil
  1147. }
  1148. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1149. if metadata.isInvalidated {
  1150. return nil
  1151. }
  1152. return tableMetadata.init(value: metadata)
  1153. }
  1154. @objc func addMetadatas(_ metadatas: [tableMetadata]) -> [tableMetadata]? {
  1155. var directoryToClearDate = [String:String]()
  1156. let realm = try! Realm()
  1157. do {
  1158. try realm.write {
  1159. for metadata in metadatas {
  1160. directoryToClearDate[metadata.serverUrl] = metadata.account
  1161. realm.add(metadata, update: true)
  1162. }
  1163. }
  1164. } catch let error {
  1165. print("[LOG] Could not write to database: ", error)
  1166. return nil
  1167. }
  1168. for (serverUrl, account) in directoryToClearDate {
  1169. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1170. }
  1171. return Array(metadatas.map { tableMetadata.init(value:$0) })
  1172. }
  1173. @objc func deleteMetadata(predicate: NSPredicate) {
  1174. var directoryToClearDate = [String:String]()
  1175. let realm = try! Realm()
  1176. realm.beginWrite()
  1177. let results = realm.objects(tableMetadata.self).filter(predicate)
  1178. for result in results {
  1179. directoryToClearDate[result.serverUrl] = result.account
  1180. }
  1181. realm.delete(results)
  1182. do {
  1183. try realm.commitWrite()
  1184. } catch let error {
  1185. print("[LOG] Could not write to database: ", error)
  1186. return
  1187. }
  1188. for (serverUrl, account) in directoryToClearDate {
  1189. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1190. }
  1191. }
  1192. @objc func moveMetadata(fileID: String, serverUrlTo: String) {
  1193. let realm = try! Realm()
  1194. do {
  1195. try realm.write {
  1196. let results = realm.objects(tableMetadata.self).filter("fileID == %@", fileID)
  1197. for result in results {
  1198. result.serverUrl = serverUrlTo
  1199. }
  1200. }
  1201. } catch let error {
  1202. print("[LOG] Could not write to database: ", error)
  1203. return
  1204. }
  1205. }
  1206. @objc func addMetadataServerUrl(fileID: String, serverUrl: String) {
  1207. let realm = try! Realm()
  1208. do {
  1209. try realm.write {
  1210. let results = realm.objects(tableMetadata.self).filter("fileID == %@", fileID)
  1211. for result in results {
  1212. result.serverUrl = serverUrl
  1213. }
  1214. }
  1215. } catch let error {
  1216. print("[LOG] Could not write to database: ", error)
  1217. return
  1218. }
  1219. }
  1220. @objc func renameMetadata(fileNameTo: String, fileID: String) -> tableMetadata? {
  1221. var result :tableMetadata?
  1222. let realm = try! Realm()
  1223. do {
  1224. try realm.write {
  1225. result = realm.objects(tableMetadata.self).filter("fileID == %@", fileID).first
  1226. if result != nil {
  1227. result!.fileName = fileNameTo
  1228. result!.fileNameView = fileNameTo
  1229. }
  1230. }
  1231. } catch let error {
  1232. print("[LOG] Could not write to database: ", error)
  1233. return nil
  1234. }
  1235. if result == nil {
  1236. return nil
  1237. }
  1238. self.setDateReadDirectory(serverUrl: result!.serverUrl, account: result!.account)
  1239. return tableMetadata.init(value: result!)
  1240. }
  1241. @objc func updateMetadata(_ metadata: tableMetadata) -> tableMetadata? {
  1242. let account = metadata.account
  1243. let serverUrl = metadata.serverUrl
  1244. let realm = try! Realm()
  1245. do {
  1246. try realm.write {
  1247. realm.add(metadata, update: true)
  1248. }
  1249. } catch let error {
  1250. print("[LOG] Could not write to database: ", error)
  1251. return nil
  1252. }
  1253. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1254. return tableMetadata.init(value: metadata)
  1255. }
  1256. @objc func copyMetadata(_ object: tableMetadata) -> tableMetadata? {
  1257. return tableMetadata.init(value: object)
  1258. }
  1259. @objc func setMetadataSession(_ session: String?, sessionError: String?, sessionSelector: String?, sessionTaskIdentifier: Int, status: Int, predicate: NSPredicate) {
  1260. let realm = try! Realm()
  1261. realm.beginWrite()
  1262. guard let result = realm.objects(tableMetadata.self).filter(predicate).first else {
  1263. realm.cancelWrite()
  1264. return
  1265. }
  1266. if let session = session {
  1267. result.session = session
  1268. }
  1269. if let sessionError = sessionError {
  1270. result.sessionError = sessionError
  1271. }
  1272. if let sessionSelector = sessionSelector {
  1273. result.sessionSelector = sessionSelector
  1274. }
  1275. result.sessionTaskIdentifier = sessionTaskIdentifier
  1276. result.status = status
  1277. let account = result.account
  1278. let serverUrl = result.serverUrl
  1279. do {
  1280. try realm.commitWrite()
  1281. } catch let error {
  1282. print("[LOG] Could not write to database: ", error)
  1283. return
  1284. }
  1285. // Update Date Read Directory
  1286. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1287. }
  1288. @objc func setMetadataFavorite(fileID: String, favorite: Bool) {
  1289. let realm = try! Realm()
  1290. realm.beginWrite()
  1291. guard let result = realm.objects(tableMetadata.self).filter("fileID == %@", fileID).first else {
  1292. realm.cancelWrite()
  1293. return
  1294. }
  1295. result.favorite = favorite
  1296. let account = result.account
  1297. let serverUrl = result.serverUrl
  1298. do {
  1299. try realm.commitWrite()
  1300. } catch let error {
  1301. print("[LOG] Could not write to database: ", error)
  1302. return
  1303. }
  1304. // Update Date Read Directory
  1305. setDateReadDirectory(serverUrl: serverUrl, account: account)
  1306. }
  1307. @objc func setMetadataFileNameView(serverUrl: String, fileName: String, newFileNameView: String, account: String) {
  1308. let realm = try! Realm()
  1309. realm.beginWrite()
  1310. guard let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first else {
  1311. realm.cancelWrite()
  1312. return
  1313. }
  1314. result.fileNameView = newFileNameView
  1315. let account = result.account
  1316. let serverUrl = result.serverUrl
  1317. do {
  1318. try realm.commitWrite()
  1319. } catch let error {
  1320. print("[LOG] Could not write to database: ", error)
  1321. return
  1322. }
  1323. // Update Date Read Directory
  1324. setDateReadDirectory(serverUrl: serverUrl, account: account)
  1325. }
  1326. @objc func getMetadata(predicate: NSPredicate) -> tableMetadata? {
  1327. let realm = try! Realm()
  1328. realm.refresh()
  1329. guard let result = realm.objects(tableMetadata.self).filter(predicate).first else {
  1330. return nil
  1331. }
  1332. return tableMetadata.init(value: result)
  1333. }
  1334. @objc func getMetadata(predicate: NSPredicate, sorted: String, ascending: Bool) -> tableMetadata? {
  1335. let realm = try! Realm()
  1336. realm.refresh()
  1337. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1338. if (results.count > 0) {
  1339. return tableMetadata.init(value: results[0])
  1340. } else {
  1341. return nil
  1342. }
  1343. }
  1344. @objc func getMetadatas(predicate: NSPredicate, sorted: String?, ascending: Bool) -> [tableMetadata]? {
  1345. let realm = try! Realm()
  1346. realm.refresh()
  1347. let results : Results<tableMetadata>
  1348. if let sorted = sorted {
  1349. if (tableMetadata().objectSchema.properties.contains { $0.name == sorted }) {
  1350. results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1351. } else {
  1352. results = realm.objects(tableMetadata.self).filter(predicate)
  1353. }
  1354. } else {
  1355. results = realm.objects(tableMetadata.self).filter(predicate)
  1356. }
  1357. if (results.count > 0) {
  1358. return Array(results.map { tableMetadata.init(value:$0) })
  1359. } else {
  1360. return nil
  1361. }
  1362. }
  1363. @objc func getMetadataAtIndex(predicate: NSPredicate, sorted: String, ascending: Bool, index: Int) -> tableMetadata? {
  1364. let realm = try! Realm()
  1365. realm.refresh()
  1366. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1367. if (results.count > 0 && results.count > index) {
  1368. return tableMetadata.init(value: results[index])
  1369. } else {
  1370. return nil
  1371. }
  1372. }
  1373. @objc func getMetadataInSessionFromFileName(_ fileName: String, serverUrl: String, taskIdentifier: Int) -> tableMetadata? {
  1374. let realm = try! Realm()
  1375. realm.refresh()
  1376. guard let result = realm.objects(tableMetadata.self).filter("serverUrl == %@ AND fileName == %@ AND session != '' AND sessionTaskIdentifier == %d", serverUrl, fileName, taskIdentifier).first else {
  1377. return nil
  1378. }
  1379. return tableMetadata.init(value: result)
  1380. }
  1381. @objc func getTableMetadatasDirectoryFavoriteIdentifierRank(account: String) -> [String:NSNumber] {
  1382. var listIdentifierRank = [String:NSNumber]()
  1383. let realm = try! Realm()
  1384. realm.refresh()
  1385. var counter = 10 as Int64
  1386. let results = realm.objects(tableMetadata.self).filter("account = %@ AND directory = true AND favorite = true", account).sorted(byKeyPath: "fileNameView", ascending: true)
  1387. for result in results {
  1388. counter += 1
  1389. listIdentifierRank[result.fileID] = NSNumber(value: Int64(counter))
  1390. }
  1391. return listIdentifierRank
  1392. }
  1393. @objc func clearMetadatasUpload(account: String) {
  1394. let realm = try! Realm()
  1395. do {
  1396. try realm.write {
  1397. let results = realm.objects(tableMetadata.self).filter("account == %@ AND (status == %d OR status == %@)", account, k_metadataStatusWaitUpload, k_metadataStatusUploadError)
  1398. realm.delete(results)
  1399. }
  1400. } catch let error {
  1401. print("[LOG] Could not write to database: ", error)
  1402. }
  1403. }
  1404. @objc func initNewMetadata(_ metadata: tableMetadata) -> tableMetadata {
  1405. return tableMetadata.init(value: metadata)
  1406. }
  1407. //MARK: -
  1408. //MARK: Table Photos
  1409. @objc func getTablePhotos(addMetadatasFromUpload: [tableMetadata], account: String) -> [tableMetadata]? {
  1410. let realm = try! Realm()
  1411. realm.refresh()
  1412. let predicate = NSPredicate(format: "account == %@", account)
  1413. let results = realm.objects(tablePhotos.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  1414. if (results.count > 0) {
  1415. var returnMetadatas = Array(results.map { tableMetadata.init(value:$0) })
  1416. for metadata in addMetadatasFromUpload {
  1417. let result = realm.objects(tablePhotos.self).filter("fileID == %@", metadata.fileID).first
  1418. if result == nil {
  1419. returnMetadatas.append(metadata)
  1420. }
  1421. }
  1422. return returnMetadatas
  1423. } else {
  1424. return nil
  1425. }
  1426. }
  1427. @objc func getTablePhoto(predicate: NSPredicate) -> tableMetadata? {
  1428. let realm = try! Realm()
  1429. realm.refresh()
  1430. guard let result = realm.objects(tablePhotos.self).filter(predicate).first else {
  1431. return nil
  1432. }
  1433. return tableMetadata.init(value: result)
  1434. }
  1435. @objc func getTablePhotos(predicate: NSPredicate) -> [tableMetadata]? {
  1436. let realm = try! Realm()
  1437. realm.refresh()
  1438. let results = realm.objects(tablePhotos.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  1439. if (results.count > 0) {
  1440. return Array(results.map { tableMetadata.init(value:$0) })
  1441. } else {
  1442. return nil
  1443. }
  1444. }
  1445. @objc func createTablePhotos(_ metadatas: [tableMetadata], lteDate: Date, gteDate: Date,account: String) {
  1446. let realm = try! Realm()
  1447. realm.refresh()
  1448. do {
  1449. try realm.write {
  1450. // DELETE ALL
  1451. let results = realm.objects(tablePhotos.self).filter("account = %@ AND date >= %@ AND date <= %@", account, gteDate, lteDate)
  1452. realm.delete(results)
  1453. // INSERT ALL
  1454. let photos = Array(metadatas.map { tablePhotos.init(value:$0) })
  1455. realm.add(photos, update: true)
  1456. }
  1457. } catch let error {
  1458. print("[LOG] Could not write to database: ", error)
  1459. realm.cancelWrite()
  1460. }
  1461. }
  1462. @objc func deletePhotos(fileID: String) {
  1463. let realm = try! Realm()
  1464. realm.beginWrite()
  1465. let results = realm.objects(tablePhotos.self).filter("fileID = %@", fileID)
  1466. realm.delete(results)
  1467. do {
  1468. try realm.commitWrite()
  1469. } catch let error {
  1470. print("[LOG] Could not write to database: ", error)
  1471. return
  1472. }
  1473. }
  1474. //MARK: -
  1475. //MARK: Table Photo Library
  1476. @objc func addPhotoLibrary(_ assets: [PHAsset], account: String) -> Bool {
  1477. let realm = try! Realm()
  1478. if realm.isInWriteTransaction {
  1479. print("[LOG] Could not write to database, addPhotoLibrary is already in write transaction")
  1480. return false
  1481. } else {
  1482. do {
  1483. try realm.write {
  1484. var creationDateString = ""
  1485. for asset in assets {
  1486. let addObject = tablePhotoLibrary()
  1487. addObject.account = account
  1488. addObject.assetLocalIdentifier = asset.localIdentifier
  1489. addObject.mediaType = asset.mediaType.rawValue
  1490. if let creationDate = asset.creationDate {
  1491. addObject.creationDate = creationDate as NSDate
  1492. creationDateString = String(describing: creationDate)
  1493. } else {
  1494. creationDateString = ""
  1495. }
  1496. if let modificationDate = asset.modificationDate {
  1497. addObject.modificationDate = modificationDate as NSDate
  1498. }
  1499. addObject.idAsset = "\(account)\(asset.localIdentifier)\(creationDateString)"
  1500. realm.add(addObject, update: true)
  1501. }
  1502. }
  1503. } catch let error {
  1504. print("[LOG] Could not write to database: ", error)
  1505. return false
  1506. }
  1507. }
  1508. return true
  1509. }
  1510. @objc func getPhotoLibraryIdAsset(image: Bool, video: Bool, account: String) -> [String]? {
  1511. let realm = try! Realm()
  1512. realm.refresh()
  1513. var predicate = NSPredicate()
  1514. if (image && video) {
  1515. predicate = NSPredicate(format: "account == %@ AND (mediaType == %i OR mediaType == %i)", account, PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
  1516. } else if (image) {
  1517. predicate = NSPredicate(format: "account == %@ AND mediaType == %i", account, PHAssetMediaType.image.rawValue)
  1518. } else if (video) {
  1519. predicate = NSPredicate(format: "account == %@ AND mediaType == %i", account, PHAssetMediaType.video.rawValue)
  1520. }
  1521. let results = realm.objects(tablePhotoLibrary.self).filter(predicate)
  1522. let idsAsset = results.map { $0.idAsset }
  1523. return Array(idsAsset)
  1524. }
  1525. @objc func getPhotoLibrary(predicate: NSPredicate) -> [tablePhotoLibrary] {
  1526. let realm = try! Realm()
  1527. let results = realm.objects(tablePhotoLibrary.self).filter(predicate)
  1528. return Array(results.map { tablePhotoLibrary.init(value:$0) })
  1529. }
  1530. //MARK: -
  1531. //MARK: Table Share
  1532. @objc func addShareLink(_ share: String, fileName: String, serverUrl: String, account: String) -> [String:String]? {
  1533. let realm = try! Realm()
  1534. realm.beginWrite()
  1535. // Verify if exists
  1536. let result = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", account, fileName, serverUrl).first
  1537. if result != nil {
  1538. result?.shareLink = share
  1539. } else {
  1540. // Add new
  1541. let addObject = tableShare()
  1542. addObject.account = account
  1543. addObject.fileName = fileName
  1544. addObject.serverUrl = serverUrl
  1545. addObject.shareLink = share
  1546. realm.add(addObject)
  1547. }
  1548. do {
  1549. try realm.commitWrite()
  1550. } catch let error {
  1551. print("[LOG] Could not write to database: ", error)
  1552. return nil
  1553. }
  1554. return ["\(serverUrl)\(fileName)" : share]
  1555. }
  1556. @objc func addShareUserAndGroup(_ share: String, fileName: String, serverUrl: String, account: String) -> [String:String]? {
  1557. let realm = try! Realm()
  1558. realm.beginWrite()
  1559. // Verify if exists
  1560. let result = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", account, fileName, serverUrl).first
  1561. if result != nil {
  1562. result?.shareUserAndGroup = share
  1563. } else {
  1564. // Add new
  1565. let addObject = tableShare()
  1566. addObject.account = account
  1567. addObject.fileName = fileName
  1568. addObject.serverUrl = serverUrl
  1569. addObject.shareUserAndGroup = share
  1570. realm.add(addObject)
  1571. }
  1572. do {
  1573. try realm.commitWrite()
  1574. } catch let error {
  1575. print("[LOG] Could not write to database: ", error)
  1576. return nil
  1577. }
  1578. return ["\(serverUrl)\(fileName)" : share]
  1579. }
  1580. @objc func unShare(_ share: String, fileName: String, serverUrl: String, sharesLink: [String:String], sharesUserAndGroup: [String:String], account: String) -> [Any]? {
  1581. var sharesLink = sharesLink
  1582. var sharesUserAndGroup = sharesUserAndGroup
  1583. let realm = try! Realm()
  1584. realm.beginWrite()
  1585. let results = realm.objects(tableShare.self).filter("account = %@ AND (shareLink CONTAINS %@ OR shareUserAndGroup CONTAINS %@)", account, share, share)
  1586. if (results.count > 0) {
  1587. let result = results[0]
  1588. if (result.shareLink.contains(share)) {
  1589. result.shareLink = ""
  1590. }
  1591. if (result.shareUserAndGroup.contains(share)) {
  1592. var shares : [String] = result.shareUserAndGroup.components(separatedBy: ",")
  1593. if let index = shares.index(of:share) {
  1594. shares.remove(at: index)
  1595. }
  1596. result.shareUserAndGroup = shares.joined(separator: ",")
  1597. }
  1598. if (result.shareLink.count > 0) {
  1599. sharesLink.updateValue(result.shareLink, forKey:"\(serverUrl)\(fileName)")
  1600. } else {
  1601. sharesLink.removeValue(forKey: "\(serverUrl)\(fileName)")
  1602. }
  1603. if (result.shareUserAndGroup.count > 0) {
  1604. sharesUserAndGroup.updateValue(result.shareUserAndGroup, forKey:"\(serverUrl)\(fileName)")
  1605. } else {
  1606. sharesUserAndGroup.removeValue(forKey: "\(serverUrl)\(fileName)")
  1607. }
  1608. if (result.shareLink.count == 0 && result.shareUserAndGroup.count == 0) {
  1609. realm.delete(result)
  1610. }
  1611. }
  1612. do {
  1613. try realm.commitWrite()
  1614. } catch let error {
  1615. print("[LOG] Could not write to database: ", error)
  1616. return nil
  1617. }
  1618. return [sharesLink, sharesUserAndGroup]
  1619. }
  1620. @objc func removeShareActiveAccount(account: String) {
  1621. let realm = try! Realm()
  1622. do {
  1623. try realm.write {
  1624. let results = realm.objects(tableShare.self).filter("account = %@", account)
  1625. realm.delete(results)
  1626. }
  1627. } catch let error {
  1628. print("[LOG] Could not write to database: ", error)
  1629. }
  1630. }
  1631. @objc func updateShare(_ items: [String:OCSharedDto], activeUrl: String, account: String) -> [Any]? {
  1632. var sharesLink = [String:String]()
  1633. var sharesUserAndGroup = [String:String]()
  1634. self.removeShareActiveAccount(account: account)
  1635. var itemsLink = [OCSharedDto]()
  1636. var itemsUsersAndGroups = [OCSharedDto]()
  1637. for (_, itemOCSharedDto) in items {
  1638. if (itemOCSharedDto.shareType == Int(shareTypeLink.rawValue)) {
  1639. itemsLink.append(itemOCSharedDto)
  1640. }
  1641. if (itemOCSharedDto.shareWith.count > 0 && (itemOCSharedDto.shareType == Int(shareTypeUser.rawValue) || itemOCSharedDto.shareType == Int(shareTypeGroup.rawValue) || itemOCSharedDto.shareType == Int(shareTypeRemote.rawValue) )) {
  1642. itemsUsersAndGroups.append(itemOCSharedDto)
  1643. }
  1644. }
  1645. // Manage sharesLink
  1646. for itemOCSharedDto in itemsLink {
  1647. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(itemOCSharedDto.path!)"
  1648. let fileName = NSString(string: fullPath).lastPathComponent
  1649. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.count - fileName.count - 1))
  1650. if serverUrl.hasSuffix("/") {
  1651. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.count - 1))
  1652. }
  1653. if itemOCSharedDto.idRemoteShared > 0 {
  1654. let sharesLinkReturn = self.addShareLink("\(itemOCSharedDto.idRemoteShared)", fileName: fileName, serverUrl: serverUrl, account: account)
  1655. if sharesLinkReturn != nil {
  1656. for (key,value) in sharesLinkReturn! {
  1657. sharesLink.updateValue(value, forKey:key)
  1658. }
  1659. }
  1660. }
  1661. }
  1662. // Manage sharesUserAndGroup
  1663. var paths = [String:[String]]()
  1664. for itemOCSharedDto in itemsUsersAndGroups {
  1665. if paths[itemOCSharedDto.path] != nil {
  1666. var share : [String] = paths[itemOCSharedDto.path]!
  1667. share.append("\(itemOCSharedDto.idRemoteShared)")
  1668. paths[itemOCSharedDto.path] = share
  1669. } else {
  1670. paths[itemOCSharedDto.path] = ["\(itemOCSharedDto.idRemoteShared)"]
  1671. }
  1672. }
  1673. for (path, idsRemoteSharedArray) in paths {
  1674. let idsRemoteShared = idsRemoteSharedArray.joined(separator: ",")
  1675. print("[LOG] share \(String(describing: idsRemoteShared))")
  1676. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(path)"
  1677. let fileName = NSString(string: fullPath).lastPathComponent
  1678. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.count - fileName.count - 1))
  1679. if serverUrl.hasSuffix("/") {
  1680. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.count - 1))
  1681. }
  1682. let sharesUserAndGroupReturn = self.addShareUserAndGroup(idsRemoteShared, fileName: fileName, serverUrl: serverUrl, account: account)
  1683. if sharesUserAndGroupReturn != nil {
  1684. for (key,value) in sharesUserAndGroupReturn! {
  1685. sharesUserAndGroup.updateValue(value, forKey:key)
  1686. }
  1687. }
  1688. }
  1689. return [sharesLink, sharesUserAndGroup]
  1690. }
  1691. @objc func getShares(account: String) -> [Any]? {
  1692. var sharesLink = [String:String]()
  1693. var sharesUserAndGroup = [String:String]()
  1694. let realm = try! Realm()
  1695. let results = realm.objects(tableShare.self).filter("account = %@", account)
  1696. for resultShare in results {
  1697. if (resultShare.shareLink.count > 0) {
  1698. sharesLink = [resultShare.shareLink: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  1699. }
  1700. if (resultShare.shareUserAndGroup.count > 0) {
  1701. sharesUserAndGroup = [resultShare.shareUserAndGroup: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  1702. }
  1703. }
  1704. return [sharesLink, sharesUserAndGroup]
  1705. }
  1706. @objc func getTableShares(account: String) -> [tableShare]? {
  1707. let realm = try! Realm()
  1708. realm.refresh()
  1709. let results = realm.objects(tableShare.self).filter("account = %@", account).sorted(byKeyPath: "fileName", ascending: true)
  1710. return Array(results)
  1711. }
  1712. //MARK: -
  1713. //MARK: Table Tag
  1714. @objc func addTag(_ fileID: String ,tagIOS: Data?, account: String) {
  1715. let realm = try! Realm()
  1716. do {
  1717. try realm.write {
  1718. // Add new
  1719. let addObject = tableTag()
  1720. addObject.account = account
  1721. addObject.fileID = fileID
  1722. addObject.tagIOS = tagIOS
  1723. realm.add(addObject, update: true)
  1724. }
  1725. } catch let error {
  1726. print("[LOG] Could not write to database: ", error)
  1727. }
  1728. }
  1729. @objc func deleteTag(_ fileID: String) {
  1730. let realm = try! Realm()
  1731. realm.beginWrite()
  1732. guard let result = realm.objects(tableTag.self).filter("fileID == %@", fileID).first else {
  1733. realm.cancelWrite()
  1734. return
  1735. }
  1736. realm.delete(result)
  1737. do {
  1738. try realm.commitWrite()
  1739. } catch let error {
  1740. print("[LOG] Could not write to database: ", error)
  1741. }
  1742. }
  1743. @objc func getTags(predicate: NSPredicate) -> [tableTag] {
  1744. let realm = try! Realm()
  1745. realm.refresh()
  1746. let results = realm.objects(tableTag.self).filter(predicate)
  1747. return Array(results.map { tableTag.init(value:$0) })
  1748. }
  1749. @objc func getTag(predicate: NSPredicate) -> tableTag? {
  1750. let realm = try! Realm()
  1751. realm.refresh()
  1752. guard let result = realm.objects(tableTag.self).filter(predicate).first else {
  1753. return nil
  1754. }
  1755. return tableTag.init(value: result)
  1756. }
  1757. //MARK: -
  1758. //MARK: Table Trash
  1759. @objc func addTrashs(_ trashs: [tableTrash]) {
  1760. let realm = try! Realm()
  1761. do {
  1762. try realm.write {
  1763. for trash in trashs {
  1764. realm.add(trash, update: true)
  1765. }
  1766. }
  1767. } catch let error {
  1768. print("[LOG] Could not write to database: ", error)
  1769. return
  1770. }
  1771. }
  1772. @objc func deleteTrash(filePath: String, account: String) {
  1773. let realm = try! Realm()
  1774. realm.beginWrite()
  1775. let results = realm.objects(tableTrash.self).filter("account = %@ AND filePath = %@", account, filePath)
  1776. realm.delete(results)
  1777. do {
  1778. try realm.commitWrite()
  1779. } catch let error {
  1780. print("[LOG] Could not write to database: ", error)
  1781. }
  1782. }
  1783. @objc func deleteTrash(fileID: String?, account: String) {
  1784. let realm = try! Realm()
  1785. var predicate = NSPredicate()
  1786. realm.beginWrite()
  1787. if fileID == nil {
  1788. predicate = NSPredicate(format: "account == %@", account)
  1789. } else {
  1790. predicate = NSPredicate(format: "account = %@ AND fileID = %@", account, fileID!)
  1791. }
  1792. let result = realm.objects(tableTrash.self).filter(predicate)
  1793. realm.delete(result)
  1794. do {
  1795. try realm.commitWrite()
  1796. } catch let error {
  1797. print("[LOG] Could not write to database: ", error)
  1798. }
  1799. }
  1800. @objc func getTrash(filePath: String, sorted: String, ascending: Bool, account: String) -> [tableTrash]? {
  1801. let realm = try! Realm()
  1802. realm.refresh()
  1803. let results = realm.objects(tableTrash.self).filter("account = %@ AND filePath = %@", account, filePath).sorted(byKeyPath: sorted, ascending: ascending)
  1804. return Array(results.map { tableTrash.init(value:$0) })
  1805. }
  1806. @objc func getTrashItem(fileID: String, account: String) -> tableTrash? {
  1807. let realm = try! Realm()
  1808. realm.refresh()
  1809. guard let result = realm.objects(tableTrash.self).filter("account = %@ AND fileID = %@", account, fileID).first else {
  1810. return nil
  1811. }
  1812. return tableTrash.init(value: result)
  1813. }
  1814. //MARK: -
  1815. }