cbl-ionic 0.2.6 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CblIonic.podspec +1 -1
  2. package/README.md +12 -0
  3. package/android/build.gradle +1 -1
  4. package/android/src/main/java/cbl/js/kotiln/DatabaseManager.kt +19 -6
  5. package/android/src/main/java/cbl/js/kotiln/URLEndpointListenerManager.kt +143 -0
  6. package/android/src/main/java/com/couchbase/ionic/CblIonicPluginPlugin.kt +186 -30
  7. package/android/src/main/java/com/couchbase/ionic/PluginHelper.kt +27 -38
  8. package/android/src/main/java/com/couchbase/ionic/QueryHelper.kt +14 -4
  9. package/android/src/main/java/com/couchbase/ionic/ReplicatorHelper.kt +33 -11
  10. package/dist/esm/cblite-js/cblite/core-types.d.ts +148 -5
  11. package/dist/esm/cblite-js/cblite/src/collection-config.d.ts +34 -0
  12. package/dist/esm/cblite-js/cblite/src/collection-config.js +40 -0
  13. package/dist/esm/cblite-js/cblite/src/collection-config.js.map +1 -1
  14. package/dist/esm/cblite-js/cblite/src/collection.d.ts +1 -2
  15. package/dist/esm/cblite-js/cblite/src/collection.js +17 -17
  16. package/dist/esm/cblite-js/cblite/src/collection.js.map +1 -1
  17. package/dist/esm/cblite-js/cblite/src/database-logging.js +1 -1
  18. package/dist/esm/cblite-js/cblite/src/database-logging.js.map +1 -1
  19. package/dist/esm/cblite-js/cblite/src/database.d.ts +13 -2
  20. package/dist/esm/cblite-js/cblite/src/database.js +50 -34
  21. package/dist/esm/cblite-js/cblite/src/database.js.map +1 -1
  22. package/dist/esm/cblite-js/cblite/src/document.d.ts +3 -4
  23. package/dist/esm/cblite-js/cblite/src/document.js +6 -6
  24. package/dist/esm/cblite-js/cblite/src/document.js.map +1 -1
  25. package/dist/esm/cblite-js/cblite/src/index.d.ts +1 -0
  26. package/dist/esm/cblite-js/cblite/src/index.js +1 -0
  27. package/dist/esm/cblite-js/cblite/src/index.js.map +1 -1
  28. package/dist/esm/cblite-js/cblite/src/query.js +6 -11
  29. package/dist/esm/cblite-js/cblite/src/query.js.map +1 -1
  30. package/dist/esm/cblite-js/cblite/src/replicated-document.js +2 -2
  31. package/dist/esm/cblite-js/cblite/src/replicated-document.js.map +1 -1
  32. package/dist/esm/cblite-js/cblite/src/replicator-configuration.d.ts +2 -1
  33. package/dist/esm/cblite-js/cblite/src/replicator-configuration.js +29 -3
  34. package/dist/esm/cblite-js/cblite/src/replicator-configuration.js.map +1 -1
  35. package/dist/esm/cblite-js/cblite/src/replicator.js +8 -5
  36. package/dist/esm/cblite-js/cblite/src/replicator.js.map +1 -1
  37. package/dist/esm/cblite-js/cblite/src/scope.js +2 -2
  38. package/dist/esm/cblite-js/cblite/src/scope.js.map +1 -1
  39. package/dist/esm/cblite-js/cblite/src/url-endpoint-listener.d.ts +84 -0
  40. package/dist/esm/cblite-js/cblite/src/url-endpoint-listener.js +109 -0
  41. package/dist/esm/cblite-js/cblite/src/url-endpoint-listener.js.map +1 -0
  42. package/dist/esm/couchbase-lite/capacitor-engine.d.ts +17 -2
  43. package/dist/esm/couchbase-lite/capacitor-engine.js +19 -1
  44. package/dist/esm/couchbase-lite/capacitor-engine.js.map +1 -1
  45. package/dist/plugin.cjs.js +288 -82
  46. package/dist/plugin.cjs.js.map +1 -1
  47. package/dist/plugin.js +288 -82
  48. package/dist/plugin.js.map +1 -1
  49. package/ios/Plugin/CblIonicPlugin.swift +120 -7
  50. package/ios/Plugin/CblIonicPluginPlugin.m +7 -0
  51. package/ios/Plugin/cbl-js-swift/CollectionManager.swift +24 -3
  52. package/ios/Plugin/cbl-js-swift/DatabaseManager.swift +29 -13
  53. package/ios/Plugin/cbl-js-swift/FileSystemHelper.swift +0 -2
  54. package/ios/Plugin/cbl-js-swift/IndexHelper.swift +0 -2
  55. package/ios/Plugin/cbl-js-swift/LoggingManager.swift +0 -2
  56. package/ios/Plugin/cbl-js-swift/MapHelper.swift +0 -25
  57. package/ios/Plugin/cbl-js-swift/QueryHelper.swift +0 -2
  58. package/ios/Plugin/cbl-js-swift/README.md +12 -0
  59. package/ios/Plugin/cbl-js-swift/ReplicatorHelper.swift +116 -5
  60. package/ios/Plugin/cbl-js-swift/ReplicatorManager.swift +0 -2
  61. package/ios/Plugin/cbl-js-swift/URLEndpointListenerManager.swift +154 -0
  62. package/package.json +8 -3
package/CblIonic.podspec CHANGED
@@ -13,6 +13,6 @@ Pod::Spec.new do |s|
13
13
  s.source_files = 'ios/Plugin/**/*.{swift,h,m,c,cc,mm,cpp}'
14
14
  s.ios.deployment_target = '13.0'
15
15
  s.dependency 'Capacitor'
16
- s.dependency 'CouchbaseLite-Swift-Enterprise', '3.2.1'
16
+ s.dependency 'CouchbaseLite-Swift-Enterprise', '3.2.2'
17
17
  s.swift_version = '5.5'
18
18
  end
package/README.md CHANGED
@@ -17,3 +17,15 @@ Full documentation for this project can be found at [Couchbase Lite for Ionic Pl
17
17
 
18
18
  ## Migration
19
19
  See the documentation [migration page](https://cbl-ionic.dev/migration) for more information, video links, etc
20
+
21
+ ---
22
+
23
+ ## 📢 Support Policy
24
+
25
+ We truly appreciate your interest in this project!
26
+ This project is **community-maintained**, which means it's **not officially supported** by our support team.
27
+
28
+ If you need help, have found a bug, or want to contribute improvements, the best place to do that is right here — by [opening a GitHub issue](https://github.com/Couchbase-Ecosystem/cbl-ionic/issues).
29
+ Our support portal is unable to assist with requests related to this project, so we kindly ask that all inquiries stay within GitHub.
30
+
31
+ Your collaboration helps us all move forward together — thank you!
@@ -60,7 +60,7 @@ repositories {
60
60
  dependencies {
61
61
  implementation fileTree(dir: 'libs', include: ['*.jar'])
62
62
  implementation project(':capacitor-android')
63
- implementation "com.couchbase.lite:couchbase-lite-android-ee-ktx:3.2.1"
63
+ implementation "com.couchbase.lite:couchbase-lite-android-ee-ktx:3.2.2"
64
64
  implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
65
65
  implementation 'androidx.core:core-ktx:1.10.1'
66
66
  testImplementation "junit:junit:$junitVersion"
@@ -2,6 +2,7 @@ package cbl.js.kotiln
2
2
  import android.content.Context
3
3
  import com.couchbase.lite.*
4
4
  import com.couchbase.lite.Collection
5
+ import kotlin.random.Random
5
6
 
6
7
  import org.json.JSONObject
7
8
  import java.io.File
@@ -159,15 +160,17 @@ object DatabaseManager {
159
160
  return db?.getScope(scopeName)
160
161
  }
161
162
 
162
- fun openDatabase(databaseName: String, config: JSONObject?, context: Context): Database {
163
+ fun openDatabase(databaseName: String, config: JSONObject?, context: Context): String {
163
164
  synchronized(openDatabases) {
165
+ val nanoId = generateNanoId()
166
+ val uniqueName = "${databaseName}_${nanoId}"
167
+
164
168
  val databaseConfig = buildDatabaseConfiguration(config, context)
165
169
  val newDatabase = Database(databaseName, databaseConfig)
166
- if (openDatabases.containsKey(databaseName)) {
167
- openDatabases.remove(databaseName)
168
- }
169
- openDatabases[databaseName] = newDatabase
170
- return newDatabase
170
+
171
+ openDatabases[uniqueName] = newDatabase
172
+
173
+ return uniqueName
171
174
  }
172
175
  }
173
176
 
@@ -180,4 +183,14 @@ object DatabaseManager {
180
183
  val db = getDatabase(databaseName)
181
184
  return db?.scopes ?: setOf()
182
185
  }
186
+ }
187
+
188
+ fun generateNanoId(size: Int = 21): String {
189
+ val alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
190
+ val nanoId = StringBuilder(size)
191
+ repeat(size) {
192
+ val randomIndex = Random.nextInt(alphabet.length)
193
+ nanoId.append(alphabet[randomIndex])
194
+ }
195
+ return nanoId.toString()
183
196
  }
@@ -0,0 +1,143 @@
1
+ package cbl.js.kotiln
2
+
3
+ import com.couchbase.lite.Collection
4
+ import com.couchbase.lite.ConnectionStatus
5
+ import com.couchbase.lite.URLEndpointListener
6
+ import com.couchbase.lite.URLEndpointListenerConfiguration
7
+ import com.couchbase.lite.TLSIdentity
8
+ import com.couchbase.lite.ListenerPasswordAuthenticator
9
+ import com.getcapacitor.JSObject
10
+ import java.util.UUID
11
+ import java.text.SimpleDateFormat
12
+ import java.util.TimeZone
13
+ import java.util.Base64
14
+
15
+ class URLEndpointListenerManager private constructor() {
16
+ private val listeners = mutableMapOf<String, URLEndpointListener>()
17
+
18
+ companion object {
19
+ val shared: URLEndpointListenerManager by lazy { URLEndpointListenerManager() }
20
+ @JvmStatic
21
+ fun deleteIdentity(label: String) {
22
+ throw UnsupportedOperationException("Delete identity is not implemented")
23
+ }
24
+ }
25
+
26
+ fun createListener(
27
+ collections: Set<Collection>,
28
+ port: Int? = null,
29
+ networkInterface: String? = null,
30
+ disableTLS: Boolean? = null,
31
+ enableDeltaSync: Boolean? = null,
32
+ authenticatorConfig: JSObject? = null,
33
+ tlsIdentityConfig: JSObject? = null
34
+ ): String {
35
+ val config = URLEndpointListenerConfiguration(collections)
36
+ port?.let { config.port = it }
37
+ networkInterface?.let { config.networkInterface = it }
38
+ disableTLS?.let { config.setDisableTls(it) }
39
+ enableDeltaSync?.let { config.setEnableDeltaSync(it) }
40
+ config.tlsIdentity = null
41
+
42
+ // Convert authenticatorConfig (from JS) to a Kotlin Map<String, Any> recursively
43
+ fun toKotlinMap(obj: Any?): Any? {
44
+ return when (obj) {
45
+ is org.json.JSONObject -> {
46
+ obj.keys().asSequence().associateWith { toKotlinMap(obj.get(it)) }
47
+ }
48
+ is org.json.JSONArray -> {
49
+ (0 until obj.length()).map { toKotlinMap(obj.get(it)) }
50
+ }
51
+ else -> obj
52
+ }
53
+ }
54
+
55
+ if (authenticatorConfig != null) {
56
+ val authenticatorConfigMap = toKotlinMap(authenticatorConfig) as Map<String, Any>
57
+ val authenticator = listenerAuthenticatorFromConfig(authenticatorConfigMap)
58
+ config.authenticator = authenticator
59
+ }
60
+ if (tlsIdentityConfig != null) {
61
+ val tlsIdentityConfigMap = toKotlinMap(tlsIdentityConfig) as Map<String, Any>
62
+
63
+ val mode = tlsIdentityConfigMap["mode"] as? String ?: "selfSigned"
64
+ val label = tlsIdentityConfigMap["label"] as? String ?: UUID.randomUUID().toString()
65
+ if (mode == "selfSigned") {
66
+
67
+ val attrs = (tlsIdentityConfigMap["attributes"] as? Map<*, *>)?.mapNotNull {
68
+ (k, v) ->
69
+ if (k is String && v is String) k to v else null
70
+ }?.toMap()?.toMutableMap() ?: mutableMapOf()
71
+
72
+ // Map certAttrCommonName to the correct constant if present
73
+ val commonName = attrs.remove("certAttrCommonName")
74
+ if (commonName != null) {
75
+ attrs[TLSIdentity.CERT_ATTRIBUTE_COMMON_NAME] = commonName
76
+ }
77
+
78
+ val expiration = tlsIdentityConfigMap["expiration"] as? String ?: null
79
+ val expirationDate = expiration?.let {
80
+ val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
81
+ formatter.timeZone = TimeZone.getTimeZone("UTC")
82
+ formatter.parse(it)
83
+ }
84
+ val tlsIdentity = TLSIdentity.createIdentity(true, attrs, expirationDate, label)
85
+ config.tlsIdentity = tlsIdentity
86
+ }
87
+ if (mode == "imported") {
88
+ throw UnsupportedOperationException("Importing TLS identity is not implemented")
89
+ }
90
+ }
91
+
92
+ val listener = URLEndpointListener(config)
93
+ val listenerId = UUID.randomUUID().toString()
94
+ listeners[listenerId] = listener
95
+ return listenerId
96
+ }
97
+
98
+ fun startListener(listenerId: String) {
99
+ val listener = listeners[listenerId]
100
+ ?: throw UnableToFindListenerException(listenerId)
101
+ listener.start()
102
+ }
103
+
104
+ fun stopListener(listenerId: String) {
105
+ val listener = listeners[listenerId]
106
+ ?: throw UnableToFindListenerException(listenerId)
107
+ listener.stop()
108
+ }
109
+
110
+ fun getListenerStatus(listenerId: String): ConnectionStatus? {
111
+ val listener = listeners[listenerId]
112
+ ?: throw UnableToFindListenerException(listenerId)
113
+ return listener.status
114
+ }
115
+
116
+ fun getListenerUrls(listenerId: String): List<String> {
117
+ val listener = listeners[listenerId]
118
+ ?: throw UnableToFindListenerException(listenerId)
119
+ //if listener is not started, urls is null
120
+ if (listener.urls == null || listener.urls.isEmpty()) {
121
+ return emptyList()
122
+ }
123
+ return listener.urls.map { it.toString() }
124
+ }
125
+
126
+ private fun listenerAuthenticatorFromConfig(config: Map<String, Any>): ListenerPasswordAuthenticator? {
127
+ val type = config["type"] as? String ?: return null
128
+ val data = config["data"] as? Map<String, Any> ?: return null
129
+ return when (type) {
130
+ "basic" -> {
131
+ val username = data["username"] as? String ?: return null
132
+ val password = data["password"] as? String ?: return null
133
+ ListenerPasswordAuthenticator { inputUsername, inputPassword ->
134
+ inputUsername == username && String(inputPassword) == password
135
+ }
136
+ }
137
+ else -> null
138
+ }
139
+ }
140
+
141
+ class UnableToFindListenerException(val listenerId: String) :
142
+ Exception("Unable to find listener with id: $listenerId")
143
+ }
@@ -7,6 +7,7 @@ import cbl.js.kotiln.DatabaseManager
7
7
  import cbl.js.kotiln.FileSystemHelper
8
8
  import cbl.js.kotiln.LoggingManager
9
9
  import cbl.js.kotiln.ReplicatorManager
10
+ import cbl.js.kotiln.URLEndpointListenerManager
10
11
  import kotlinx.coroutines.Dispatchers
11
12
  import kotlinx.coroutines.withContext
12
13
 
@@ -16,6 +17,10 @@ import com.getcapacitor.PluginCall
16
17
  import com.getcapacitor.PluginMethod
17
18
  import com.getcapacitor.annotation.CapacitorPlugin
18
19
  import com.couchbase.lite.*
20
+ import com.couchbase.lite.URLEndpointListener
21
+ import com.couchbase.lite.URLEndpointListenerConfiguration
22
+ import com.couchbase.lite.Collection
23
+ import com.couchbase.lite.Database
19
24
  import com.getcapacitor.JSArray
20
25
  import kotlinx.coroutines.DelicateCoroutinesApi
21
26
  import kotlinx.coroutines.GlobalScope
@@ -63,6 +68,8 @@ class CblIonicPluginPlugin : Plugin() {
63
68
  val listenerToken = collection.addChangeListener { change ->
64
69
  val results = JSObject()
65
70
  results.put("documentIDs", JSONArray(change.documentIDs))
71
+ val collectionDictonary = PluginHelper.collectionToJson(collectionDto)
72
+ results.put("collection", collectionDictonary)
66
73
  call.resolve(results)
67
74
  }
68
75
  collectionChangeListeners.put(strToken, listenerToken)
@@ -101,7 +108,7 @@ class CblIonicPluginPlugin : Plugin() {
101
108
  val listenerToken =
102
109
  collection.addDocumentChangeListener(documentId) { change ->
103
110
  val results = JSObject()
104
- results.put("documentID", change.documentID)
111
+ results.put("documentId", change.documentID)
105
112
  results.put("collectionName", change.collection.name)
106
113
  results.put("scopeName", change.collection.scope.name)
107
114
  results.put("databaseName", collectionDto.databaseName)
@@ -596,19 +603,31 @@ class CblIonicPluginPlugin : Plugin() {
596
603
  collectionDto.scopeName,
597
604
  collectionDto.databaseName
598
605
  )
599
- document?.let {
600
- val results = PluginHelper.documentToMap(it)
601
- return@withContext withContext(Dispatchers.Main) {
602
- call.resolve(results)
606
+ withContext(Dispatchers.Main) {
607
+ if (document == null) {
608
+ call.resolve(JSObject())
609
+ return@withContext
610
+ }
611
+ val documentJson = document.toJSON()
612
+ if (!documentJson.isNullOrEmpty()) {
613
+ try {
614
+ val jsonObj = org.json.JSONObject(documentJson)
615
+ val result = JSObject()
616
+ result.put("_data", jsonObj)
617
+ result.put("_id", document.id)
618
+ result.put("_sequence", document.sequence)
619
+ result.put("_revId", document.revisionID)
620
+ call.resolve(result)
621
+ } catch (e: Exception) {
622
+ call.reject("DOCUMENT_ERROR: Failed to parse document JSON: ${e.message}")
623
+ }
624
+ } else {
625
+ call.resolve(JSObject())
603
626
  }
604
- }
605
- return@withContext withContext(Dispatchers.Main) {
606
- val results = JSObject()
607
- call.resolve(results)
608
627
  }
609
628
  } catch (e: Exception) {
610
- return@withContext withContext(Dispatchers.Main) {
611
- call.reject("${e.message}")
629
+ withContext(Dispatchers.Main) {
630
+ call.reject("DOCUMENT_ERROR: ${e.message}")
612
631
  }
613
632
  }
614
633
  }
@@ -1090,9 +1109,9 @@ class CblIonicPluginPlugin : Plugin() {
1090
1109
  name?.let { databaseName ->
1091
1110
  withContext(Dispatchers.IO) {
1092
1111
  try {
1093
- DatabaseManager.openDatabase(databaseName, config, bridge.context)
1112
+ val databaseUniqueName = DatabaseManager.openDatabase(databaseName, config, bridge.context)
1094
1113
  return@withContext withContext(Dispatchers.Main) {
1095
- call.resolve()
1114
+ call.resolve(JSObject().put("databaseUniqueName", databaseUniqueName))
1096
1115
  }
1097
1116
  } catch (e: Exception) {
1098
1117
  return@withContext withContext(Dispatchers.Main) {
@@ -1421,7 +1440,7 @@ class CblIonicPluginPlugin : Plugin() {
1421
1440
  ReplicatorHelper.generateReplicatorStatusJson(change.status)
1422
1441
  call.resolve(result)
1423
1442
  }
1424
- ReplicatorManager.replicatorChangeListeners.put(token, listenerToken)
1443
+ replicationChangeListeners[token] = listenerToken
1425
1444
  }
1426
1445
 
1427
1446
  } catch (e: Exception) {
@@ -1457,7 +1476,7 @@ class CblIonicPluginPlugin : Plugin() {
1457
1476
  ReplicatorHelper.generateReplicatorDocumentChangeJson(change)
1458
1477
  call.resolve(result)
1459
1478
  }
1460
- ReplicatorManager.replicatorChangeListeners.put(token, listenerToken)
1479
+ replicationChangeListeners.put(token, listenerToken)
1461
1480
  }
1462
1481
 
1463
1482
  } catch (e: Exception) {
@@ -1474,17 +1493,23 @@ class CblIonicPluginPlugin : Plugin() {
1474
1493
  call,
1475
1494
  "replicatorId"
1476
1495
  )
1477
- if (isReplicatorIdError || replicatorId.isNullOrEmpty()) {
1496
+ if (isReplicatorIdError || replicatorId.isNullOrEmpty()){
1497
+ call.reject("Error: No replicatorId provided")
1478
1498
  return
1479
1499
  }
1480
1500
  GlobalScope.launch {
1481
1501
  withContext(Dispatchers.IO) {
1482
1502
  try {
1483
- ReplicatorManager.getReplicator(replicatorId)?.let { replicator ->
1484
- replicator.stop()
1485
- ReplicatorManager.removeReplicator(replicatorId)
1486
- }
1503
+ val replicator = ReplicatorManager.getReplicator(replicatorId)
1504
+ replicator?.let {
1505
+ replicationChangeListeners[replicatorId]?.let { listener ->
1506
+ replicator.stop()
1507
+ ReplicatorManager.removeReplicator(replicatorId)
1508
+ replicationChangeListeners.remove(replicatorId)
1509
+ }
1510
+ }
1487
1511
  call.resolve()
1512
+
1488
1513
  } catch (e: Exception) {
1489
1514
  call.reject("${e.message}")
1490
1515
  }
@@ -1634,7 +1659,7 @@ class CblIonicPluginPlugin : Plugin() {
1634
1659
  }
1635
1660
  }
1636
1661
 
1637
- @PluginMethod(returnType = PluginMethod.RETURN_CALLBACK)
1662
+ @PluginMethod(returnType = PluginMethod.RETURN_PROMISE)
1638
1663
  @Throws(JSONException::class)
1639
1664
  fun replicator_RemoveChangeListener(call: PluginCall) {
1640
1665
  val (replicatorId, isReplicatorIdError) = PluginHelper.getStringFromCall(
@@ -1642,24 +1667,26 @@ class CblIonicPluginPlugin : Plugin() {
1642
1667
  "replicatorId"
1643
1668
  )
1644
1669
  val (token, isTokenError) = PluginHelper.getStringFromCall(call, "changeListenerToken")
1645
- if (isReplicatorIdError ||
1646
- replicatorId.isNullOrEmpty() ||
1647
- isTokenError ||
1648
- token.isNullOrEmpty()
1649
- ) {
1670
+ if (isReplicatorIdError || replicatorId.isNullOrEmpty() || isTokenError || token.isNullOrEmpty()) {
1650
1671
  return
1651
1672
  }
1652
1673
  GlobalScope.launch {
1653
1674
  withContext(Dispatchers.IO) {
1654
1675
  try {
1655
- val replicator = ReplicatorManager.getReplicator(replicatorId)
1656
- replicator?.let {
1657
- ReplicatorManager.removeChangeListener(replicatorId, token)
1676
+ if(replicationChangeListeners.isEmpty() || !replicationChangeListeners.containsKey(token)) {
1677
+ call.reject("No such listener found")
1678
+ return@withContext
1658
1679
  }
1680
+
1681
+ replicationChangeListeners[token].let { listener ->
1682
+ ReplicatorManager.removeChangeListener(replicatorId, token)
1683
+ replicationChangeListeners.remove(token)
1684
+ call.resolve()
1685
+ }
1659
1686
  } catch (e: Exception) {
1660
1687
  call.reject("${e.message}")
1661
1688
  }
1662
- }
1689
+ }
1663
1690
  }
1664
1691
  }
1665
1692
 
@@ -1829,4 +1856,133 @@ class CblIonicPluginPlugin : Plugin() {
1829
1856
  }
1830
1857
  }
1831
1858
 
1859
+ @PluginMethod(returnType = PluginMethod.RETURN_PROMISE)
1860
+ fun URLEndpointListener_createListener(call: PluginCall) {
1861
+ val collectionsArray = call.getArray("collections")
1862
+ val (port, isPortError) = PluginHelper.getIntFromCall(call, "port")
1863
+ val (networkInterface, isNetworkInterfaceError) = PluginHelper.getStringFromCall(call, "networkInterface")
1864
+ if (collectionsArray == null || isPortError || port == null || isNetworkInterfaceError || networkInterface.isNullOrEmpty()) {
1865
+ call.reject("Missing required parameters")
1866
+ return
1867
+ }
1868
+ val disableTLS = call.getBoolean("disableTLS") ?: false
1869
+ val enableDeltaSync = call.getBoolean("enableDeltaSync") ?: false
1870
+ val authenticatorConfig = call.getObject("authenticatorConfig") ?: null
1871
+ val tlsIdentityConfig = call.getObject("tlsIdentityConfig") ?: null
1872
+
1873
+ val collections = mutableSetOf<Collection>()
1874
+ for (i in 0 until collectionsArray.length()) {
1875
+ val dict = collectionsArray.getJSONObject(i)
1876
+ val dbName = dict.getString("databaseName")
1877
+ val scopeName = dict.getString("scopeName")
1878
+ val collectionName = dict.getString("name")
1879
+ val db = DatabaseManager.getDatabase(dbName)
1880
+ val scope = db?.getScope(scopeName)
1881
+ val collection = scope?.getCollection(collectionName)
1882
+ if (db == null || scope == null || collection == null) {
1883
+ call.reject("Invalid collection parameters")
1884
+ return
1885
+ }
1886
+ collections.add(collection)
1887
+ }
1888
+
1889
+ try {
1890
+ val listenerId = URLEndpointListenerManager.shared.createListener(
1891
+ collections = collections,
1892
+ port = port,
1893
+ networkInterface = networkInterface,
1894
+ disableTLS = disableTLS,
1895
+ enableDeltaSync = enableDeltaSync,
1896
+ authenticatorConfig = authenticatorConfig,
1897
+ tlsIdentityConfig = tlsIdentityConfig
1898
+ )
1899
+ val result = JSObject()
1900
+ result.put("listenerId", listenerId)
1901
+ call.resolve(result)
1902
+ } catch (e: Exception) {
1903
+ call.reject("Failed to create listener: ${e.localizedMessage}")
1904
+ }
1905
+ }
1906
+
1907
+ @PluginMethod(returnType = PluginMethod.RETURN_PROMISE)
1908
+ fun URLEndpointListener_startListener(call: PluginCall) {
1909
+ val listenerId = call.getString("listenerId")
1910
+ if (listenerId == null) {
1911
+ call.reject("Missing required parameter: 'listenerId'")
1912
+ return
1913
+ }
1914
+ GlobalScope.launch {
1915
+ withContext(Dispatchers.IO) {
1916
+ try {
1917
+ URLEndpointListenerManager.shared.startListener(listenerId)
1918
+ withContext(Dispatchers.Main) {
1919
+ call.resolve()
1920
+ }
1921
+ } catch (e: Exception) {
1922
+ withContext(Dispatchers.Main) {
1923
+ call.reject("Failed to start listener: ${e.localizedMessage}")
1924
+ }
1925
+ }
1926
+ }
1927
+ }
1928
+ }
1929
+
1930
+ @PluginMethod(returnType = PluginMethod.RETURN_PROMISE)
1931
+ fun URLEndpointListener_stopListener(call: PluginCall) {
1932
+ val listenerId = call.getString("listenerId")
1933
+ if (listenerId == null) {
1934
+ call.reject("Missing required parameter: 'listenerId'")
1935
+ return
1936
+ }
1937
+ GlobalScope.launch {
1938
+ withContext(Dispatchers.IO) {
1939
+ try {
1940
+ URLEndpointListenerManager.shared.stopListener(listenerId)
1941
+ withContext(Dispatchers.Main) {
1942
+ call.resolve()
1943
+ }
1944
+ } catch (e: Exception) {
1945
+ withContext(Dispatchers.Main) {
1946
+ call.reject("Failed to stop listener: ${e.localizedMessage}")
1947
+ }
1948
+ }
1949
+ }
1950
+ }
1951
+ }
1952
+
1953
+ @PluginMethod(returnType = PluginMethod.RETURN_PROMISE)
1954
+ fun URLEndpointListener_getStatus(call: PluginCall) {
1955
+ val listenerId = call.getString("listenerId")
1956
+ if (listenerId == null) {
1957
+ call.reject("Missing required parameter: 'listenerId'")
1958
+ return
1959
+ }
1960
+ try {
1961
+ val status = URLEndpointListenerManager.shared.getListenerStatus(listenerId)
1962
+ if (status == null) {
1963
+ call.reject("Listener not found or status unavailable")
1964
+ return
1965
+ }
1966
+ val result = JSObject()
1967
+ result.put("connectionsCount", status.connectionCount)
1968
+ result.put("activeConnectionCount", status.activeConnectionCount)
1969
+ call.resolve(result)
1970
+ } catch (e: Exception) {
1971
+ call.reject("Failed to get listener status: ${e.localizedMessage}")
1972
+ }
1973
+ }
1974
+ @PluginMethod(returnType = PluginMethod.RETURN_PROMISE)
1975
+ fun URLEndpointListener_deleteIdentity(call: PluginCall) {
1976
+ val label = call.getString("label")
1977
+ if (label == null) {
1978
+ call.reject("Missing required parameter: 'label'")
1979
+ return
1980
+ }
1981
+ try {
1982
+ URLEndpointListenerManager.deleteIdentity(label)
1983
+ call.resolve()
1984
+ } catch (e: Exception) {
1985
+ call.reject("Failed to delete identity: ${e.localizedMessage}")
1986
+ }
1987
+ }
1832
1988
  }
@@ -14,44 +14,6 @@ import org.json.JSONObject
14
14
 
15
15
  object PluginHelper {
16
16
 
17
- /**
18
- * Converts a `Document` object to a `JSObject` representation.
19
- *
20
- * This method transforms the given `Document` into a `JSObject` that includes its data, ID, sequence, and revision ID.
21
- * It iterates through the document's map, and if a value is a `Blob`, it replaces it with its properties in the resulting JSON object.
22
- *
23
- * @param document The `Document` object to convert.
24
- * @return A `JSObject` containing the document's data, ID, sequence, and revision ID, or `null` if an error occurs.
25
- * @throws Exception If an error occurs during the conversion process.
26
- */
27
- fun documentToMap(document: Document): JSObject {
28
- try {
29
- val dMap = document.toMap()
30
- val docJson = JSONObject(dMap)
31
- val keys: Iterator<*> = docJson.keys()
32
- while (keys.hasNext()) {
33
- val key = keys.next() as String
34
- val value = dMap[key]
35
- // only replace the value if it's a blob because
36
- // JSONObject will not map in the blob object into the JSON object
37
- // since it's not a supported JSON type
38
- if (value is Blob) {
39
- val blobProps = JSONObject(value.properties)
40
- blobProps.put("raw", JSONArray(value.content))
41
- docJson.put(key, blobProps)
42
- }
43
- }
44
- val docMap = JSObject()
45
- docMap.put("_data", docJson)
46
- docMap.put("_id", document.id)
47
- docMap.put("_sequence", document.sequence)
48
- docMap.put("_revId", document.revisionID)
49
- return docMap
50
- } catch (ex: Exception) {
51
- throw ex
52
- }
53
- }
54
-
55
17
  /**
56
18
  * Converts a JSON string representation of blobs into a map of Blob objects.
57
19
  *
@@ -280,4 +242,31 @@ object PluginHelper {
280
242
  }
281
243
  return Pair(value, false)
282
244
  }
245
+
246
+ /**
247
+ * Converts a `Collection` object to a `JSObject` representation.
248
+ *
249
+ * This method transforms the given `Collection` into a `JSObject` that includes its name, scope, and database name.
250
+ * The resulting JSON object contains the following structure:
251
+ * {
252
+ * "name": "collectionName",
253
+ * "scope": {
254
+ * "name": "scopeName",
255
+ * "databaseName": "databaseName"
256
+ * }
257
+ * }
258
+ *
259
+ * @param collection The `Collection` object to convert.
260
+ * @param databaseName The name of the database to which the collection belongs.
261
+ * @return A `JSObject` containing the collection's name, scope, and database name.
262
+ */
263
+ fun collectionToJson(collection: CollectionDto): JSObject {
264
+ val colResult = JSObject()
265
+ val scopeResult = JSObject()
266
+ colResult.put("name", collection.collectionName)
267
+ scopeResult.put("name", collection.scopeName)
268
+ scopeResult.put("databaseName", collection.databaseName)
269
+ colResult.put("scope", scopeResult)
270
+ return colResult
271
+ }
283
272
  }
@@ -3,6 +3,7 @@ package com.couchbase.ionic
3
3
  import com.couchbase.lite.Parameters
4
4
  import com.getcapacitor.JSObject
5
5
  import java.text.SimpleDateFormat
6
+ import java.util.TimeZone
6
7
 
7
8
  object QueryHelper {
8
9
  fun getQueryParameters(jsObject: JSObject): Parameters {
@@ -32,11 +33,20 @@ object QueryHelper {
32
33
  "date" -> {
33
34
  val dateValue = it.getString(valueKey)
34
35
  dateValue?.let { strValue ->
35
- //
36
- //bug in SDK with Android and Date
37
- val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
36
+ // Check if the date string contains 'Z' (UTC)
37
+ val dateFormat = if (strValue.endsWith("Z")) {
38
+ SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").apply {
39
+ timeZone = TimeZone.getTimeZone("UTC")
40
+ }
41
+ } else {
42
+ // Handle date strings with or without time zone offsets
43
+ SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").apply {
44
+ timeZone = TimeZone.getDefault()
45
+ }
46
+ }
47
+ // Parse the date
38
48
  val date = dateFormat.parse(strValue)
39
- date?.let {d ->
49
+ date?.let { d ->
40
50
  queryParameters.setDate(key, d)
41
51
  }
42
52
  }