|
| 1 | +package com.ably.chat |
| 2 | + |
| 3 | +import com.google.gson.JsonElement |
| 4 | +import com.google.gson.JsonParser |
| 5 | +import io.ably.lib.realtime.AblyRealtime |
| 6 | +import io.ktor.client.HttpClient |
| 7 | +import io.ktor.client.engine.cio.CIO |
| 8 | +import io.ktor.client.plugins.HttpRequestRetry |
| 9 | +import io.ktor.client.request.get |
| 10 | +import io.ktor.client.request.post |
| 11 | +import io.ktor.client.request.setBody |
| 12 | +import io.ktor.client.statement.HttpResponse |
| 13 | +import io.ktor.client.statement.bodyAsText |
| 14 | +import io.ktor.http.ContentType |
| 15 | +import io.ktor.http.contentType |
| 16 | + |
| 17 | +val client = HttpClient(CIO) { |
| 18 | + install(HttpRequestRetry) { |
| 19 | + retryOnServerErrors(maxRetries = 4) |
| 20 | + exponentialDelay() |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +class Sandbox private constructor(val appId: String, val apiKey: String) { |
| 25 | + companion object { |
| 26 | + suspend fun createInstance(): Sandbox { |
| 27 | + val response: HttpResponse = client.post("https://sandbox-rest.ably.io/apps") { |
| 28 | + contentType(ContentType.Application.Json) |
| 29 | + setBody(loadAppCreationRequestBody().toString()) |
| 30 | + } |
| 31 | + val body = JsonParser.parseString(response.bodyAsText()) |
| 32 | + |
| 33 | + return Sandbox( |
| 34 | + appId = body.asJsonObject["appId"].asString, |
| 35 | + // From JS chat repo at 7985ab7 — "The key we need to use is the one at index 5, which gives enough permissions to interact with Chat and Channels" |
| 36 | + apiKey = body.asJsonObject["keys"].asJsonArray[5].asJsonObject["keyStr"].asString, |
| 37 | + ) |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +internal fun Sandbox.createSandboxChatClient(): DefaultChatClient { |
| 43 | + val realtime = createSandboxRealtime(apiKey) |
| 44 | + return DefaultChatClient(realtime, ClientOptions()) |
| 45 | +} |
| 46 | + |
| 47 | +internal fun Sandbox.createSandboxRealtime(chatClientId: String = "sandbox-client"): AblyRealtime = |
| 48 | + AblyRealtime( |
| 49 | + io.ably.lib.types.ClientOptions().apply { |
| 50 | + key = apiKey |
| 51 | + environment = "sandbox" |
| 52 | + clientId = chatClientId |
| 53 | + }, |
| 54 | + ) |
| 55 | + |
| 56 | +private suspend fun loadAppCreationRequestBody(): JsonElement = |
| 57 | + JsonParser.parseString( |
| 58 | + client.get("https://raw.githubusercontent.com/ably/ably-common/refs/heads/main/test-resources/test-app-setup.json") { |
| 59 | + contentType(ContentType.Application.Json) |
| 60 | + }.bodyAsText(), |
| 61 | + ).asJsonObject.get("post_apps") |
0 commit comments