NCManageDatabase.swift 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533
  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(_ table: Object) -> Any {
  156. // id tradeReference = [[NCManageDatabase sharedInstance] getThreadConfined:metadata];
  157. return ThreadSafeReference(to: table)
  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(_ table: Object) -> Bool {
  165. return table.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. let dict = activity.subject_rich[1] as! [String:AnyObject]
  453. for (key, value) in dict {
  454. let addObjectActivitySubjectRich = tableActivitySubjectRich()
  455. let dict = value as! [String:AnyObject]
  456. addObjectActivitySubjectRich.account = account
  457. addObjectActivitySubjectRich.idPrimaryKey = account + String(activity.idActivity) + key
  458. addObjectActivitySubjectRich.key = key
  459. addObjectActivitySubjectRich.idActivity = activity.idActivity
  460. addObjectActivitySubjectRich.id = dict["id"] as? String ?? ""
  461. addObjectActivitySubjectRich.link = dict["link"] as? String ?? ""
  462. addObjectActivitySubjectRich.name = dict["name"] as? String ?? ""
  463. addObjectActivitySubjectRich.path = dict["path"] as? String ?? ""
  464. addObjectActivitySubjectRich.type = dict["type"] as? String ?? ""
  465. realm.add(addObjectActivitySubjectRich, update: true)
  466. }
  467. }
  468. }
  469. if activity.previews.count > 0 {
  470. for case let activityPreview as [String:AnyObject] in activity.previews {
  471. let addObjectActivityPreview = tableActivityPreview()
  472. addObjectActivityPreview.account = account
  473. addObjectActivityPreview.idActivity = activity.idActivity
  474. addObjectActivityPreview.fileId = activityPreview["fileId"] as! Int
  475. addObjectActivityPreview.idPrimaryKey = account + String(activity.idActivity) + String(addObjectActivityPreview.fileId)
  476. addObjectActivityPreview.source = activityPreview["source"] as? String ?? ""
  477. addObjectActivityPreview.link = activityPreview["link"] as? String ?? ""
  478. addObjectActivityPreview.mimeType = activityPreview["mimeType"] as? String ?? ""
  479. addObjectActivityPreview.view = activityPreview["view"] as? String ?? ""
  480. addObjectActivityPreview.isMimeTypeIcon = activityPreview["isMimeTypeIcon"] as! Bool
  481. realm.add(addObjectActivityPreview, update: true)
  482. }
  483. }
  484. addObjectActivity.icon = activity.icon
  485. addObjectActivity.link = activity.link
  486. addObjectActivity.message = activity.message
  487. addObjectActivity.objectType = activity.object_type
  488. addObjectActivity.objectId = activity.object_id
  489. addObjectActivity.objectName = activity.object_name
  490. realm.add(addObjectActivity, update: true)
  491. }
  492. }
  493. } catch let error {
  494. print("[LOG] Could not write to database: ", error)
  495. }
  496. }
  497. @objc func getActivity(predicate: NSPredicate) -> [tableActivity] {
  498. let realm = try! Realm()
  499. realm.refresh()
  500. let results = realm.objects(tableActivity.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  501. return Array(results.map { tableActivity.init(value:$0) })
  502. }
  503. @objc func getActivitySubjectRich(account: String, idActivity: Int, key: String) -> tableActivitySubjectRich? {
  504. let realm = try! Realm()
  505. realm.refresh()
  506. let results = realm.objects(tableActivitySubjectRich.self).filter("account = %@ && idActivity == %d && key = %@", account, idActivity, key).first
  507. return results.map { tableActivitySubjectRich.init(value:$0) }
  508. }
  509. @objc func getActivitySubjectRich(account: String, idActivity: Int, id: String) -> tableActivitySubjectRich? {
  510. let realm = try! Realm()
  511. realm.refresh()
  512. let results = realm.objects(tableActivitySubjectRich.self).filter("account = %@ && idActivity == %d && id == %@", account, idActivity, id).first
  513. return results.map { tableActivitySubjectRich.init(value:$0) }
  514. }
  515. @objc func getActivityPreview(account: String, idActivity: Int) -> [tableActivityPreview] {
  516. let realm = try! Realm()
  517. realm.refresh()
  518. let results = realm.objects(tableActivityPreview.self).filter("account = %@ && idActivity == %d", account, idActivity)
  519. return Array(results.map { tableActivityPreview.init(value:$0) })
  520. }
  521. @objc func getActivityLastIdActivity(account: String) -> Int {
  522. let realm = try! Realm()
  523. realm.refresh()
  524. if let entities = realm.objects(tableActivity.self).filter("account = %@", account).max(by: { $0.idActivity < $1.idActivity }) {
  525. return entities.idActivity
  526. }
  527. return 0
  528. }
  529. @objc func addActivityClient(_ file: String, fileID: String, action: String, selector: String, note: String, type: String, verbose: Bool, activeUrl: String?) {
  530. /*
  531. guard let tableAccount = self.getAccountActive() else {
  532. return
  533. }
  534. var noteReplacing : String = ""
  535. if let activeUrl = activeUrl {
  536. noteReplacing = note.replacingOccurrences(of: "\(activeUrl)\(k_webDAV)", with: "")
  537. }
  538. noteReplacing = note.replacingOccurrences(of: "\(k_domain_session_queue).", with: "")
  539. let realm = try! Realm()
  540. if realm.isInWriteTransaction {
  541. print("[LOG] Could not write to database, addActivityClient is already in write transaction")
  542. } else {
  543. do {
  544. try realm.write {
  545. // Add new Activity
  546. let addObject = tableActivity()
  547. addObject.account = tableAccount.account
  548. addObject.action = action
  549. addObject.file = file
  550. addObject.fileID = fileID
  551. addObject.note = noteReplacing
  552. addObject.selector = selector
  553. addObject.type = type
  554. addObject.verbose = verbose
  555. realm.add(addObject)
  556. }
  557. } catch let error {
  558. print("[LOG] Could not write to database: ", error)
  559. }
  560. }
  561. print("[LOG] " + note)
  562. */
  563. }
  564. //MARK: -
  565. //MARK: Table Capabilities
  566. @objc func addCapabilities(_ capabilities: OCCapabilities, account: String) {
  567. let realm = try! Realm()
  568. do {
  569. try realm.write {
  570. let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first
  571. var resultCapabilities = tableCapabilities()
  572. if let result = result {
  573. resultCapabilities = result
  574. }
  575. resultCapabilities.account = account
  576. resultCapabilities.themingBackground = capabilities.themingBackground
  577. resultCapabilities.themingBackgroundDefault = capabilities.themingBackgroundDefault
  578. resultCapabilities.themingBackgroundPlain = capabilities.themingBackgroundPlain
  579. resultCapabilities.themingColor = capabilities.themingColor
  580. resultCapabilities.themingColorElement = capabilities.themingColorElement
  581. resultCapabilities.themingColorText = capabilities.themingColorText
  582. resultCapabilities.themingLogo = capabilities.themingLogo
  583. resultCapabilities.themingName = capabilities.themingName
  584. resultCapabilities.themingSlogan = capabilities.themingSlogan
  585. resultCapabilities.themingUrl = capabilities.themingUrl
  586. resultCapabilities.versionMajor = capabilities.versionMajor
  587. resultCapabilities.versionMinor = capabilities.versionMinor
  588. resultCapabilities.versionMicro = capabilities.versionMicro
  589. resultCapabilities.versionString = capabilities.versionString
  590. resultCapabilities.endToEndEncryption = capabilities.isEndToEndEncryptionEnabled
  591. resultCapabilities.endToEndEncryptionVersion = capabilities.endToEndEncryptionVersion
  592. resultCapabilities.richdocumentsMimetypes.removeAll()
  593. for mimeType in capabilities.richdocumentsMimetypes {
  594. resultCapabilities.richdocumentsMimetypes.append(mimeType as! String)
  595. }
  596. resultCapabilities.richdocumentsDirectEditing = capabilities.richdocumentsDirectEditing
  597. if result == nil {
  598. realm.add(resultCapabilities)
  599. }
  600. }
  601. } catch let error {
  602. print("[LOG] Could not write to database: ", error)
  603. }
  604. }
  605. @objc func getCapabilites(account: String) -> tableCapabilities? {
  606. let realm = try! Realm()
  607. realm.refresh()
  608. return realm.objects(tableCapabilities.self).filter("account = %@", account).first
  609. }
  610. @objc func getServerVersion(account: String) -> Int {
  611. let realm = try! Realm()
  612. realm.refresh()
  613. guard let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  614. return 0
  615. }
  616. return result.versionMajor
  617. }
  618. @objc func getEndToEndEncryptionVersion(account: String) -> Float {
  619. let realm = try! Realm()
  620. realm.refresh()
  621. guard let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  622. return 0
  623. }
  624. return Float(result.endToEndEncryptionVersion)!
  625. }
  626. @objc func compareServerVersion(_ versionCompare: String, account: String) -> Int {
  627. let realm = try! Realm()
  628. guard let capabilities = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  629. return -1
  630. }
  631. let versionServer = capabilities.versionString
  632. var v1 = versionServer.split(separator:".").map { Int(String($0)) }
  633. var v2 = versionCompare.split(separator:".").map { Int(String($0)) }
  634. var result = 0
  635. for i in 0..<max(v1.count,v2.count) {
  636. let left = i >= v1.count ? 0 : v1[i]
  637. let right = i >= v2.count ? 0 : v2[i]
  638. if (left == right) {
  639. result = 0
  640. } else if left! > right! {
  641. return 1
  642. } else if right! > left! {
  643. return -1
  644. }
  645. }
  646. return result
  647. }
  648. @objc func getRichdocumentsMimetypes(account: String) -> [String]? {
  649. let realm = try! Realm()
  650. realm.refresh()
  651. guard let result = realm.objects(tableCapabilities.self).filter("account = %@", account).first else {
  652. return nil
  653. }
  654. return Array(result.richdocumentsMimetypes)
  655. }
  656. //MARK: -
  657. //MARK: Table Certificates
  658. @objc func addCertificates(_ certificateLocation: String) {
  659. let realm = try! Realm()
  660. do {
  661. try realm.write {
  662. let addObject = tableCertificates()
  663. addObject.certificateLocation = certificateLocation
  664. realm.add(addObject)
  665. }
  666. } catch let error {
  667. print("[LOG] Could not write to database: ", error)
  668. }
  669. }
  670. @objc func getCertificatesLocation(_ localCertificatesFolder: String) -> [String] {
  671. let realm = try! Realm()
  672. realm.refresh()
  673. let results = realm.objects(tableCertificates.self)
  674. return Array(results.map { "\(localCertificatesFolder)/\($0.certificateLocation)" })
  675. }
  676. //MARK: -
  677. //MARK: Table Directory
  678. @objc func addDirectory(encrypted: Bool, favorite: Bool, fileID: String?, permissions: String?, serverUrl: String, account: String) -> tableDirectory? {
  679. let realm = try! Realm()
  680. realm.beginWrite()
  681. var addObject = tableDirectory()
  682. let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first
  683. if result != nil {
  684. addObject = result!
  685. } else {
  686. addObject.directoryID = CCUtility.createDirectoyID(fromAccount: account, serverUrl: serverUrl)
  687. }
  688. addObject.account = account
  689. addObject.e2eEncrypted = encrypted
  690. addObject.favorite = favorite
  691. if let fileID = fileID {
  692. addObject.fileID = fileID
  693. }
  694. if let permissions = permissions {
  695. addObject.permissions = permissions
  696. }
  697. addObject.serverUrl = serverUrl
  698. realm.add(addObject, update: true)
  699. do {
  700. try realm.commitWrite()
  701. } catch let error {
  702. print("[LOG] Could not write to database: ", error)
  703. return nil
  704. }
  705. return tableDirectory.init(value: addObject)
  706. }
  707. @objc func deleteDirectoryAndSubDirectory(serverUrl: String, account: String) {
  708. let realm = try! Realm()
  709. realm.refresh()
  710. let results = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl BEGINSWITH %@", account, serverUrl)
  711. // Delete table Metadata & LocalFile
  712. for result in results {
  713. self.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", result.account, result.serverUrl))
  714. self.deleteLocalFile(predicate: NSPredicate(format: "fileID == %@", result.fileID))
  715. }
  716. // Delete table Dirrectory
  717. do {
  718. try realm.write {
  719. realm.delete(results)
  720. }
  721. } catch let error {
  722. print("[LOG] Could not write to database: ", error)
  723. }
  724. }
  725. @objc func setDirectory(serverUrl: String, serverUrlTo: String?, etag: String?, fileID: String?, encrypted: Bool, account: String) {
  726. let realm = try! Realm()
  727. do {
  728. try realm.write {
  729. guard let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first else {
  730. return
  731. }
  732. let directory = tableDirectory.init(value: result)
  733. realm.delete(result)
  734. directory.e2eEncrypted = encrypted
  735. if let etag = etag {
  736. directory.etag = etag
  737. }
  738. if let fileID = fileID {
  739. directory.fileID = fileID
  740. }
  741. if let serverUrlTo = serverUrlTo {
  742. directory.serverUrl = serverUrlTo
  743. }
  744. directory.directoryID = CCUtility.createDirectoyID(fromAccount: account, serverUrl: directory.serverUrl)
  745. realm.add(directory, update: true)
  746. }
  747. } catch let error {
  748. print("[LOG] Could not write to database: ", error)
  749. }
  750. }
  751. @objc func clearDateRead(serverUrl: String, account: String) {
  752. let realm = try! Realm()
  753. do {
  754. try realm.write {
  755. var predicate = NSPredicate()
  756. predicate = NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl)
  757. guard let result = realm.objects(tableDirectory.self).filter(predicate).first else {
  758. return
  759. }
  760. result.dateReadDirectory = nil
  761. result.etag = ""
  762. realm.add(result, update: true)
  763. }
  764. } catch let error {
  765. print("[LOG] Could not write to database: ", error)
  766. }
  767. }
  768. @objc func getTableDirectory(predicate: NSPredicate) -> tableDirectory? {
  769. let realm = try! Realm()
  770. realm.refresh()
  771. guard let result = realm.objects(tableDirectory.self).filter(predicate).first else {
  772. return nil
  773. }
  774. return tableDirectory.init(value: result)
  775. }
  776. @objc func getTablesDirectory(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableDirectory]? {
  777. let realm = try! Realm()
  778. realm.refresh()
  779. let results = realm.objects(tableDirectory.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  780. if (results.count > 0) {
  781. return Array(results.map { tableDirectory.init(value:$0) })
  782. } else {
  783. return nil
  784. }
  785. }
  786. @objc func setDateReadDirectory(serverUrl: String, account: String) {
  787. let realm = try! Realm()
  788. realm.beginWrite()
  789. guard let result = realm.objects(tableDirectory.self).filter("account == %@ AND serverUrl == %@", account, serverUrl).first else {
  790. realm.cancelWrite()
  791. return
  792. }
  793. result.dateReadDirectory = NSDate()
  794. do {
  795. try realm.commitWrite()
  796. } catch let error {
  797. print("[LOG] Could not write to database: ", error)
  798. }
  799. }
  800. @objc func setClearAllDateReadDirectory() {
  801. let realm = try! Realm()
  802. do {
  803. try realm.write {
  804. let results = realm.objects(tableDirectory.self)
  805. for result in results {
  806. result.dateReadDirectory = nil;
  807. result.etag = ""
  808. }
  809. }
  810. } catch let error {
  811. print("[LOG] Could not write to database: ", error)
  812. }
  813. }
  814. @objc func setDirectoryLock(serverUrl: String, lock: Bool, account: String) -> Bool {
  815. let realm = try! Realm()
  816. var update = false
  817. do {
  818. try realm.write {
  819. guard let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first else {
  820. realm.cancelWrite()
  821. return
  822. }
  823. result.lock = lock
  824. update = true
  825. }
  826. } catch let error {
  827. print("[LOG] Could not write to database: ", error)
  828. return false
  829. }
  830. return update
  831. }
  832. @objc func setAllDirectoryUnLock(account: String) {
  833. let realm = try! Realm()
  834. do {
  835. try realm.write {
  836. let results = realm.objects(tableDirectory.self).filter("account = %@", account)
  837. for result in results {
  838. result.lock = false;
  839. }
  840. }
  841. } catch let error {
  842. print("[LOG] Could not write to database: ", error)
  843. }
  844. }
  845. @objc func setDirectory(serverUrl: String, offline: Bool, account: String) {
  846. let realm = try! Realm()
  847. do {
  848. try realm.write {
  849. guard let result = realm.objects(tableDirectory.self).filter("account = %@ AND serverUrl = %@", account, serverUrl).first else {
  850. realm.cancelWrite()
  851. return
  852. }
  853. result.offline = offline
  854. }
  855. } catch let error {
  856. print("[LOG] Could not write to database: ", error)
  857. }
  858. }
  859. //MARK: -
  860. //MARK: Table e2e Encryption
  861. @objc func addE2eEncryption(_ e2e: tableE2eEncryption) -> Bool {
  862. guard self.getAccountActive() != nil else {
  863. return false
  864. }
  865. let realm = try! Realm()
  866. do {
  867. try realm.write {
  868. realm.add(e2e, update: true)
  869. }
  870. } catch let error {
  871. print("[LOG] Could not write to database: ", error)
  872. return false
  873. }
  874. return true
  875. }
  876. @objc func deleteE2eEncryption(predicate: NSPredicate) {
  877. guard self.getAccountActive() != nil else {
  878. return
  879. }
  880. let realm = try! Realm()
  881. do {
  882. try realm.write {
  883. let results = realm.objects(tableE2eEncryption.self).filter(predicate)
  884. realm.delete(results)
  885. }
  886. } catch let error {
  887. print("[LOG] Could not write to database: ", error)
  888. }
  889. }
  890. @objc func getE2eEncryption(predicate: NSPredicate) -> tableE2eEncryption? {
  891. guard self.getAccountActive() != nil else {
  892. return nil
  893. }
  894. let realm = try! Realm()
  895. realm.refresh()
  896. guard let result = realm.objects(tableE2eEncryption.self).filter(predicate).sorted(byKeyPath: "metadataKeyIndex", ascending: false).first else {
  897. return nil
  898. }
  899. return tableE2eEncryption.init(value: result)
  900. }
  901. @objc func getE2eEncryptions(predicate: NSPredicate) -> [tableE2eEncryption]? {
  902. guard self.getAccountActive() != nil else {
  903. return nil
  904. }
  905. let realm = try! Realm()
  906. realm.refresh()
  907. let results : Results<tableE2eEncryption>
  908. results = realm.objects(tableE2eEncryption.self).filter(predicate)
  909. if (results.count > 0) {
  910. return Array(results.map { tableE2eEncryption.init(value:$0) })
  911. } else {
  912. return nil
  913. }
  914. }
  915. @objc func renameFileE2eEncryption(serverUrl: String, fileNameIdentifier: String, newFileName: String, newFileNamePath: String) {
  916. guard let tableAccount = self.getAccountActive() else {
  917. return
  918. }
  919. let realm = try! Realm()
  920. realm.beginWrite()
  921. guard let result = realm.objects(tableE2eEncryption.self).filter("account = %@ AND serverUrl = %@ AND fileNameIdentifier = %@", tableAccount.account, serverUrl, fileNameIdentifier).first else {
  922. realm.cancelWrite()
  923. return
  924. }
  925. let object = tableE2eEncryption.init(value: result)
  926. realm.delete(result)
  927. object.fileName = newFileName
  928. object.fileNamePath = newFileNamePath
  929. realm.add(object)
  930. do {
  931. try realm.commitWrite()
  932. } catch let error {
  933. print("[LOG] Could not write to database: ", error)
  934. return
  935. }
  936. return
  937. }
  938. //MARK: -
  939. //MARK: Table e2e Encryption Lock
  940. @objc func getE2ETokenLock(serverUrl: String) -> tableE2eEncryptionLock? {
  941. guard let tableAccount = self.getAccountActive() else {
  942. return nil
  943. }
  944. let realm = try! Realm()
  945. realm.refresh()
  946. guard let result = realm.objects(tableE2eEncryptionLock.self).filter("account = %@ AND serverUrl = %@", tableAccount.account, serverUrl).first else {
  947. return nil
  948. }
  949. return tableE2eEncryptionLock.init(value: result)
  950. }
  951. @objc func setE2ETokenLock(serverUrl: String, fileID: String, token: String) {
  952. guard let tableAccount = self.getAccountActive() else {
  953. return
  954. }
  955. let realm = try! Realm()
  956. realm.beginWrite()
  957. let addObject = tableE2eEncryptionLock()
  958. addObject.account = tableAccount.account
  959. addObject.fileID = fileID
  960. addObject.serverUrl = serverUrl
  961. addObject.token = token
  962. realm.add(addObject, update: true)
  963. do {
  964. try realm.commitWrite()
  965. } catch let error {
  966. print("[LOG] Could not write to database: ", error)
  967. }
  968. }
  969. @objc func deteleE2ETokenLock(serverUrl: String) {
  970. guard let tableAccount = self.getAccountActive() else {
  971. return
  972. }
  973. let realm = try! Realm()
  974. realm.beginWrite()
  975. guard let result = realm.objects(tableE2eEncryptionLock.self).filter("account = %@ AND serverUrl = %@", tableAccount.account, serverUrl).first else {
  976. return
  977. }
  978. realm.delete(result)
  979. do {
  980. try realm.commitWrite()
  981. } catch let error {
  982. print("[LOG] Could not write to database: ", error)
  983. }
  984. }
  985. //MARK: -
  986. //MARK: Table External Sites
  987. @objc func addExternalSites(_ externalSites: OCExternalSites, account: String) {
  988. let realm = try! Realm()
  989. do {
  990. try realm.write {
  991. let addObject = tableExternalSites()
  992. addObject.account = account
  993. addObject.idExternalSite = externalSites.idExternalSite
  994. addObject.icon = externalSites.icon
  995. addObject.lang = externalSites.lang
  996. addObject.name = externalSites.name
  997. addObject.url = externalSites.url
  998. addObject.type = externalSites.type
  999. realm.add(addObject)
  1000. }
  1001. } catch let error {
  1002. print("[LOG] Could not write to database: ", error)
  1003. }
  1004. }
  1005. @objc func deleteExternalSites(account: String) {
  1006. let realm = try! Realm()
  1007. do {
  1008. try realm.write {
  1009. let results = realm.objects(tableExternalSites.self).filter("account = %@", account)
  1010. realm.delete(results)
  1011. }
  1012. } catch let error {
  1013. print("[LOG] Could not write to database: ", error)
  1014. }
  1015. }
  1016. @objc func getAllExternalSites(account: String) -> [tableExternalSites]? {
  1017. let realm = try! Realm()
  1018. realm.refresh()
  1019. let results = realm.objects(tableExternalSites.self).filter("account = %@", account).sorted(byKeyPath: "idExternalSite", ascending: true)
  1020. return Array(results)
  1021. }
  1022. //MARK: -
  1023. //MARK: Table GPS
  1024. @objc func addGeocoderLocation(_ location: String, placemarkAdministrativeArea: String, placemarkCountry: String, placemarkLocality: String, placemarkPostalCode: String, placemarkThoroughfare: String, latitude: String, longitude: String) {
  1025. let realm = try! Realm()
  1026. realm.beginWrite()
  1027. // Verify if exists
  1028. guard realm.objects(tableGPS.self).filter("latitude = %@ AND longitude = %@", latitude, longitude).first == nil else {
  1029. realm.cancelWrite()
  1030. return
  1031. }
  1032. // Add new GPS
  1033. let addObject = tableGPS()
  1034. addObject.latitude = latitude
  1035. addObject.location = location
  1036. addObject.longitude = longitude
  1037. addObject.placemarkAdministrativeArea = placemarkAdministrativeArea
  1038. addObject.placemarkCountry = placemarkCountry
  1039. addObject.placemarkLocality = placemarkLocality
  1040. addObject.placemarkPostalCode = placemarkPostalCode
  1041. addObject.placemarkThoroughfare = placemarkThoroughfare
  1042. realm.add(addObject)
  1043. do {
  1044. try realm.commitWrite()
  1045. } catch let error {
  1046. print("[LOG] Could not write to database: ", error)
  1047. }
  1048. }
  1049. @objc func getLocationFromGeoLatitude(_ latitude: String, longitude: String) -> String? {
  1050. let realm = try! Realm()
  1051. realm.refresh()
  1052. guard let result = realm.objects(tableGPS.self).filter("latitude = %@ AND longitude = %@", latitude, longitude).first else {
  1053. return nil
  1054. }
  1055. return result.location
  1056. }
  1057. //MARK: -
  1058. //MARK: Table LocalFile
  1059. @objc func addLocalFile(metadata: tableMetadata) {
  1060. let realm = try! Realm()
  1061. do {
  1062. try realm.write {
  1063. let addObject = tableLocalFile()
  1064. addObject.account = metadata.account
  1065. addObject.date = metadata.date
  1066. addObject.etag = metadata.etag
  1067. addObject.exifDate = NSDate()
  1068. addObject.exifLatitude = "-1"
  1069. addObject.exifLongitude = "-1"
  1070. addObject.fileID = metadata.fileID
  1071. addObject.fileName = metadata.fileName
  1072. addObject.size = metadata.size
  1073. realm.add(addObject, update: true)
  1074. }
  1075. } catch let error {
  1076. print("[LOG] Could not write to database: ", error)
  1077. }
  1078. }
  1079. @objc func deleteLocalFile(predicate: NSPredicate) {
  1080. let realm = try! Realm()
  1081. do {
  1082. try realm.write {
  1083. let results = realm.objects(tableLocalFile.self).filter(predicate)
  1084. realm.delete(results)
  1085. }
  1086. } catch let error {
  1087. print("[LOG] Could not write to database: ", error)
  1088. }
  1089. }
  1090. @objc func setLocalFile(fileID: String, date: NSDate?, exifDate: NSDate?, exifLatitude: String?, exifLongitude: String?, fileName: String?, etag: String?) {
  1091. let realm = try! Realm()
  1092. do {
  1093. try realm.write {
  1094. guard let result = realm.objects(tableLocalFile.self).filter("fileID = %@", fileID).first else {
  1095. realm.cancelWrite()
  1096. return
  1097. }
  1098. if let date = date {
  1099. result.date = date
  1100. }
  1101. if let exifDate = exifDate {
  1102. result.exifDate = exifDate
  1103. }
  1104. if let exifLatitude = exifLatitude {
  1105. result.exifLatitude = exifLatitude
  1106. }
  1107. if let exifLongitude = exifLongitude {
  1108. result.exifLongitude = exifLongitude
  1109. }
  1110. if let fileName = fileName {
  1111. result.fileName = fileName
  1112. }
  1113. if let etag = etag {
  1114. result.etag = etag
  1115. }
  1116. }
  1117. } catch let error {
  1118. print("[LOG] Could not write to database: ", error)
  1119. }
  1120. }
  1121. @objc func getTableLocalFile(predicate: NSPredicate) -> tableLocalFile? {
  1122. let realm = try! Realm()
  1123. realm.refresh()
  1124. guard let result = realm.objects(tableLocalFile.self).filter(predicate).first else {
  1125. return nil
  1126. }
  1127. return tableLocalFile.init(value: result)
  1128. }
  1129. @objc func getTableLocalFiles(predicate: NSPredicate, sorted: String, ascending: Bool) -> [tableLocalFile]? {
  1130. let realm = try! Realm()
  1131. realm.refresh()
  1132. let results = realm.objects(tableLocalFile.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1133. if (results.count > 0) {
  1134. return Array(results.map { tableLocalFile.init(value:$0) })
  1135. } else {
  1136. return nil
  1137. }
  1138. }
  1139. @objc func setLocalFile(fileID: String, offline: Bool) {
  1140. let realm = try! Realm()
  1141. do {
  1142. try realm.write {
  1143. guard let result = realm.objects(tableLocalFile.self).filter("fileID = %@", fileID).first else {
  1144. realm.cancelWrite()
  1145. return
  1146. }
  1147. result.offline = offline
  1148. }
  1149. } catch let error {
  1150. print("[LOG] Could not write to database: ", error)
  1151. }
  1152. }
  1153. //MARK: -
  1154. //MARK: Table Metadata
  1155. @objc func addMetadata(_ metadata: tableMetadata) -> tableMetadata? {
  1156. if metadata.isInvalidated {
  1157. return nil
  1158. }
  1159. let serverUrl = metadata.serverUrl
  1160. let account = metadata.account
  1161. let realm = try! Realm()
  1162. do {
  1163. try realm.write {
  1164. realm.add(metadata, update: true)
  1165. }
  1166. } catch let error {
  1167. print("[LOG] Could not write to database: ", error)
  1168. return nil
  1169. }
  1170. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1171. if metadata.isInvalidated {
  1172. return nil
  1173. }
  1174. return tableMetadata.init(value: metadata)
  1175. }
  1176. @objc func addMetadatas(_ metadatas: [tableMetadata]) -> [tableMetadata]? {
  1177. var directoryToClearDate = [String:String]()
  1178. let realm = try! Realm()
  1179. do {
  1180. try realm.write {
  1181. for metadata in metadatas {
  1182. directoryToClearDate[metadata.serverUrl] = metadata.account
  1183. realm.add(metadata, update: true)
  1184. }
  1185. }
  1186. } catch let error {
  1187. print("[LOG] Could not write to database: ", error)
  1188. return nil
  1189. }
  1190. for (serverUrl, account) in directoryToClearDate {
  1191. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1192. }
  1193. return Array(metadatas.map { tableMetadata.init(value:$0) })
  1194. }
  1195. @objc func deleteMetadata(predicate: NSPredicate) {
  1196. var directoryToClearDate = [String:String]()
  1197. let realm = try! Realm()
  1198. realm.beginWrite()
  1199. let results = realm.objects(tableMetadata.self).filter(predicate)
  1200. for result in results {
  1201. directoryToClearDate[result.serverUrl] = result.account
  1202. }
  1203. realm.delete(results)
  1204. do {
  1205. try realm.commitWrite()
  1206. } catch let error {
  1207. print("[LOG] Could not write to database: ", error)
  1208. return
  1209. }
  1210. for (serverUrl, account) in directoryToClearDate {
  1211. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1212. }
  1213. }
  1214. @objc func moveMetadata(fileID: String, serverUrlTo: String) {
  1215. let realm = try! Realm()
  1216. do {
  1217. try realm.write {
  1218. let results = realm.objects(tableMetadata.self).filter("fileID == %@", fileID)
  1219. for result in results {
  1220. result.serverUrl = serverUrlTo
  1221. }
  1222. }
  1223. } catch let error {
  1224. print("[LOG] Could not write to database: ", error)
  1225. return
  1226. }
  1227. }
  1228. @objc func addMetadataServerUrl(fileID: String, serverUrl: String) {
  1229. let realm = try! Realm()
  1230. do {
  1231. try realm.write {
  1232. let results = realm.objects(tableMetadata.self).filter("fileID == %@", fileID)
  1233. for result in results {
  1234. result.serverUrl = serverUrl
  1235. }
  1236. }
  1237. } catch let error {
  1238. print("[LOG] Could not write to database: ", error)
  1239. return
  1240. }
  1241. }
  1242. @objc func renameMetadata(fileNameTo: String, fileID: String) -> tableMetadata? {
  1243. var result :tableMetadata?
  1244. let realm = try! Realm()
  1245. do {
  1246. try realm.write {
  1247. result = realm.objects(tableMetadata.self).filter("fileID == %@", fileID).first
  1248. if result != nil {
  1249. result!.fileName = fileNameTo
  1250. result!.fileNameView = fileNameTo
  1251. }
  1252. }
  1253. } catch let error {
  1254. print("[LOG] Could not write to database: ", error)
  1255. return nil
  1256. }
  1257. if result == nil {
  1258. return nil
  1259. }
  1260. self.setDateReadDirectory(serverUrl: result!.serverUrl, account: result!.account)
  1261. return tableMetadata.init(value: result!)
  1262. }
  1263. @objc func updateMetadata(_ metadata: tableMetadata) -> tableMetadata? {
  1264. let account = metadata.account
  1265. let serverUrl = metadata.serverUrl
  1266. let realm = try! Realm()
  1267. do {
  1268. try realm.write {
  1269. realm.add(metadata, update: true)
  1270. }
  1271. } catch let error {
  1272. print("[LOG] Could not write to database: ", error)
  1273. return nil
  1274. }
  1275. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1276. return tableMetadata.init(value: metadata)
  1277. }
  1278. @objc func setMetadataSession(_ session: String?, sessionError: String?, sessionSelector: String?, sessionTaskIdentifier: Int, status: Int, predicate: NSPredicate) {
  1279. let realm = try! Realm()
  1280. realm.beginWrite()
  1281. guard let result = realm.objects(tableMetadata.self).filter(predicate).first else {
  1282. realm.cancelWrite()
  1283. return
  1284. }
  1285. if let session = session {
  1286. result.session = session
  1287. }
  1288. if let sessionError = sessionError {
  1289. result.sessionError = sessionError
  1290. }
  1291. if let sessionSelector = sessionSelector {
  1292. result.sessionSelector = sessionSelector
  1293. }
  1294. result.sessionTaskIdentifier = sessionTaskIdentifier
  1295. result.status = status
  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. self.setDateReadDirectory(serverUrl: serverUrl, account: account)
  1306. }
  1307. @objc func setMetadataFavorite(fileID: String, favorite: Bool) {
  1308. let realm = try! Realm()
  1309. realm.beginWrite()
  1310. guard let result = realm.objects(tableMetadata.self).filter("fileID == %@", fileID).first else {
  1311. realm.cancelWrite()
  1312. return
  1313. }
  1314. result.favorite = favorite
  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 setMetadataFileNameView(serverUrl: String, fileName: String, newFileNameView: String, account: String) {
  1327. let realm = try! Realm()
  1328. realm.beginWrite()
  1329. guard let result = realm.objects(tableMetadata.self).filter("account == %@ AND serverUrl == %@ AND fileName == %@", account, serverUrl, fileName).first else {
  1330. realm.cancelWrite()
  1331. return
  1332. }
  1333. result.fileNameView = newFileNameView
  1334. let account = result.account
  1335. let serverUrl = result.serverUrl
  1336. do {
  1337. try realm.commitWrite()
  1338. } catch let error {
  1339. print("[LOG] Could not write to database: ", error)
  1340. return
  1341. }
  1342. // Update Date Read Directory
  1343. setDateReadDirectory(serverUrl: serverUrl, account: account)
  1344. }
  1345. @objc func getMetadata(predicate: NSPredicate) -> tableMetadata? {
  1346. let realm = try! Realm()
  1347. realm.refresh()
  1348. guard let result = realm.objects(tableMetadata.self).filter(predicate).first else {
  1349. return nil
  1350. }
  1351. return tableMetadata.init(value: result)
  1352. }
  1353. @objc func getMetadata(predicate: NSPredicate, sorted: String, ascending: Bool) -> tableMetadata? {
  1354. let realm = try! Realm()
  1355. realm.refresh()
  1356. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1357. if (results.count > 0) {
  1358. return tableMetadata.init(value: results[0])
  1359. } else {
  1360. return nil
  1361. }
  1362. }
  1363. @objc func getMetadatas(predicate: NSPredicate, sorted: String?, ascending: Bool) -> [tableMetadata]? {
  1364. let realm = try! Realm()
  1365. realm.refresh()
  1366. let results : Results<tableMetadata>
  1367. if let sorted = sorted {
  1368. if (tableMetadata().objectSchema.properties.contains { $0.name == sorted }) {
  1369. results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1370. } else {
  1371. results = realm.objects(tableMetadata.self).filter(predicate)
  1372. }
  1373. } else {
  1374. results = realm.objects(tableMetadata.self).filter(predicate)
  1375. }
  1376. if (results.count > 0) {
  1377. return Array(results.map { tableMetadata.init(value:$0) })
  1378. } else {
  1379. return nil
  1380. }
  1381. }
  1382. @objc func getMetadataAtIndex(predicate: NSPredicate, sorted: String, ascending: Bool, index: Int) -> tableMetadata? {
  1383. let realm = try! Realm()
  1384. realm.refresh()
  1385. let results = realm.objects(tableMetadata.self).filter(predicate).sorted(byKeyPath: sorted, ascending: ascending)
  1386. if (results.count > 0 && results.count > index) {
  1387. return tableMetadata.init(value: results[index])
  1388. } else {
  1389. return nil
  1390. }
  1391. }
  1392. @objc func getMetadataInSessionFromFileName(_ fileName: String, serverUrl: String, taskIdentifier: Int) -> tableMetadata? {
  1393. let realm = try! Realm()
  1394. realm.refresh()
  1395. guard let result = realm.objects(tableMetadata.self).filter("serverUrl == %@ AND fileName == %@ AND session != '' AND sessionTaskIdentifier == %d", serverUrl, fileName, taskIdentifier).first else {
  1396. return nil
  1397. }
  1398. return tableMetadata.init(value: result)
  1399. }
  1400. @objc func getTableMetadatasDirectoryFavoriteIdentifierRank(account: String) -> [String:NSNumber] {
  1401. var listIdentifierRank = [String:NSNumber]()
  1402. let realm = try! Realm()
  1403. realm.refresh()
  1404. var counter = 10 as Int64
  1405. let results = realm.objects(tableMetadata.self).filter("account = %@ AND directory = true AND favorite = true", account).sorted(byKeyPath: "fileNameView", ascending: true)
  1406. for result in results {
  1407. counter += 1
  1408. listIdentifierRank[result.fileID] = NSNumber(value: Int64(counter))
  1409. }
  1410. return listIdentifierRank
  1411. }
  1412. @objc func clearMetadatasUpload(account: String) {
  1413. let realm = try! Realm()
  1414. do {
  1415. try realm.write {
  1416. let results = realm.objects(tableMetadata.self).filter("account == %@ AND (status == %d OR status == %@)", account, k_metadataStatusWaitUpload, k_metadataStatusUploadError)
  1417. realm.delete(results)
  1418. }
  1419. } catch let error {
  1420. print("[LOG] Could not write to database: ", error)
  1421. }
  1422. }
  1423. @objc func initNewMetadata(_ metadata: tableMetadata) -> tableMetadata {
  1424. return tableMetadata.init(value: metadata)
  1425. }
  1426. //MARK: -
  1427. //MARK: Table Photos
  1428. @objc func getTablePhotos(addMetadatasFromUpload: [tableMetadata], account: String) -> [tableMetadata]? {
  1429. let realm = try! Realm()
  1430. realm.refresh()
  1431. let predicate = NSPredicate(format: "account == %@", account)
  1432. let results = realm.objects(tablePhotos.self).filter(predicate).sorted(byKeyPath: "date", ascending: false)
  1433. if (results.count > 0) {
  1434. var returnMetadatas = Array(results.map { tableMetadata.init(value:$0) })
  1435. for metadata in addMetadatasFromUpload {
  1436. let result = realm.objects(tablePhotos.self).filter("fileID == %@", metadata.fileID).first
  1437. if result == nil {
  1438. returnMetadatas.append(metadata)
  1439. }
  1440. }
  1441. return returnMetadatas
  1442. } else {
  1443. return nil
  1444. }
  1445. }
  1446. @objc func getTablePhoto(predicate: NSPredicate) -> tableMetadata? {
  1447. let realm = try! Realm()
  1448. realm.refresh()
  1449. guard let result = realm.objects(tablePhotos.self).filter(predicate).first else {
  1450. return nil
  1451. }
  1452. return tableMetadata.init(value: result)
  1453. }
  1454. @objc func createTablePhotos(_ metadatas: [tableMetadata], account: String) {
  1455. let realm = try! Realm()
  1456. realm.refresh()
  1457. do {
  1458. try realm.write {
  1459. // DELETE ALL
  1460. let results = realm.objects(tablePhotos.self).filter("account = %@", account)
  1461. realm.delete(results)
  1462. // INSERT ALL
  1463. let photos = Array(metadatas.map { tablePhotos.init(value:$0) })
  1464. realm.add(photos, update: true)
  1465. }
  1466. } catch let error {
  1467. print("[LOG] Could not write to database: ", error)
  1468. realm.cancelWrite()
  1469. }
  1470. }
  1471. @objc func deletePhotos(fileID: String) {
  1472. let realm = try! Realm()
  1473. realm.beginWrite()
  1474. let results = realm.objects(tablePhotos.self).filter("fileID = %@", fileID)
  1475. realm.delete(results)
  1476. do {
  1477. try realm.commitWrite()
  1478. } catch let error {
  1479. print("[LOG] Could not write to database: ", error)
  1480. return
  1481. }
  1482. }
  1483. //MARK: -
  1484. //MARK: Table Photo Library
  1485. @objc func addPhotoLibrary(_ assets: [PHAsset], account: String) -> Bool {
  1486. let realm = try! Realm()
  1487. if realm.isInWriteTransaction {
  1488. print("[LOG] Could not write to database, addPhotoLibrary is already in write transaction")
  1489. return false
  1490. } else {
  1491. do {
  1492. try realm.write {
  1493. var creationDateString = ""
  1494. for asset in assets {
  1495. let addObject = tablePhotoLibrary()
  1496. addObject.account = account
  1497. addObject.assetLocalIdentifier = asset.localIdentifier
  1498. addObject.mediaType = asset.mediaType.rawValue
  1499. if let creationDate = asset.creationDate {
  1500. addObject.creationDate = creationDate as NSDate
  1501. creationDateString = String(describing: creationDate)
  1502. } else {
  1503. creationDateString = ""
  1504. }
  1505. if let modificationDate = asset.modificationDate {
  1506. addObject.modificationDate = modificationDate as NSDate
  1507. }
  1508. addObject.idAsset = "\(account)\(asset.localIdentifier)\(creationDateString)"
  1509. realm.add(addObject, update: true)
  1510. }
  1511. }
  1512. } catch let error {
  1513. print("[LOG] Could not write to database: ", error)
  1514. return false
  1515. }
  1516. }
  1517. return true
  1518. }
  1519. @objc func getPhotoLibraryIdAsset(image: Bool, video: Bool, account: String) -> [String]? {
  1520. let realm = try! Realm()
  1521. realm.refresh()
  1522. var predicate = NSPredicate()
  1523. if (image && video) {
  1524. predicate = NSPredicate(format: "account == %@ AND (mediaType == %i OR mediaType == %i)", account, PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
  1525. } else if (image) {
  1526. predicate = NSPredicate(format: "account == %@ AND mediaType == %i", account, PHAssetMediaType.image.rawValue)
  1527. } else if (video) {
  1528. predicate = NSPredicate(format: "account == %@ AND mediaType == %i", account, PHAssetMediaType.video.rawValue)
  1529. }
  1530. let results = realm.objects(tablePhotoLibrary.self).filter(predicate)
  1531. let idsAsset = results.map { $0.idAsset }
  1532. return Array(idsAsset)
  1533. }
  1534. @objc func getPhotoLibrary(predicate: NSPredicate) -> [tablePhotoLibrary] {
  1535. let realm = try! Realm()
  1536. let results = realm.objects(tablePhotoLibrary.self).filter(predicate)
  1537. return Array(results.map { tablePhotoLibrary.init(value:$0) })
  1538. }
  1539. //MARK: -
  1540. //MARK: Table Share
  1541. @objc func addShareLink(_ share: String, fileName: String, serverUrl: String, account: String) -> [String:String]? {
  1542. let realm = try! Realm()
  1543. realm.beginWrite()
  1544. // Verify if exists
  1545. let result = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", account, fileName, serverUrl).first
  1546. if result != nil {
  1547. result?.shareLink = share
  1548. } else {
  1549. // Add new
  1550. let addObject = tableShare()
  1551. addObject.account = account
  1552. addObject.fileName = fileName
  1553. addObject.serverUrl = serverUrl
  1554. addObject.shareLink = share
  1555. realm.add(addObject)
  1556. }
  1557. do {
  1558. try realm.commitWrite()
  1559. } catch let error {
  1560. print("[LOG] Could not write to database: ", error)
  1561. return nil
  1562. }
  1563. return ["\(serverUrl)\(fileName)" : share]
  1564. }
  1565. @objc func addShareUserAndGroup(_ share: String, fileName: String, serverUrl: String, account: String) -> [String:String]? {
  1566. let realm = try! Realm()
  1567. realm.beginWrite()
  1568. // Verify if exists
  1569. let result = realm.objects(tableShare.self).filter("account = %@ AND fileName = %@ AND serverUrl = %@", account, fileName, serverUrl).first
  1570. if result != nil {
  1571. result?.shareUserAndGroup = share
  1572. } else {
  1573. // Add new
  1574. let addObject = tableShare()
  1575. addObject.account = account
  1576. addObject.fileName = fileName
  1577. addObject.serverUrl = serverUrl
  1578. addObject.shareUserAndGroup = share
  1579. realm.add(addObject)
  1580. }
  1581. do {
  1582. try realm.commitWrite()
  1583. } catch let error {
  1584. print("[LOG] Could not write to database: ", error)
  1585. return nil
  1586. }
  1587. return ["\(serverUrl)\(fileName)" : share]
  1588. }
  1589. @objc func unShare(_ share: String, fileName: String, serverUrl: String, sharesLink: [String:String], sharesUserAndGroup: [String:String], account: String) -> [Any]? {
  1590. var sharesLink = sharesLink
  1591. var sharesUserAndGroup = sharesUserAndGroup
  1592. let realm = try! Realm()
  1593. realm.beginWrite()
  1594. let results = realm.objects(tableShare.self).filter("account = %@ AND (shareLink CONTAINS %@ OR shareUserAndGroup CONTAINS %@)", account, share, share)
  1595. if (results.count > 0) {
  1596. let result = results[0]
  1597. if (result.shareLink.contains(share)) {
  1598. result.shareLink = ""
  1599. }
  1600. if (result.shareUserAndGroup.contains(share)) {
  1601. var shares : [String] = result.shareUserAndGroup.components(separatedBy: ",")
  1602. if let index = shares.index(of:share) {
  1603. shares.remove(at: index)
  1604. }
  1605. result.shareUserAndGroup = shares.joined(separator: ",")
  1606. }
  1607. if (result.shareLink.count > 0) {
  1608. sharesLink.updateValue(result.shareLink, forKey:"\(serverUrl)\(fileName)")
  1609. } else {
  1610. sharesLink.removeValue(forKey: "\(serverUrl)\(fileName)")
  1611. }
  1612. if (result.shareUserAndGroup.count > 0) {
  1613. sharesUserAndGroup.updateValue(result.shareUserAndGroup, forKey:"\(serverUrl)\(fileName)")
  1614. } else {
  1615. sharesUserAndGroup.removeValue(forKey: "\(serverUrl)\(fileName)")
  1616. }
  1617. if (result.shareLink.count == 0 && result.shareUserAndGroup.count == 0) {
  1618. realm.delete(result)
  1619. }
  1620. }
  1621. do {
  1622. try realm.commitWrite()
  1623. } catch let error {
  1624. print("[LOG] Could not write to database: ", error)
  1625. return nil
  1626. }
  1627. return [sharesLink, sharesUserAndGroup]
  1628. }
  1629. @objc func removeShareActiveAccount(account: String) {
  1630. let realm = try! Realm()
  1631. do {
  1632. try realm.write {
  1633. let results = realm.objects(tableShare.self).filter("account = %@", account)
  1634. realm.delete(results)
  1635. }
  1636. } catch let error {
  1637. print("[LOG] Could not write to database: ", error)
  1638. }
  1639. }
  1640. @objc func updateShare(_ items: [String:OCSharedDto], activeUrl: String, account: String) -> [Any]? {
  1641. var sharesLink = [String:String]()
  1642. var sharesUserAndGroup = [String:String]()
  1643. self.removeShareActiveAccount(account: account)
  1644. var itemsLink = [OCSharedDto]()
  1645. var itemsUsersAndGroups = [OCSharedDto]()
  1646. for (_, itemOCSharedDto) in items {
  1647. if (itemOCSharedDto.shareType == Int(shareTypeLink.rawValue)) {
  1648. itemsLink.append(itemOCSharedDto)
  1649. }
  1650. if (itemOCSharedDto.shareWith.count > 0 && (itemOCSharedDto.shareType == Int(shareTypeUser.rawValue) || itemOCSharedDto.shareType == Int(shareTypeGroup.rawValue) || itemOCSharedDto.shareType == Int(shareTypeRemote.rawValue) )) {
  1651. itemsUsersAndGroups.append(itemOCSharedDto)
  1652. }
  1653. }
  1654. // Manage sharesLink
  1655. for itemOCSharedDto in itemsLink {
  1656. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(itemOCSharedDto.path!)"
  1657. let fileName = NSString(string: fullPath).lastPathComponent
  1658. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.count - fileName.count - 1))
  1659. if serverUrl.hasSuffix("/") {
  1660. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.count - 1))
  1661. }
  1662. if itemOCSharedDto.idRemoteShared > 0 {
  1663. let sharesLinkReturn = self.addShareLink("\(itemOCSharedDto.idRemoteShared)", fileName: fileName, serverUrl: serverUrl, account: account)
  1664. if sharesLinkReturn != nil {
  1665. for (key,value) in sharesLinkReturn! {
  1666. sharesLink.updateValue(value, forKey:key)
  1667. }
  1668. }
  1669. }
  1670. }
  1671. // Manage sharesUserAndGroup
  1672. var paths = [String:[String]]()
  1673. for itemOCSharedDto in itemsUsersAndGroups {
  1674. if paths[itemOCSharedDto.path] != nil {
  1675. var share : [String] = paths[itemOCSharedDto.path]!
  1676. share.append("\(itemOCSharedDto.idRemoteShared)")
  1677. paths[itemOCSharedDto.path] = share
  1678. } else {
  1679. paths[itemOCSharedDto.path] = ["\(itemOCSharedDto.idRemoteShared)"]
  1680. }
  1681. }
  1682. for (path, idsRemoteSharedArray) in paths {
  1683. let idsRemoteShared = idsRemoteSharedArray.joined(separator: ",")
  1684. print("[LOG] share \(String(describing: idsRemoteShared))")
  1685. let fullPath = CCUtility.getHomeServerUrlActiveUrl(activeUrl) + "\(path)"
  1686. let fileName = NSString(string: fullPath).lastPathComponent
  1687. var serverUrl = NSString(string: fullPath).substring(to: (fullPath.count - fileName.count - 1))
  1688. if serverUrl.hasSuffix("/") {
  1689. serverUrl = NSString(string: serverUrl).substring(to: (serverUrl.count - 1))
  1690. }
  1691. let sharesUserAndGroupReturn = self.addShareUserAndGroup(idsRemoteShared, fileName: fileName, serverUrl: serverUrl, account: account)
  1692. if sharesUserAndGroupReturn != nil {
  1693. for (key,value) in sharesUserAndGroupReturn! {
  1694. sharesUserAndGroup.updateValue(value, forKey:key)
  1695. }
  1696. }
  1697. }
  1698. return [sharesLink, sharesUserAndGroup]
  1699. }
  1700. @objc func getShares(account: String) -> [Any]? {
  1701. var sharesLink = [String:String]()
  1702. var sharesUserAndGroup = [String:String]()
  1703. let realm = try! Realm()
  1704. let results = realm.objects(tableShare.self).filter("account = %@", account)
  1705. for resultShare in results {
  1706. if (resultShare.shareLink.count > 0) {
  1707. sharesLink = [resultShare.shareLink: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  1708. }
  1709. if (resultShare.shareUserAndGroup.count > 0) {
  1710. sharesUserAndGroup = [resultShare.shareUserAndGroup: "\(resultShare.serverUrl)\(resultShare.fileName)"]
  1711. }
  1712. }
  1713. return [sharesLink, sharesUserAndGroup]
  1714. }
  1715. @objc func getTableShares(account: String) -> [tableShare]? {
  1716. let realm = try! Realm()
  1717. realm.refresh()
  1718. let results = realm.objects(tableShare.self).filter("account = %@", account).sorted(byKeyPath: "fileName", ascending: true)
  1719. return Array(results)
  1720. }
  1721. //MARK: -
  1722. //MARK: Table Tag
  1723. @objc func addTag(_ fileID: String ,tagIOS: Data?, account: String) {
  1724. let realm = try! Realm()
  1725. do {
  1726. try realm.write {
  1727. // Add new
  1728. let addObject = tableTag()
  1729. addObject.account = account
  1730. addObject.fileID = fileID
  1731. addObject.tagIOS = tagIOS
  1732. realm.add(addObject, update: true)
  1733. }
  1734. } catch let error {
  1735. print("[LOG] Could not write to database: ", error)
  1736. }
  1737. }
  1738. @objc func deleteTag(_ fileID: String) {
  1739. let realm = try! Realm()
  1740. realm.beginWrite()
  1741. guard let result = realm.objects(tableTag.self).filter("fileID == %@", fileID).first else {
  1742. realm.cancelWrite()
  1743. return
  1744. }
  1745. realm.delete(result)
  1746. do {
  1747. try realm.commitWrite()
  1748. } catch let error {
  1749. print("[LOG] Could not write to database: ", error)
  1750. }
  1751. }
  1752. @objc func getTags(predicate: NSPredicate) -> [tableTag] {
  1753. let realm = try! Realm()
  1754. realm.refresh()
  1755. let results = realm.objects(tableTag.self).filter(predicate)
  1756. return Array(results.map { tableTag.init(value:$0) })
  1757. }
  1758. @objc func getTag(predicate: NSPredicate) -> tableTag? {
  1759. let realm = try! Realm()
  1760. realm.refresh()
  1761. guard let result = realm.objects(tableTag.self).filter(predicate).first else {
  1762. return nil
  1763. }
  1764. return tableTag.init(value: result)
  1765. }
  1766. //MARK: -
  1767. //MARK: Table Trash
  1768. @objc func addTrashs(_ trashs: [tableTrash]) {
  1769. let realm = try! Realm()
  1770. do {
  1771. try realm.write {
  1772. for trash in trashs {
  1773. realm.add(trash, update: true)
  1774. }
  1775. }
  1776. } catch let error {
  1777. print("[LOG] Could not write to database: ", error)
  1778. return
  1779. }
  1780. }
  1781. @objc func deleteTrash(filePath: String, account: String) {
  1782. let realm = try! Realm()
  1783. realm.beginWrite()
  1784. let results = realm.objects(tableTrash.self).filter("account = %@ AND filePath = %@", account, filePath)
  1785. realm.delete(results)
  1786. do {
  1787. try realm.commitWrite()
  1788. } catch let error {
  1789. print("[LOG] Could not write to database: ", error)
  1790. }
  1791. }
  1792. @objc func deleteTrash(fileID: String?, account: String) {
  1793. let realm = try! Realm()
  1794. var predicate = NSPredicate()
  1795. realm.beginWrite()
  1796. if fileID == nil {
  1797. predicate = NSPredicate(format: "account == %@", account)
  1798. } else {
  1799. predicate = NSPredicate(format: "account = %@ AND fileID = %@", account, fileID!)
  1800. }
  1801. let result = realm.objects(tableTrash.self).filter(predicate)
  1802. realm.delete(result)
  1803. do {
  1804. try realm.commitWrite()
  1805. } catch let error {
  1806. print("[LOG] Could not write to database: ", error)
  1807. }
  1808. }
  1809. @objc func getTrash(filePath: String, sorted: String, ascending: Bool, account: String) -> [tableTrash]? {
  1810. let realm = try! Realm()
  1811. realm.refresh()
  1812. let results = realm.objects(tableTrash.self).filter("account = %@ AND filePath = %@", account, filePath).sorted(byKeyPath: sorted, ascending: ascending)
  1813. return Array(results.map { tableTrash.init(value:$0) })
  1814. }
  1815. @objc func getTrashItem(fileID: String, account: String) -> tableTrash? {
  1816. let realm = try! Realm()
  1817. realm.refresh()
  1818. guard let result = realm.objects(tableTrash.self).filter("account = %@ AND fileID = %@", account, fileID).first else {
  1819. return nil
  1820. }
  1821. return tableTrash.init(value: result)
  1822. }
  1823. //MARK: -
  1824. }