NCManageDatabase.swift 81 KB

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