diff --git a/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/CallStatsReport.kt b/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/CallStatsReport.kt index 5e565a5868..9ee4f2a7c9 100644 --- a/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/CallStatsReport.kt +++ b/stream-video-android-core/src/main/kotlin/io/getstream/video/android/core/CallStatsReport.kt @@ -16,6 +16,7 @@ package io.getstream.video.android.core +import android.util.Log import io.getstream.video.android.core.call.stats.model.RtcStatsReport import io.getstream.video.android.core.internal.InternalStreamVideoApi import io.getstream.video.android.core.model.StreamPeerType @@ -33,43 +34,42 @@ data class CallStatsReport( ) fun CallStatsReport.toJson(peerType: StreamPeerType): String { - val statsKey: String - val stats: Map? - - if (peerType == StreamPeerType.PUBLISHER) { - statsKey = "publisherStats" - stats = publisher?.origin?.statsMap + val stats: Map? = if (peerType == StreamPeerType.PUBLISHER) { + publisher?.origin?.statsMap } else { - statsKey = "subscriberStats" - stats = subscriber?.origin?.statsMap + subscriber?.origin?.statsMap } - return JSONObject().apply { - put( - statsKey, - JSONArray().also { array -> - stats?.forEach { statsEntry -> - array.put( - JSONObject().apply { - put( - statsEntry.key, - JSONObject().apply { - statsEntry.value.members.forEach { (key, value) -> - put( - key, - try { - JSONObject(value.toString()) - } catch (e: JSONException) { - value - }, - ) - } - }, - ) - }, - ) - } - }, - ) - }.toString(4) + return JSONArray().also { array -> + stats?.forEach { statsEntry -> + array.put( + JSONObject().apply { + // Cannot use statsEntry.value.toString() because it's not valid JSON sometimes + // So we add the properties one by one + put("timestamp", statsEntry.value.timestampUs) + put("id", statsEntry.value.id) + put("type", statsEntry.value.type) + statsEntry.value.members.forEach { (key, value) -> + put( + key, + try { + // Sometimes the member is a JSON string, so we try to parse it + when (value) { + is Array<*> -> JSONArray(value) + is Map<*, *> -> JSONObject(value.toString()) + else -> value // Or we just add the value + } + } catch (e: JSONException) { + Log.d( + "CallStatsReport", + "sendStats. Error for $key with $value: ${e.message}", + ) + "" + }, + ) + } + }, + ) + } + }.toString(2) }