Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RoomMessageEvent #76

Merged
merged 10 commits into from
May 17, 2022
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 22 additions & 15 deletions src/main/kotlin/io/kuzzle/sdk/Kuzzle.kt
Original file line number Diff line number Diff line change
Expand Up @@ -60,51 +60,58 @@ open class Kuzzle {
if (event.requestId != null && queries[event.requestId!!] != null) {
queries[event.requestId!!]?.completeExceptionally(event.exception)
queries.remove(event.requestId!!)
} else {
protocol.trigger(UnhandledExceptionEvent(event.exception))
}
}

private fun onMessageReceived(event: MessageReceivedEvent) {
val message = event.message
val jsonObject: Map<String?, Any?>
var jsonObject: Map<String?, Any?>
try {
jsonObject = JsonSerializer.deserialize(message) as Map<String?, Any?>
} catch (e: Exception) {
if (event.requestId != null) {
queries[event.requestId]?.completeExceptionally(InvalidJSON(event.message ?: "null"))
queries.remove(event.requestId)
} else {
protocol.trigger(UnhandledResponseEvent(message))
protocol.trigger(UnhandledExceptionEvent(InvalidJSON(event.message ?: "null")))
}
return
}

// If the message is empty, we take the requestId of the event,
// to avoid error in fromMap function.
if (! jsonObject.containsKey("requestId") && event.requestId != null) {
jsonObject = jsonObject.plus("requestId" to event.requestId)
}

val response = Response().apply {
fromMap(jsonObject)
}

val requestId = event.requestId ?: response.room ?: response.requestId

if (queries.size == 0 || requestId == null || queries[requestId] == null) {
protocol.trigger(UnhandledResponseEvent(message))
return
if (response.error?.id == "security.token.expired") {
protocol.trigger(TokenExpiredEvent())
}

if (response.error == null) {
queries[requestId]?.complete(response)
queries.remove(requestId)
if (queries.size == 0 || requestId == null || queries[requestId] == null) {
OlivierCavadenti marked this conversation as resolved.
Show resolved Hide resolved
if (response.error != null) {
protocol.trigger(UnhandledExceptionEvent(ApiErrorException(response)))
return
}
protocol.trigger(RoomMessageEvent(response))
return
}

if (response.error?.id == null ||
response.error?.id != "security.token.expired"
) {
if (response.error != null) {
queries[requestId]?.completeExceptionally(ApiErrorException(response))
queries.remove(requestId)
return
} else {
queries[requestId]?.complete(response)
}

queries[requestId]?.completeExceptionally(ApiErrorException(response))
queries.remove(requestId)
protocol.trigger(TokenExpiredEvent())
}

private fun onNetworkStateChange(event: NetworkStateChangeEvent) {
Expand Down
36 changes: 15 additions & 21 deletions src/main/kotlin/io/kuzzle/sdk/controllers/RealtimeController.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package io.kuzzle.sdk.controllers

import io.kuzzle.sdk.Kuzzle
import io.kuzzle.sdk.coreClasses.json.JsonSerializer
import io.kuzzle.sdk.coreClasses.maps.KuzzleMap
import io.kuzzle.sdk.coreClasses.responses.Response
import io.kuzzle.sdk.events.NetworkStateChangeEvent
import io.kuzzle.sdk.events.TokenExpiredEvent
import io.kuzzle.sdk.events.RoomMessageEvent
import io.kuzzle.sdk.events.UnhandledResponseEvent
import io.kuzzle.sdk.handlers.NotificationHandler
import io.kuzzle.sdk.protocol.ProtocolState
Expand All @@ -25,32 +24,27 @@ class RealtimeController(kuzzle: Kuzzle) : BaseController(kuzzle) {
)

init {
kuzzle.protocol.addListener<UnhandledResponseEvent>() {
val response = Response().apply {
fromMap(JsonSerializer.deserialize(it.message) as Map<String?, Any?>)
kuzzle.protocol.addListener<RoomMessageEvent> {
val response = it.response
var sdkInstanceId = ""
if (response.Volatile != null) {
sdkInstanceId = response.Volatile!!["sdkInstanceId"].toString()
}

if (response.error != null && response.error!!.id.equals("security.token.expired")) {
kuzzle.protocol.trigger(TokenExpiredEvent())
} else {
var sdkInstanceId = ""
if (response.Volatile != null) {
sdkInstanceId = response.Volatile!!["sdkInstanceId"].toString()
}

val subs: ArrayList<Subscription>? = currentSubscriptions[response.room]
if (subs != null) {
val instanceId = sdkInstanceId
subs.forEach {
if (instanceId == kuzzle.instanceId && it.subscribeToSelf || instanceId != kuzzle.instanceId) {
it.handler(response)
}
val subs: ArrayList<Subscription>? = currentSubscriptions[response.room]
if (subs != null) {
val instanceId = sdkInstanceId
OlivierCavadenti marked this conversation as resolved.
Show resolved Hide resolved
subs.forEach {
if (instanceId == kuzzle.instanceId && it.subscribeToSelf || instanceId != kuzzle.instanceId) {
it.handler(response)
}
}
} else {
kuzzle.protocol.trigger(UnhandledResponseEvent(response))
}
}

kuzzle.protocol.addListener<NetworkStateChangeEvent>() {
kuzzle.protocol.addListener<NetworkStateChangeEvent> {
if (it.state == ProtocolState.CLOSE) {
currentSubscriptions.clear()
}
Expand Down
30 changes: 25 additions & 5 deletions src/main/kotlin/io/kuzzle/sdk/coreClasses/http/Route.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.kuzzle.sdk.coreClasses.http

import io.kuzzle.sdk.coreClasses.exceptions.MissingURLParamException
import io.kuzzle.sdk.coreClasses.json.JsonSerializer
import io.kuzzle.sdk.coreClasses.maps.KuzzleMap
import io.kuzzle.sdk.coreClasses.serializer.StringSerializer
import java.net.URLEncoder
Expand Down Expand Up @@ -63,7 +64,6 @@ class Route {
*/
fun buildRequest(request: KuzzleMap): HttpRequest {
val headers = request.optMap("headers", KuzzleMap())

val queryArgs = KuzzleMap()
for (key: String? in request.keys) {
// Skip if a key or value is null
Expand All @@ -78,7 +78,13 @@ class Route {
"headers" -> headers.putAll(request.optMap("headers", KuzzleMap()))
"body" -> {
if (verb == "GET") {
queryArgs.putAll(request.optMap("body", KuzzleMap()))
var body = request["body"]
if (body != null) {
if (body !is Map<*, *>) {
body = JsonSerializer.deserialize(JsonSerializer.serialize(body))
}
queryArgs.putAll(body as Map<String?, Any?>)
}
}
}
else -> {
Expand All @@ -88,7 +94,6 @@ class Route {
}
}
}

/**
* Build the query string
*/
Expand All @@ -113,7 +118,7 @@ class Route {
return HttpRequest(
verb,
if (queryArgs.isEmpty()) staticURL else "$staticURL?$queryString",
if (verb != "GET") request.optMap("body", KuzzleMap()) else null,
if (verb != "GET") getBody(request) else null,
headers
)
}
Expand All @@ -138,11 +143,26 @@ class Route {
return HttpRequest(
verb,
if (queryArgs.isEmpty()) urlBuilder.toString() else "$urlBuilder?$queryString",
if (verb != "GET") request.optMap("body", KuzzleMap()) else null,
if (verb != "GET") getBody(request) else null,
headers
)
}

private fun getBody(request: KuzzleMap): KuzzleMap {
return when (val body = request["body"]) {
null -> {
KuzzleMap()
}
// If it's not a map, it can be a RawJson or Serializable object.
!is Map<*, *> -> {
KuzzleMap.from(JsonSerializer.deserialize(JsonSerializer.serialize(body)) as Map<String?, Any?>)
}
else -> {
KuzzleMap.from(body as Map<String?, Any?>)
}
}
}

companion object {
/**
* Parse Kuzzle url with the format /:index/:collection
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ package io.kuzzle.sdk.coreClasses.json
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import io.kuzzle.sdk.coreClasses.RequestPayload
import io.kuzzle.sdk.coreClasses.maps.KuzzleMap

object JsonSerializer {
private var gson: Gson? = null
fun deserialize(rawJson: String?): Map<*, *> {
return gson!!.fromJson(rawJson, Map::class.java)
return if (rawJson == null || rawJson.isBlank()) {
KuzzleMap()
} else {
gson!!.fromJson(rawJson, Map::class.java)
}
}

fun serialize(obj: Any): String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class KuzzleMap : HashMap<String?, Any?> {
/**
* Create a new instance of CustomMap
*/
constructor() : super() {}
constructor() : super()

/**
* Create a new instance of CustomMap from a Map<String></String>,
Expand Down
5 changes: 5 additions & 0 deletions src/main/kotlin/io/kuzzle/sdk/events/RoomMessageEvent.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package io.kuzzle.sdk.events

import io.kuzzle.sdk.coreClasses.responses.Response

data class RoomMessageEvent(val response: Response)
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package io.kuzzle.sdk.events

data class UnhandledExceptionEvent(val exception: Exception)
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
package io.kuzzle.sdk.events

data class UnhandledResponseEvent(var message: String?)
import io.kuzzle.sdk.coreClasses.responses.Response

data class UnhandledResponseEvent(var message: Response?)